ad440c4f083d909fe677890105c6ebab9ca4208a
[vfc/nfvo/catalog.git] /
1 /**
2  * Copyright 2016 ZTE Corporation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openo.commontosca.catalog.model.externalservice.container;
17
18 import org.xml.sax.Attributes;
19 import org.xml.sax.SAXException;
20 import org.xml.sax.helpers.XMLFilterImpl;
21
22 /**
23  * NamespaceFilter.
24  * 
25  * @author 10189609
26  * 
27  */
28 public class NamespaceFilter extends XMLFilterImpl {
29
30   private String usedNamespaceUri;
31   private boolean addNamespace;
32
33   // State variable
34   private boolean addedNamespace = false;
35
36   /**
37    * constructor.
38    * @param namespaceUri namspace uri
39    * @param addNamespace add namespace or not
40    */
41   public NamespaceFilter(String namespaceUri, boolean addNamespace) {
42     super();
43
44     if (addNamespace) {
45       this.usedNamespaceUri = namespaceUri;
46     } else {
47       this.usedNamespaceUri = "";
48     }
49     this.addNamespace = addNamespace;
50   }
51
52
53
54   @Override
55   public void startDocument() throws SAXException {
56     super.startDocument();
57     if (addNamespace) {
58       startControlledPrefixMapping();
59     }
60   }
61
62
63
64   @Override
65   public void startElement(String arg0, String arg1, String arg2, Attributes arg3)
66       throws SAXException {
67
68     super.startElement(this.usedNamespaceUri, arg1, arg2, arg3);
69   }
70
71   @Override
72   public void endElement(String arg0, String arg1, String arg2) throws SAXException {
73
74     super.endElement(this.usedNamespaceUri, arg1, arg2);
75   }
76
77   @Override
78   public void startPrefixMapping(String prefix, String url) throws SAXException {
79
80
81     if (addNamespace) {
82       this.startControlledPrefixMapping();
83     } else {
84       // Remove the namespace, i.e. donĀ“t call startPrefixMapping for parent!
85     }
86
87   }
88
89   private void startControlledPrefixMapping() throws SAXException {
90
91     if (this.addNamespace && !this.addedNamespace) {
92       // We should add namespace since it is set and has not yet been done.
93       super.startPrefixMapping("", this.usedNamespaceUri);
94
95       // Make sure we dont do it twice
96       this.addedNamespace = true;
97     }
98   }
99
100 }