List of usage examples for org.xml.sax XMLReader parse
public void parse(String systemId) throws IOException, SAXException;
From source file:org.dishevelled.color.scheme.impl.ColorSchemes.java
/** * Create and return a discrete color scheme with the specified name and number of colors, if any. * The color schemes are defined in a simple XML format and read from the color-scheme library classpath. * * @since 2.1/*from w ww. j a v a2s .c o m*/ * @param name name * @param colors number of colors * @return a discrete color scheme with the specified name and number of colors, or * <code>null</code> if no such discrete color scheme exists */ public static ColorScheme getDiscreteColorScheme(final String name, final int colors) { InputStream inputStream = null; ColorScheme colorScheme = null; try { inputStream = ColorSchemes.class.getResourceAsStream(name + "-" + colors + ".xml"); XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); InputSource inputSource = new InputSource(inputStream); ColorSchemeHandler colorSchemeHandler = new ColorSchemeHandler(); ContentHandler contentHandler = new SAX2StAXAdaptor(colorSchemeHandler); xmlReader.setContentHandler(contentHandler); xmlReader.parse(inputSource); if ("divergent".equals(colorSchemeHandler.getType())) { colorScheme = new DiscreteDivergentColorScheme(colorSchemeHandler.getName(), colorSchemeHandler.getColors(), 0.0d, 0.5d, 1.0d, COLOR_FACTORY); } else { colorScheme = new DiscreteColorScheme(colorSchemeHandler.getName(), colorSchemeHandler.getColors(), 0.0d, 1.0d, COLOR_FACTORY); } } catch (Exception e) { //e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); } return colorScheme; }
From source file:org.dishevelled.color.scheme.impl.ColorSchemes.java
/** * Create and return a continuous color scheme with the specified name and number of colors, if any. * The color schemes are defined in a simple XML format and read from the color-scheme library classpath. * * @since 2.1/* ww w. jav a 2 s . c om*/ * @param name name * @param colors number of colors * @return a continuous color scheme with the specified name and number of colors, or * <code>null</code> if no such continuous color scheme exists */ public static ColorScheme getContinuousColorScheme(final String name, final int colors) { InputStream inputStream = null; ColorScheme colorScheme = null; try { inputStream = ColorSchemes.class.getResourceAsStream(name + "-" + colors + ".xml"); XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); InputSource inputSource = new InputSource(inputStream); ColorSchemeHandler colorSchemeHandler = new ColorSchemeHandler(); ContentHandler contentHandler = new SAX2StAXAdaptor(colorSchemeHandler); xmlReader.setContentHandler(contentHandler); xmlReader.parse(inputSource); if ("divergent".equals(colorSchemeHandler.getType())) { colorScheme = new ContinuousDivergentColorScheme(colorSchemeHandler.getName(), colorSchemeHandler.getColors(), 0.0d, 0.5d, 1.0d, COLOR_FACTORY); } else { colorScheme = new ContinuousColorScheme(colorSchemeHandler.getName(), colorSchemeHandler.getColors(), 0.0d, 1.0d, COLOR_FACTORY); } } catch (Exception e) { //e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); } return colorScheme; }
From source file:org.dita.dost.module.GenMapAndTopicListModule.java
/** * Read a file and process it for list information. * // ww w . j ava2s . c o m * @param ref system path of the file to process * @throws DITAOTException if processing failed */ private void processFile(final Reference ref) throws DITAOTException { currentFile = ref.filename; assert currentFile.isAbsolute(); logger.info("Processing " + currentFile); final String[] params = { currentFile.toString() }; try { XMLReader xmlSource = getXmlReader(ref.format); for (final XMLFilter f : getProcessingPipe(currentFile)) { f.setParent(xmlSource); f.setEntityResolver(CatalogUtils.getCatalogResolver()); xmlSource = f; } xmlSource.setContentHandler(nullHandler); xmlSource.parse(currentFile.toString()); if (listFilter.isValidInput()) { processParseResult(currentFile); categorizeCurrentFile(ref); } else if (!currentFile.equals(rootFile)) { logger.warn(MessageUtils.getInstance().getMessage("DOTJ021W", params).toString()); failureList.add(currentFile); } } catch (final RuntimeException e) { throw e; } catch (final SAXParseException sax) { final Exception inner = sax.getException(); if (inner != null && inner instanceof DITAOTException) { throw (DITAOTException) inner; } if (currentFile.equals(rootFile)) { throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ012F", params).toString() + ": " + sax.getMessage(), sax); } else if (processingMode == Mode.STRICT) { throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString() + ": " + sax.getMessage(), sax); } else { logger.error(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString() + ": " + sax.getMessage(), sax); } failureList.add(currentFile); } catch (final FileNotFoundException e) { if (currentFile.equals(rootFile)) { throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTA069F", params).toString(), e); } else if (processingMode == Mode.STRICT) { throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTX008E", params).toString() + ": " + e.getMessage(), e); } else { logger.error(MessageUtils.getInstance().getMessage("DOTX008E", params).toString()); } failureList.add(currentFile); } catch (final Exception e) { if (currentFile.equals(rootFile)) { throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ012F", params).toString() + ": " + e.getMessage(), e); } else if (processingMode == Mode.STRICT) { throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString() + ": " + e.getMessage(), e); } else { logger.error(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString() + ": " + e.getMessage(), e); } failureList.add(currentFile); } if (!listFilter.isValidInput() && currentFile.equals(rootFile)) { if (xmlValidate) { // stop the build if all content in the input file was filtered out. throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ022F", params).toString()); } else { // stop the build if the content of the file is not valid. throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ034F", params).toString()); } } doneList.add(currentFile); listFilter.reset(); keydefFilter.reset(); }
From source file:org.dita.dost.module.reader.AbstractReaderModule.java
/** * Read a file and process it for list information. * * @param ref system path of the file to process * @param parseFile file to parse, may be {@code null} * @throws DITAOTException if processing failed *//*from w w w . j av a2s . c o m*/ void readFile(final Reference ref, final URI parseFile) throws DITAOTException { currentFile = ref.filename; assert currentFile.isAbsolute(); final URI src = parseFile != null ? parseFile : currentFile; assert src.isAbsolute(); final URI rel = tempFileNameScheme.generateTempFileName(currentFile); outputFile = new File(job.tempDirURI.resolve(rel)); final File outputDir = outputFile.getParentFile(); if (!outputDir.exists() && !outputDir.mkdirs()) { logger.error("Failed to create output directory " + outputDir.getAbsolutePath()); return; } validateMap = Collections.emptyMap(); defaultValueMap = Collections.emptyMap(); logger.info("Processing " + currentFile + " to " + outputFile.toURI()); final String[] params = { currentFile.toString() }; // Verify stub for current file is in Job final FileInfo fi = job.getFileInfo(currentFile); if (fi == null) { final FileInfo stub = new FileInfo.Builder().src(currentFile).uri(rel).result(currentFile) .isInput(currentFile.equals(rootFile)).build(); job.add(stub); } // InputSource in = null; Result out = null; try { final TransformerFactory tf = TransformerFactory.newInstance(); final SAXTransformerFactory stf = (SAXTransformerFactory) tf; final TransformerHandler serializer = stf.newTransformerHandler(); XMLReader parser = getXmlReader(ref.format); XMLReader xmlSource = parser; for (final XMLFilter f : getProcessingPipe(currentFile)) { f.setParent(xmlSource); f.setEntityResolver(CatalogUtils.getCatalogResolver()); xmlSource = f; } try { final LexicalHandler lexicalHandler = new DTDForwardHandler(xmlSource); parser.setProperty("http://xml.org/sax/properties/lexical-handler", lexicalHandler); parser.setFeature("http://xml.org/sax/features/lexical-handler", true); } catch (final SAXNotRecognizedException e) { } // in = new InputSource(src.toString()); out = new StreamResult(new FileOutputStream(outputFile)); serializer.setResult(out); xmlSource.setContentHandler(serializer); xmlSource.parse(src.toString()); if (listFilter.isValidInput()) { processParseResult(currentFile); categorizeCurrentFile(ref); } else if (!currentFile.equals(rootFile)) { logger.warn(MessageUtils.getMessage("DOTJ021W", params).toString()); failureList.add(currentFile); } } catch (final RuntimeException e) { throw e; } catch (final SAXParseException sax) { final Exception inner = sax.getException(); if (inner != null && inner instanceof DITAOTException) { throw (DITAOTException) inner; } if (currentFile.equals(rootFile)) { throw new DITAOTException( MessageUtils.getMessage("DOTJ012F", params).toString() + ": " + sax.getMessage(), sax); } else if (processingMode == Mode.STRICT) { throw new DITAOTException( MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + sax.getMessage(), sax); } else { logger.error(MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + sax.getMessage(), sax); } failureList.add(currentFile); } catch (final FileNotFoundException e) { if (!exists(currentFile)) { if (currentFile.equals(rootFile)) { throw new DITAOTException(MessageUtils.getMessage("DOTA069F", params).toString(), e); } else if (processingMode == Mode.STRICT) { throw new DITAOTException(MessageUtils.getMessage("DOTX008E", params).toString(), e); } else { logger.error(MessageUtils.getMessage("DOTX008E", params).toString()); } } else if (currentFile.equals(rootFile)) { throw new DITAOTException(MessageUtils.getMessage("DOTJ078F", params).toString() + " Cannot load file: " + e.getMessage(), e); } else if (processingMode == Mode.STRICT) { throw new DITAOTException(MessageUtils.getMessage("DOTJ079E", params).toString() + " Cannot load file: " + e.getMessage(), e); } else { logger.error(MessageUtils.getMessage("DOTJ079E", params).toString() + " Cannot load file: " + e.getMessage()); } failureList.add(currentFile); } catch (final Exception e) { if (currentFile.equals(rootFile)) { throw new DITAOTException( MessageUtils.getMessage("DOTJ012F", params).toString() + ": " + e.getMessage(), e); } else if (processingMode == Mode.STRICT) { throw new DITAOTException( MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + e.getMessage(), e); } else { logger.error(MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + e.getMessage(), e); } failureList.add(currentFile); } finally { if (out != null) { try { close(out); } catch (final IOException e) { logger.error(e.getMessage(), e); } } if (failureList.contains(currentFile)) { FileUtils.deleteQuietly(outputFile); } } if (!listFilter.isValidInput() && currentFile.equals(rootFile)) { if (validate) { // stop the build if all content in the input file was filtered out. throw new DITAOTException(MessageUtils.getMessage("DOTJ022F", params).toString()); } else { // stop the build if the content of the file is not valid. throw new DITAOTException(MessageUtils.getMessage("DOTJ034F", params).toString()); } } doneList.add(currentFile); listFilter.reset(); keydefFilter.reset(); }
From source file:org.dita.dost.reader.TestGenListModuleReader.java
private void run(final File rootFile) throws Exception { final File ditaDir = new File("src" + File.separator + "main").getAbsoluteFile(); final boolean validate = false; reader = new GenListModuleReader(); reader.setLogger(new TestUtils.TestLogger()); reader.setCurrentFile(rootFile.toURI()); reader.setPrimaryDitamap(rootFile.toURI()); reader.setJob(new Job(tempDir)); reader.setContentHandler(new DefaultHandler()); final XMLReader parser = initXMLReader(ditaDir, validate, new File(rootFile.getPath()).getCanonicalFile()); parser.setContentHandler(reader);/*w w w . j a v a2 s .c om*/ parser.parse(rootFile.toURI().toString()); }
From source file:org.dspace.content.authority.LCNameAuthority.java
/** * Guts of the implementation, returns a complete Choices result, or * null for a failure.//from w w w . j a va 2 s . c om */ private Choices queryPerson(String text, int start, int limit) { // punt if there is no query text if (text == null || text.trim().length() == 0) { return new Choices(true); } // 1. build CQL query DCPersonName pn = new DCPersonName(text); StringBuilder query = new StringBuilder(); query.append("local.FirstName = \"").append(pn.getFirstNames()).append("\" and local.FamilyName = \"") .append(pn.getLastName()).append("\""); // XXX arbitrary default limit - should be configurable? if (limit == 0) { limit = 50; } NameValuePair args[] = new NameValuePair[6]; args[0] = new NameValuePair("operation", "searchRetrieve"); args[1] = new NameValuePair("version", "1.1"); args[2] = new NameValuePair("recordSchema", "info:srw/schema/1/marcxml-v1.1"); args[3] = new NameValuePair("query", query.toString()); args[4] = new NameValuePair("maximumRecords", String.valueOf(limit)); args[5] = new NameValuePair("startRecord", String.valueOf(start + 1)); HttpClient hc = new HttpClient(); String srUrl = url + "?" + EncodingUtil.formUrlEncode(args, "UTF8"); GetMethod get = new GetMethod(srUrl); log.debug("Trying SRU query, URL=" + srUrl); // 2. web request try { int status = hc.executeMethod(get); if (status == 200) { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); SRUHandler handler = new SRUHandler(); // XXX FIXME: should turn off validation here explicitly, but // it seems to be off by default. xr.setFeature("http://xml.org/sax/features/namespaces", true); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(get.getResponseBodyAsStream())); // this probably just means more results available.. if (handler.hits != handler.result.size()) { log.warn("Discrepency in results, result.length=" + handler.result.size() + ", yet expected results=" + handler.hits); } boolean more = handler.hits > (start + handler.result.size()); // XXX add non-auth option; perhaps the UI should do this? // XXX it's really a policy matter if they allow unauth result. // XXX good, stop it. // handler.result.add(new Choice("", text, "Non-Authority: \""+text+"\"")); int confidence; if (handler.hits == 0) { confidence = Choices.CF_NOTFOUND; } else if (handler.hits == 1) { confidence = Choices.CF_UNCERTAIN; } else { confidence = Choices.CF_AMBIGUOUS; } return new Choices(handler.result.toArray(new Choice[handler.result.size()]), start, handler.hits, confidence, more); } } catch (HttpException e) { log.error("SRU query failed: ", e); return new Choices(true); } catch (IOException e) { log.error("SRU query failed: ", e); return new Choices(true); } catch (ParserConfigurationException e) { log.warn("Failed parsing SRU result: ", e); return new Choices(true); } catch (SAXException e) { log.warn("Failed parsing SRU result: ", e); return new Choices(true); } finally { get.releaseConnection(); } return new Choices(true); }
From source file:org.dspace.content.authority.SHERPARoMEOProtocol.java
protected Choices query(String result, String label, String authority, NameValuePair[] args, int start, int limit) { HttpClient hc = new HttpClient(); String srUrl = url + "?" + EncodingUtil.formUrlEncode(args, "UTF8"); GetMethod get = new GetMethod(srUrl); log.debug("Trying SHERPA/RoMEO Query, URL=" + srUrl); try {//from w w w . j av a 2 s . c om int status = hc.executeMethod(get); if (status == 200) { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); SRHandler handler = new SRHandler(result, label, authority); // XXX FIXME: should turn off validation here explicitly, but // it seems to be off by default. xr.setFeature("http://xml.org/sax/features/namespaces", true); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(get.getResponseBodyAsStream())); int confidence; if (handler.total == 0) { confidence = Choices.CF_NOTFOUND; } else if (handler.total == 1) { confidence = Choices.CF_UNCERTAIN; } else { confidence = Choices.CF_AMBIGUOUS; } return new Choices(handler.result, start, handler.total, confidence, false); } } catch (HttpException e) { log.error("SHERPA/RoMEO query failed: ", e); return null; } catch (IOException e) { log.error("SHERPA/RoMEO query failed: ", e); return null; } catch (ParserConfigurationException e) { log.warn("Failed parsing SHERPA/RoMEO result: ", e); return null; } catch (SAXException e) { log.warn("Failed parsing SHERPA/RoMEO result: ", e); return null; } finally { get.releaseConnection(); } return null; }
From source file:org.dspace.content.authority.SkylightAPIProtocol.java
protected Choices query(String result, String label, String authority, String args, int start, int limit) throws UnsupportedEncodingException { String encodedArgs = new String(args.getBytes("UTF-8"), "UTF-8"); HttpClient hc = new HttpClient(); String srUrl = url + "/search/" + encodedArgs + ".xml?field=" + label; GetMethod get = new GetMethod(srUrl); log.info("Trying Skylight Query, URL=" + srUrl); try {/*from w ww .j a va 2 s. c o m*/ int status = hc.executeMethod(get); log.info("Status" + status); if (status == 200) { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); SRHandler handler = new SRHandler(result, label, authority); // XXX FIXME: should turn off validation here explicitly, but // it seems to be off by default. xr.setFeature("http://xml.org/sax/features/namespaces", true); xr.setContentHandler(handler); xr.setErrorHandler(handler); InputSource src = new InputSource(get.getResponseBodyAsStream()); log.info("Source from sklightui :: " + src.toString()); xr.parse(src); int confidence; if (handler.total == 0) { confidence = Choices.CF_NOTFOUND; } else if (handler.total == 1) { confidence = Choices.CF_UNCERTAIN; } else { confidence = Choices.CF_AMBIGUOUS; } return new Choices(handler.result, start, handler.total, confidence, false); } } catch (HttpException e) { log.error("Skylight query failed: ", e); return null; } catch (IOException e) { log.error("Skylight query failed: ", e); return null; } catch (ParserConfigurationException e) { log.warn("Failed parsing SHERPA/RoMEO result: ", e); return null; } catch (SAXException e) { log.warn("Failed parsing Skylight result: ", e); return null; } finally { get.releaseConnection(); } return null; }
From source file:org.eclipse.rdf4j.rio.rdfxml.RDFXMLParser.java
private void parse(InputSource inputSource) throws IOException, RDFParseException, RDFHandlerException { clear();//from ww w . java 2s .c om try { documentURI = inputSource.getSystemId(); saxFilter.setParseStandAloneDocuments( getParserConfig().get(XMLParserSettings.PARSE_STANDALONE_DOCUMENTS)); // saxFilter.clear(); saxFilter.setDocumentURI(documentURI); XMLReader xmlReader; if (getParserConfig().isSet(XMLParserSettings.CUSTOM_XML_READER)) { xmlReader = getParserConfig().get(XMLParserSettings.CUSTOM_XML_READER); } else { xmlReader = XMLReaderFactory.createXMLReader(); } xmlReader.setContentHandler(saxFilter); xmlReader.setErrorHandler(this); // Set all compulsory feature settings, using the defaults if they are // not explicitly set for (RioSetting<Boolean> aSetting : getCompulsoryXmlFeatureSettings()) { try { xmlReader.setFeature(aSetting.getKey(), getParserConfig().get(aSetting)); } catch (SAXNotRecognizedException e) { reportWarning(String.format("%s is not a recognized SAX feature.", aSetting.getKey())); } catch (SAXNotSupportedException e) { reportWarning(String.format("%s is not a supported SAX feature.", aSetting.getKey())); } } // Set all compulsory property settings, using the defaults if they are // not explicitly set for (RioSetting<?> aSetting : getCompulsoryXmlPropertySettings()) { try { xmlReader.setProperty(aSetting.getKey(), getParserConfig().get(aSetting)); } catch (SAXNotRecognizedException e) { reportWarning(String.format("%s is not a recognized SAX property.", aSetting.getKey())); } catch (SAXNotSupportedException e) { reportWarning(String.format("%s is not a supported SAX property.", aSetting.getKey())); } } // Check for any optional feature settings that are explicitly set in // the parser config for (RioSetting<Boolean> aSetting : getOptionalXmlFeatureSettings()) { try { if (getParserConfig().isSet(aSetting)) { xmlReader.setFeature(aSetting.getKey(), getParserConfig().get(aSetting)); } } catch (SAXNotRecognizedException e) { reportWarning(String.format("%s is not a recognized SAX feature.", aSetting.getKey())); } catch (SAXNotSupportedException e) { reportWarning(String.format("%s is not a supported SAX feature.", aSetting.getKey())); } } // Check for any optional property settings that are explicitly set in // the parser config for (RioSetting<?> aSetting : getOptionalXmlPropertySettings()) { try { if (getParserConfig().isSet(aSetting)) { xmlReader.setProperty(aSetting.getKey(), getParserConfig().get(aSetting)); } } catch (SAXNotRecognizedException e) { reportWarning(String.format("%s is not a recognized SAX property.", aSetting.getKey())); } catch (SAXNotSupportedException e) { reportWarning(String.format("%s is not a supported SAX property.", aSetting.getKey())); } } xmlReader.parse(inputSource); } catch (SAXParseException e) { Exception wrappedExc = e.getException(); if (wrappedExc == null) { reportFatalError(e, e.getLineNumber(), e.getColumnNumber()); } else { reportFatalError(wrappedExc, e.getLineNumber(), e.getColumnNumber()); } } catch (SAXException e) { Exception wrappedExc = e.getException(); if (wrappedExc == null) { reportFatalError(e); } else if (wrappedExc instanceof RDFParseException) { throw (RDFParseException) wrappedExc; } else if (wrappedExc instanceof RDFHandlerException) { throw (RDFHandlerException) wrappedExc; } else { reportFatalError(wrappedExc); } } finally { // Clean up saxFilter.clear(); xmlLang = null; elementStack.clear(); usedIDs.clear(); clear(); } }
From source file:org.eclipse.smarthome.binding.sonos.internal.SonosXMLParser.java
/** * @param xml// ww w.j a va2 s .c o m * @return a list of alarms from the given xml string. * @throws IOException * @throws SAXException */ public static List<SonosAlarm> getAlarmsFromStringResult(String xml) { AlarmHandler handler = new AlarmHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { LOGGER.error("Could not parse Alarms from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse Alarms from string '{}'", xml); } return handler.getAlarms(); }