1 | /** |
2 | * Licensed to jclouds, Inc. (jclouds) under one or more |
3 | * contributor license agreements. See the NOTICE file |
4 | * distributed with this work for additional information |
5 | * regarding copyright ownership. jclouds licenses this file |
6 | * to you under the Apache License, Version 2.0 (the |
7 | * "License"); you may not use this file except in compliance |
8 | * with the License. You may obtain a copy of the License at |
9 | * |
10 | * http://www.apache.org/licenses/LICENSE-2.0 |
11 | * |
12 | * Unless required by applicable law or agreed to in writing, |
13 | * software distributed under the License is distributed on an |
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
15 | * KIND, either express or implied. See the License for the |
16 | * specific language governing permissions and limitations |
17 | * under the License. |
18 | */ |
19 | package org.jclouds.ovf.xml; |
20 | |
21 | import static org.jclouds.util.SaxUtils.currentOrNull; |
22 | import static org.jclouds.util.SaxUtils.equalsOrSuffix; |
23 | |
24 | import javax.inject.Provider; |
25 | |
26 | import org.jclouds.http.functions.ParseSax; |
27 | import org.jclouds.ovf.Section; |
28 | import org.jclouds.ovf.Section.Builder; |
29 | |
30 | /** |
31 | * @author Adrian Cole |
32 | */ |
33 | public class SectionHandler<T extends Section<T>, B extends Section.Builder<T>> extends ParseSax.HandlerWithResult<T> { |
34 | @SuppressWarnings("unchecked") |
35 | public static SectionHandler create() { |
36 | return new SectionHandler(new Provider<Section.Builder>() { |
37 | |
38 | @Override |
39 | public Builder get() { |
40 | return new Section.Builder(); |
41 | } |
42 | |
43 | }); |
44 | } |
45 | |
46 | protected final Provider<? extends Section.Builder<T>> builderProvider; |
47 | protected StringBuilder currentText = new StringBuilder(); |
48 | protected B builder; |
49 | |
50 | public SectionHandler(Provider<B> builderProvider) { |
51 | this.builderProvider = builderProvider; |
52 | this.builder = builderProvider.get(); |
53 | } |
54 | |
55 | @SuppressWarnings("unchecked") |
56 | public T getResult() { |
57 | try { |
58 | return (T) builder.build(); |
59 | } finally { |
60 | builder = (B) builderProvider.get(); |
61 | } |
62 | } |
63 | |
64 | @Override |
65 | public void endElement(String uri, String localName, String qName) { |
66 | if (equalsOrSuffix(qName, "Info")) { |
67 | builder.info(currentOrNull(currentText)); |
68 | } |
69 | currentText = new StringBuilder(); |
70 | } |
71 | |
72 | public void characters(char ch[], int start, int length) { |
73 | currentText.append(ch, start, length); |
74 | } |
75 | } |