585240d320dea35736c8acc8c2c15daedfc0648f
[vfc/nfvo/catalog.git] /
1 /**
2  * Copyright 2016 [ZTE] and others.
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
17 package org.openo.commontosca.catalog.model.externalservice.container;
18
19 import org.xml.sax.Attributes;
20 import org.xml.sax.SAXException;
21 import org.xml.sax.helpers.XMLFilterImpl;
22
23 /**
24  * NamespaceFilter.
25  * 
26  * @author 10189609
27  * 
28  */
29 public class NamespaceFilter extends XMLFilterImpl {
30
31   private String usedNamespaceUri;
32   private boolean addNamespace;
33
34   // State variable
35   private boolean addedNamespace = false;
36
37   /**
38    * constructor.
39    * @param namespaceUri namspace uri
40    * @param addNamespace add namespace or not
41    */
42   public NamespaceFilter(String namespaceUri, boolean addNamespace) {
43     super();
44
45     if (addNamespace) {
46       this.usedNamespaceUri = namespaceUri;
47     } else {
48       this.usedNamespaceUri = "";
49     }
50     this.addNamespace = addNamespace;
51   }
52
53
54
55   @Override
56   public void startDocument() throws SAXException {
57     super.startDocument();
58     if (addNamespace) {
59       startControlledPrefixMapping();
60     }
61   }
62
63
64
65   @Override
66   public void startElement(String arg0, String arg1, String arg2, Attributes arg3)
67       throws SAXException {
68
69     super.startElement(this.usedNamespaceUri, arg1, arg2, arg3);
70   }
71
72   @Override
73   public void endElement(String arg0, String arg1, String arg2) throws SAXException {
74
75     super.endElement(this.usedNamespaceUri, arg1, arg2);
76   }
77
78   @Override
79   public void startPrefixMapping(String prefix, String url) throws SAXException {
80
81
82     if (addNamespace) {
83       this.startControlledPrefixMapping();
84     } else {
85       // Remove the namespace, i.e. donĀ“t call startPrefixMapping for parent!
86     }
87
88   }
89
90   private void startControlledPrefixMapping() throws SAXException {
91
92     if (this.addNamespace && !this.addedNamespace) {
93       // We should add namespace since it is set and has not yet been done.
94       super.startPrefixMapping("", this.usedNamespaceUri);
95
96       // Make sure we dont do it twice
97       this.addedNamespace = true;
98     }
99   }
100
101 }