List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser
public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;
From source file:com.mindquarry.desktop.I18N.java
protected static Map<String, String> initTranslationMap(String fileBase, String fileSuffix) { try {/*from www .j a v a2 s. co m*/ SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setValidating(false); SAXParser parser = parserFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); TranslationMessageParser translationParser = new TranslationMessageParser(); reader.setContentHandler(translationParser); reader.setErrorHandler(translationParser); // TODO: use "xx_YY" if available, use "xx" otherwise: String transFile = fileBase + Locale.getDefault().getLanguage() + fileSuffix; InputStream is = I18N.class.getResourceAsStream(transFile); if (is == null) { // no translation available for this language log.debug("No translation file available for language: " + Locale.getDefault().getLanguage()); return new HashMap<String, String>(); } log.debug("Loading translation file " + transFile + " from JAR"); reader.parse(new InputSource(is)); return translationParser.getMap(); } catch (Exception e) { throw new RuntimeException(e.toString(), e); } }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java
/** * Reads the configuration and invokes the (SAX-based) parser to parse the configuration file contents. * * @param config/*ww w. j av a 2 s .c o m*/ * input stream to get configuration data from * @param validate * flag indicating whether to validate configuration XML against XSD schema * @return streams configuration data * @throws ParserConfigurationException * if there is an inconsistency in the configuration * @throws SAXException * if there was an error parsing the configuration * @throws IOException * if there is an error reading the configuration data */ public static StreamsConfigData parse(InputStream config, boolean validate) throws ParserConfigurationException, SAXException, IOException { if (validate) { config = config.markSupported() ? config : new ByteArrayInputStream(IOUtils.toByteArray(config)); Map<OpLevel, List<SAXParseException>> validationErrors = validate(config); if (MapUtils.isNotEmpty(validationErrors)) { for (Map.Entry<OpLevel, List<SAXParseException>> vee : validationErrors.entrySet()) { for (SAXParseException ve : vee.getValue()) { LOGGER.log(OpLevel.WARNING, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "StreamsConfigSAXParser.xml.validation.error"), ve.getLineNumber(), ve.getColumnNumber(), vee.getKey(), ve.getLocalizedMessage()); } } } } Properties p = Utils.loadPropertiesResource("sax.properties"); // NON-NLS SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); ConfigParserHandler hndlr = null; try { String handlerClassName = p.getProperty(HANDLER_PROP_KEY, ConfigParserHandler.class.getName()); if (StringUtils.isNotEmpty(handlerClassName)) { hndlr = (ConfigParserHandler) Utils.createInstance(handlerClassName); } } catch (Exception exc) { } if (hndlr == null) { hndlr = new ConfigParserHandler(); } parser.parse(config, hndlr); return hndlr.getStreamsConfigData(); }
From source file:mcp.tools.nmap.parser.NmapXmlParser.java
public static void parse(File xmlResultsFile, String scanDescription, String commandLine) { Pattern endTimePattern = Pattern.compile("<runstats><finished time=\"(\\d+)"); String xmlResults;/* ww w . j a v a 2s . com*/ try { xmlResults = FileUtils.readFileToString(xmlResultsFile); } catch (IOException e) { logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': " + e.getLocalizedMessage(), e); return; } Matcher m = endTimePattern.matcher(xmlResults); Instant scanTime = null; if (m.find()) { int t; try { t = Integer.parseInt(m.group(1)); scanTime = Instant.ofEpochSecond(t); } catch (NumberFormatException e) { } } if (scanTime == null) { logger.debug("Failed to find scan completion time in nmap results. Using current time."); scanTime = Instant.now(); } String path; try { path = xmlResultsFile.getCanonicalPath(); } catch (IOException e1) { logger.debug("Why did the canonical path fail?"); path = xmlResultsFile.getAbsolutePath(); } NmapScanSource source = new NmapScanSourceImpl(path, scanDescription, commandLine); NMapXmlHandler nmxh = new NMapXmlHandler(scanTime, source); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp; try { sp = spf.newSAXParser(); } catch (ParserConfigurationException e) { throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e); } catch (SAXException e) { throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e); } try { sp.parse(xmlResultsFile, nmxh); } catch (SAXException e) { logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': " + e.getLocalizedMessage(), e); return; } catch (IOException e) { logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': " + e.getLocalizedMessage(), e); return; } }
From source file:Main.java
@SuppressWarnings("unchecked") public static <T> T readXMLFromString(Class<?> class1, String content) throws JAXBException, FileNotFoundException, SAXException, ParserConfigurationException { JAXBContext context = JAXBContext.newInstance(class1); Unmarshaller um = context.createUnmarshaller(); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); spf.setFeature("http://xml.org/sax/features/validation", false); XMLReader xr = (XMLReader) spf.newSAXParser().getXMLReader(); try (StringReader reader = new StringReader(content)) { SAXSource source = new SAXSource(xr, new InputSource(reader)); T obj = (T) um.unmarshal(source); return obj; }/*from w ww . j av a 2 s .co m*/ }
From source file:Main.java
public static void saxParserValidation(InputStream streamDaValidare, InputStream inputSchema, DefaultHandler handler) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true);//from www . j a v a 2s. co m if (inputSchema != null) { factory.setValidating(true); } else { factory.setValidating(false); } SAXParser parser = factory.newSAXParser(); if (inputSchema != null) { parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); parser.setProperty(JAXP_SCHEMA_SOURCE, inputSchema); } parser.parse(streamDaValidare, handler); }
From source file:Main.java
@SuppressWarnings("unchecked") public static <T> T readXML(Class<?> class1, File file) throws JAXBException, IOException, SAXException, ParserConfigurationException { JAXBContext context = JAXBContext.newInstance(class1); Unmarshaller um = context.createUnmarshaller(); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); spf.setFeature("http://xml.org/sax/features/validation", false); XMLReader xr = (XMLReader) spf.newSAXParser().getXMLReader(); try (FileReader reader = new FileReader(file)) { SAXSource source = new SAXSource(xr, new InputSource(reader)); T obj = (T) um.unmarshal(source); return obj; }/*from ww w .ja v a2s . c om*/ }
From source file:org.epics.archiverappliance.retrieval.channelarchiver.XMLRPCClient.java
/** * Internal method to make a XML_RPC post call and call the SAX handler on the returned document. * @param serverURL The Server URL//from w w w.ja v a 2 s . c o m * @param handler DefaultHandler * @param postEntity StringEntity * @throws IOException   * @throws SAXException   */ private static void doHTTPPostAndCallSAXHandler(String serverURL, DefaultHandler handler, StringEntity postEntity) throws IOException, SAXException { logger.debug("Executing doHTTPPostAndCallSAXHandler with the server URL " + serverURL); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(serverURL); postMethod.addHeader("Content-Type", "text/xml"); postMethod.setEntity(postEntity); logger.debug("Executing the HTTP POST" + serverURL); HttpResponse response = httpclient.execute(postMethod); HttpEntity entity = response.getEntity(); if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); try (InputStream is = entity.getContent()) { SAXParserFactory sfac = SAXParserFactory.newInstance(); sfac.setNamespaceAware(false); sfac.setValidating(false); SAXParser parser = sfac.newSAXParser(); parser.parse(is, handler); } catch (ParserConfigurationException pex) { throw new IOException(pex); } } else { throw new IOException("HTTP response did not have an entity associated with it"); } }
From source file:Main.java
public static Set<String> compareXmlFiles(String firstFolderPath, String secondFolderPath, boolean outConsole) { Set<String> identicalFiles = new HashSet<String>(); File firstFolder = new File(firstFolderPath); File secondFolder = new File(secondFolderPath); Map<String, File> firstFileMap = new HashMap<String, File>(); Map<String, File> secondFileMap = new HashMap<String, File>(); traverseFolder(firstFileMap, firstFolder, firstFolder); traverseFolder(secondFileMap, secondFolder, secondFolder); // temporarily - comparison by MD5 instead of XML parsing SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = null;//from w ww . j a v a 2 s.c o m try { saxParser = factory.newSAXParser(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } System.out.println("Parser: " + saxParser); Set<String> sourceKeys = firstFileMap.keySet(); Set<String> destKeys = secondFileMap.keySet(); for (String key1 : sourceKeys) { File file1 = firstFileMap.get(key1); File file2 = secondFileMap.get(key1); if (file1 != null && file2 != null) { try { String node1 = calculateMd5Checksum(file1.getCanonicalPath()); String node2 = calculateMd5Checksum(file2.getCanonicalPath()); // System.out.println("Source:" + node1 + " Dest:" + node2); if (node1.equals(node2)) { firstFileMap.remove(key1); secondFileMap.remove(key1); } } catch (Exception ex) { ex.printStackTrace(); // can be ignored } } } for (String key1 : sourceKeys) { if (destKeys.contains(key1)) { identicalFiles.add(key1); sourceKeys.remove(key1); destKeys.remove(key1); } } if (outConsole == true) { } return identicalFiles; }
From source file:Main.java
/** * Helper method to unmarshall a xml doc * @see http://docs.oracle.com/javase/tutorial/jaxb/intro/basic.html * http://jaxb.java.net/nonav/2.2.6/docs/ch03.html#unmarshalling * this uses <T> JAXBElement<T> unmarshal(Source source, Class<T> declaredType) throws JAXBException//from w w w. j a va2 s .co m * */ /* public static <T> T unmarshall(Class<T> docClass, InputStream inputStream) throws JAXBException{ String packageName = docClass.getPackage().getName(); JAXBContext jc = JAXBContext.newInstance( packageName ); Unmarshaller u = jc.createUnmarshaller(); JAXBElement<T> root = u.unmarshal(new StreamSource(inputStream),docClass); return root.getValue(); }*/ public static <T> T unmarshall(Class<T> docClass, InputStream inputStream) throws JAXBException, ParserConfigurationException, SAXException { String packageName = docClass.getPackage().getName(); JAXBContext jc = JAXBContext.newInstance(packageName); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://apache.org/xml/features/validation/schema", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); InputSource inputSource = new InputSource(inputStream); SAXSource source = new SAXSource(xmlReader, inputSource); Unmarshaller u = jc.createUnmarshaller(); JAXBElement<T> root = u.unmarshal(source, docClass); return root.getValue(); }
From source file:iarnrodProducer.java
public static DefaultFeatureCollection parseXML(final SimpleFeatureBuilder builder) { // sft schema = "trainStatus:String,trainCode:String,publicMessage:String,direction:String,dtg:Date,*geom:Point:srid=4326" final DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(); try {//from w w w. j a v a 2 s . com SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); DefaultHandler handler = new DefaultHandler() { StringBuilder textContent = new StringBuilder(); String tagName; double lat; double lon; String trainCode; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { tagName = qName; textContent.setLength(0); } public void endElement(String uri, String localName, String qName) throws SAXException { tagName = qName; String text = textContent.toString(); if (tagName == TRAIN_LAT) { lat = Double.parseDouble(text); } else if (tagName == TRAIN_LON) { lon = Double.parseDouble(text); } else if (tagName == TRAIN_STATUS) { builder.add(text); } else if (tagName == TRAIN_CODE) { trainCode = text; // use this as feature ID builder.add(text); } else if (tagName == PUBLIC_MESSAGE) { builder.add(text); } else if (tagName == DIRECTION) { builder.add(text); // add direction // this is the last field, so finish up builder.add(DateTime.now().toDate()); builder.add(WKTUtils$.MODULE$.read("POINT(" + (lon) + " " + (lat) + ")")); SimpleFeature feature = builder.buildFeature(trainCode); featureCollection.add(feature); } } public void characters(char ch[], int start, int length) throws SAXException { textContent.append(ch, start, length); } public void startDocument() throws SAXException { // System.out.println("document started"); } public void endDocument() throws SAXException { // System.out.println("document ended"); } }; //handler saxParser.parse(API_PATH, handler); return featureCollection; } catch (Exception e) { System.out.println("Parsing exception: " + e); System.out.println("exception"); return null; } }