Debian Codegraph @

src/com/google/javascript/jscomp/XtbMessageBundle.java

raw symbols SCIP
1 /*
2 * Copyright 2006 The Closure Compiler Authors.
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 com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.collect.Iterables;
21 import com.google.common.collect.Maps;
22
23 import org.xml.sax.Attributes;
24 import org.xml.sax.ContentHandler;
25 import org.xml.sax.EntityResolver;
26 import org.xml.sax.InputSource;
27 import org.xml.sax.Locator;
28 import org.xml.sax.SAXException;
29 import org.xml.sax.XMLReader;
30
31 import java.io.*;
32 import java.util.*;
33
34 import javax.annotation.Nullable;
35 import javax.xml.XMLConstants;
36 import javax.xml.parsers.ParserConfigurationException;
37 import javax.xml.parsers.SAXParser;
38 import javax.xml.parsers.SAXParserFactory;
39
40 /**
41 * A MessageBundle that parses messages from an XML Translation Bundle (XTB)
42 * file.
43 *
44 */
45 @SuppressWarnings("sunapi")
46 public class XtbMessageBundle implements MessageBundle {
47 private static final SecureEntityResolver NOOP_RESOLVER
48 = new SecureEntityResolver();
49
50 private final Map<String, JsMessage> messages;
51 private final JsMessage.IdGenerator idGenerator;
52
53 public XtbMessageBundle(
54 InputStream xtb, @Nullable String projectId,
55 @SuppressWarnings("unused") boolean unused) {
56 this(xtb, projectId);
57 }
58
59 /**
60 * Creates an instance and initializes it with the messages in an XTB file.
61 *
62 * @param xtb the XTB file as a byte stream
63 * @param projectId the translation console project id (i.e. name)
64 */
65 public XtbMessageBundle(InputStream xtb, @Nullable String projectId) {
66 Preconditions.checkState(!"".equals(projectId));
67 this.messages = Maps.newHashMap();
68 this.idGenerator = new GoogleJsMessageIdGenerator(projectId);
69
70 try {
71 // Use a SAX parser for speed and less memory usage.
72 SAXParser parser = createSAXParser();
73 XMLReader reader = parser.getXMLReader();
74 Handler contentHandler = new Handler();
75 reader.setContentHandler(contentHandler);
76 reader.parse(new InputSource(xtb));
77 } catch (ParserConfigurationException e) {
78 throw new RuntimeException(e);
79 } catch (SAXException e) {
80 throw new RuntimeException(e);
81 } catch (IOException e) {
82 throw new RuntimeException(e);
83 }
84 }
85
86 // Inlined from guava-internal.
87 private SAXParser createSAXParser()
88 throws ParserConfigurationException, SAXException {
89 SAXParserFactory factory = SAXParserFactory.newInstance();
90 factory.setValidating(false);
91 factory.setXIncludeAware(false);
92 factory.setFeature(
93 "http://xml.org/sax/features/external-general-entities", false);
94 factory.setFeature(
95 "http://xml.org/sax/features/external-parameter-entities",false);
96 factory.setFeature(
97 "http://apache.org/xml/features/nonvalidating/load-external-dtd",
98 false);
99 factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
100
101 SAXParser parser = factory.newSAXParser();
102 XMLReader xmlReader = parser.getXMLReader();
103 xmlReader.setEntityResolver(NOOP_RESOLVER);
104 return parser;
105 }
106
107 @Override
108 public JsMessage getMessage(String id) {
109 return messages.get(id);
110 }
111
112 @Override
113 public JsMessage.IdGenerator idGenerator() {
114 return idGenerator;
115 }
116
117 @Override
118 public Iterable<JsMessage> getAllMessages() {
119 return Iterables.unmodifiableIterable(messages.values());
120 }
121
122 /**
123 * A {@link ContentHandler} that creates a {@link JsMessage} for each message
124 * parsed from an XML Translation Bundle (XTB) file.
125 */
126 private class Handler implements ContentHandler {
127 private static final String BUNDLE_ELEM_NAME = "translationbundle";
128 private static final String LANG_ATT_NAME = "lang";
129
130 private static final String TRANSLATION_ELEM_NAME = "translation";
131 private static final String MESSAGE_ID_ATT_NAME = "id";
132
133 private static final String PLACEHOLDER_ELEM_NAME = "ph";
134 private static final String PLACEHOLDER_NAME_ATT_NAME = "name";
135
136 String lang;
137 JsMessage.Builder msgBuilder;
138
139 @Override
140 public void setDocumentLocator(Locator locator) {}
141
142 @Override
143 public void startDocument() {}
144
145 @Override
146 public void endDocument() {}
147
148 @Override
149 public void startPrefixMapping(String prefix, String uri) {}
150
151 @Override
152 public void endPrefixMapping(String prefix) {}
153
154 @Override
155 public void startElement(String uri, String localName, String qName,
156 Attributes atts) {
157 if (BUNDLE_ELEM_NAME.equals(qName)) {
158 Preconditions.checkState(lang == null);
159 lang = atts.getValue(LANG_ATT_NAME);
160 Preconditions.checkState(lang != null && !lang.isEmpty());
161 } else if (TRANSLATION_ELEM_NAME.equals(qName)) {
162 Preconditions.checkState(msgBuilder == null);
163 String id = atts.getValue(MESSAGE_ID_ATT_NAME);
164 Preconditions.checkState(id != null && !id.isEmpty());
165 msgBuilder = new JsMessage.Builder(id);
166 } else if (PLACEHOLDER_ELEM_NAME.equals(qName)) {
167 Preconditions.checkState(msgBuilder != null);
168 String phRef = atts.getValue(PLACEHOLDER_NAME_ATT_NAME);
169 phRef = JsMessageVisitor.toLowerCamelCaseWithNumericSuffixes(phRef);
170 msgBuilder.appendPlaceholderReference(phRef);
171 }
172 }
173
174 @Override
175 public void endElement(String uri, String localName, String qName) {
176 if (TRANSLATION_ELEM_NAME.equals(qName)) {
177 Preconditions.checkState(msgBuilder != null);
178 if (!msgBuilder.hasParts()) {
179 msgBuilder.appendStringPart("");
180 }
181 String key = msgBuilder.getKey();
182 messages.put(key, msgBuilder.build());
183 msgBuilder = null;
184 }
185 }
186
187 @Override
188 public void characters(char ch[], int start, int length) {
189 if (msgBuilder != null) {
190 // Append a string literal to the message.
191 msgBuilder.appendStringPart(String.valueOf(ch, start, length));
192 }
193 }
194
195 @Override
196 public void ignorableWhitespace(char ch[], int start, int length) {
197 if (msgBuilder != null) {
198 // Preserve whitespace in messages.
199 msgBuilder.appendStringPart(String.valueOf(ch, start, length));
200 }
201 }
202
203 @Override
204 public void processingInstruction(String target, String data) {}
205
206 @Override
207 public void skippedEntity(String name) {}
208 }
209
210 /**
211 * A secure EntityResolver that returns an empty string in response to
212 * any attempt to resolve an external entity. The class is used by our
213 * secure version of the internal saxon SAX parser.
214 */
215 private static final class SecureEntityResolver implements EntityResolver {
216
217 @Override
218 public InputSource resolveEntity(String publicId, String systemId) {
219 return new InputSource(new StringReader(""));
220 }
221 }
222 }