List of usage examples for org.xml.sax.helpers XMLReaderFactory createXMLReader
public static XMLReader createXMLReader() throws SAXException
From source file:org.opennms.core.xml.JaxbUtils.java
public static <T> XMLFilter getXMLFilterForClass(final Class<T> clazz) throws SAXException { final String namespace = getNamespaceForClass(clazz); XMLFilter filter = namespace == null ? new SimpleNamespaceFilter("", false) : new SimpleNamespaceFilter(namespace, true); LOG.trace("namespace filter for class {}: {}", clazz, filter); final XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); filter.setParent(xmlReader);/* w w w . j a va 2 s .c om*/ return filter; }
From source file:org.opennms.netmgt.measurements.impl.RrdtoolXportFetchStrategy.java
/** * {@inheritDoc}/* www . ja v a 2s . co m*/ */ @Override protected FetchResults fetchMeasurements(long start, long end, long step, int maxrows, Map<Source, String> rrdsBySource, Map<String, Object> constants) throws RrdException { String rrdBinary = System.getProperty("rrd.binary"); if (rrdBinary == null) { throw new RrdException("No RRD binary is set."); } final long startInSeconds = (long) Math.floor(start / 1000); final long endInSeconds = (long) Math.floor(end / 1000); long stepInSeconds = (long) Math.floor(step / 1000); // The step must be strictly positive if (stepInSeconds <= 0) { stepInSeconds = 1; } final CommandLine cmdLine = new CommandLine(rrdBinary); cmdLine.addArgument("xport"); cmdLine.addArgument("--step"); cmdLine.addArgument("" + stepInSeconds); cmdLine.addArgument("--start"); cmdLine.addArgument("" + startInSeconds); cmdLine.addArgument("--end"); cmdLine.addArgument("" + endInSeconds); if (maxrows > 0) { cmdLine.addArgument("--maxrows"); cmdLine.addArgument("" + maxrows); } // Use labels without spaces when executing the xport command // These are mapped back to the requested labels in the response final Map<String, String> labelMap = Maps.newHashMap(); int k = 0; for (final Map.Entry<Source, String> entry : rrdsBySource.entrySet()) { final Source source = entry.getKey(); final String rrdFile = entry.getValue(); final String tempLabel = Integer.toString(++k); labelMap.put(tempLabel, source.getLabel()); cmdLine.addArgument(String.format("DEF:%s=%s:%s:%s", tempLabel, Utils.escapeColons(rrdFile), Utils.escapeColons(source.getEffectiveDataSource()), source.getAggregation())); cmdLine.addArgument(String.format("XPORT:%s:%s", tempLabel, tempLabel)); } // Use commons-exec to execute rrdtool final DefaultExecutor executor = new DefaultExecutor(); // Capture stdout/stderr final ByteArrayOutputStream stdout = new ByteArrayOutputStream(); final ByteArrayOutputStream stderr = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, null)); // Fail if we get a non-zero exit code executor.setExitValue(0); // Fail if the process takes too long final ExecuteWatchdog watchdog = new ExecuteWatchdog(XPORT_TIMEOUT_MS); executor.setWatchdog(watchdog); // Export RrdXport rrdXport; try { LOG.debug("Executing: {}", cmdLine); executor.execute(cmdLine); final XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); final SAXSource source = new SAXSource(xmlReader, new InputSource(new StringReader(stdout.toString()))); final JAXBContext jc = JAXBContext.newInstance(RrdXport.class); final Unmarshaller u = jc.createUnmarshaller(); rrdXport = (RrdXport) u.unmarshal(source); } catch (IOException e) { throw new RrdException("An error occured while executing '" + StringUtils.join(cmdLine.toStrings(), " ") + "' with stderr: " + stderr.toString(), e); } catch (SAXException | JAXBException e) { throw new RrdException("The output generated by 'rrdtool xport' could not be parsed.", e); } final int numRows = rrdXport.getRows().size(); final int numColumns = rrdXport.getMeta().getLegends().size(); final long xportStartInMs = rrdXport.getMeta().getStart() * 1000; final long xportStepInMs = rrdXport.getMeta().getStep() * 1000; final long timestamps[] = new long[numRows]; final double values[][] = new double[numColumns][numRows]; // Convert rows to columns int i = 0; for (final XRow row : rrdXport.getRows()) { // Derive the timestamp from the start and step since newer versions // of rrdtool no longer include it as part of the rows timestamps[i] = xportStartInMs + xportStepInMs * i; for (int j = 0; j < numColumns; j++) { if (row.getValues() == null) { // NMS-7710: Avoid NPEs, in certain cases the list of values may be null throw new RrdException( "The output generated by 'rrdtool xport' was not recognized. Try upgrading your rrdtool binaries."); } values[j][i] = row.getValues().get(j); } i++; } // Map the columns by label // The legend entries are in the same order as the column values final Map<String, double[]> columns = Maps.newHashMapWithExpectedSize(numColumns); i = 0; for (String label : rrdXport.getMeta().getLegends()) { columns.put(labelMap.get(label), values[i++]); } return new FetchResults(timestamps, columns, xportStepInMs, constants); }
From source file:org.opennms.web.rest.measurements.fetch.RrdtoolXportFetchStrategy.java
/** * {@inheritDoc}/*w w w .ja v a 2s.com*/ */ @Override protected FetchResults fetchMeasurements(long start, long end, long step, int maxrows, Map<Source, String> rrdsBySource, Map<String, Object> constants) throws RrdException { String rrdBinary = System.getProperty("rrd.binary"); if (rrdBinary == null) { throw new RrdException("No RRD binary is set."); } final long startInSeconds = (long) Math.floor(start / 1000); final long endInSeconds = (long) Math.floor(end / 1000); long stepInSeconds = (long) Math.floor(step / 1000); // The step must be strictly positive if (stepInSeconds <= 0) { stepInSeconds = 1; } final CommandLine cmdLine = new CommandLine(rrdBinary); cmdLine.addArgument("xport"); cmdLine.addArgument("--step"); cmdLine.addArgument("" + stepInSeconds); cmdLine.addArgument("--start"); cmdLine.addArgument("" + startInSeconds); cmdLine.addArgument("--end"); cmdLine.addArgument("" + endInSeconds); if (maxrows > 0) { cmdLine.addArgument("--maxrows"); cmdLine.addArgument("" + maxrows); } // Use labels without spaces when executing the xport command // These are mapped back to the requested labels in the response final Map<String, String> labelMap = Maps.newHashMap(); int k = 0; for (final Map.Entry<Source, String> entry : rrdsBySource.entrySet()) { final Source source = entry.getKey(); final String rrdFile = entry.getValue(); final String tempLabel = Integer.toString(++k); labelMap.put(tempLabel, source.getLabel()); cmdLine.addArgument(String.format("DEF:%s=%s:%s:%s", tempLabel, rrdFile, source.getAttribute(), source.getAggregation())); cmdLine.addArgument(String.format("XPORT:%s:%s", tempLabel, tempLabel)); } // Use commons-exec to execute rrdtool final DefaultExecutor executor = new DefaultExecutor(); // Capture stdout/stderr final ByteArrayOutputStream stdout = new ByteArrayOutputStream(); final ByteArrayOutputStream stderr = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, null)); // Fail if we get a non-zero exit code executor.setExitValue(0); // Fail if the process takes too long final ExecuteWatchdog watchdog = new ExecuteWatchdog(XPORT_TIMEOUT_MS); executor.setWatchdog(watchdog); // Export RrdXport rrdXport; try { executor.execute(cmdLine); final XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); final SAXSource source = new SAXSource(xmlReader, new InputSource(new StringReader(stdout.toString()))); final JAXBContext jc = JAXBContext.newInstance(RrdXport.class); final Unmarshaller u = jc.createUnmarshaller(); rrdXport = (RrdXport) u.unmarshal(source); } catch (IOException e) { throw new RrdException("An error occured while executing '" + StringUtils.join(cmdLine.toStrings(), " ") + "' with stderr: " + stderr.toString(), e); } catch (SAXException | JAXBException e) { throw new RrdException("The output generated by 'rrdtool xport' could not be parsed.", e); } final int numRows = rrdXport.getRows().size(); final int numColumns = rrdXport.getMeta().getLegends().size(); final long timestamps[] = new long[numRows]; final double values[][] = new double[numColumns][numRows]; // Convert rows to columns int i = 0; for (final XRow row : rrdXport.getRows()) { timestamps[i] = row.getTimestamp() * 1000; for (int j = 0; j < numColumns; j++) { if (row.getValues() == null) { // NMS-7710: Avoid NPEs, in certain cases the list of values may be null throw new RrdException( "The output generated by 'rrdtool xport' was not recognized. Try upgrading your rrdtool binaries."); } values[j][i] = row.getValues().get(j); } i++; } // Map the columns by label // The legend entries are in the same order as the column values final Map<String, double[]> columns = Maps.newHashMapWithExpectedSize(numColumns); i = 0; for (String label : rrdXport.getMeta().getLegends()) { columns.put(labelMap.get(label), values[i++]); } return new FetchResults(timestamps, columns, rrdXport.getMeta().getStep() * 1000, constants); }
From source file:org.openstreetmap.josm.tools.ImageProvider.java
/** * Reads the wiki page on a certain file in html format in order to find the real image URL. *///from ww w.j a v a 2 s . co m private static String getImgUrlFromWikiInfoPage(final String base, final String fn) { /** Quit parsing, when a certain condition is met */ class SAXReturnException extends SAXException { private String result; public SAXReturnException(String result) { this.result = result; } public String getResult() { return result; } } try { final XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(new DefaultHandler() { @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { System.out.println(); if (localName.equalsIgnoreCase("img")) { String val = atts.getValue("src"); if (val.endsWith(fn)) throw new SAXReturnException(val); // parsing done, quit early } } }); parser.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { return new InputSource(new ByteArrayInputStream(new byte[0])); } }); parser.parse(new InputSource(new MirroredInputStream(base + fn, new File(Main.pref.getPreferencesDir(), "images").toString()))); } catch (SAXReturnException r) { return r.getResult(); } catch (Exception e) { System.out.println("INFO: parsing " + base + fn + " failed:\n" + e); return null; } System.out.println("INFO: parsing " + base + fn + " failed: Unexpected content."); return null; }
From source file:org.roda.core.common.RodaUtils.java
/** * INFO 20160711 this method does not cache stylesheet related resources *//* www .j a va 2s .c o m*/ public static void applyStylesheet(Reader xsltReader, Reader fileReader, Map<String, String> parameters, Writer result) throws IOException, TransformerException { TransformerFactory factory = new net.sf.saxon.TransformerFactoryImpl(); factory.setURIResolver(new RodaURIFileResolver()); Source xsltSource = new StreamSource(xsltReader); Transformer transformer = factory.newTransformer(xsltSource); for (Entry<String, String> parameter : parameters.entrySet()) { transformer.setParameter(parameter.getKey(), parameter.getValue()); } try { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new RodaEntityResolver()); InputSource source = new InputSource(fileReader); Source text = new SAXSource(xmlReader, source); transformer.transform(text, new StreamResult(result)); } catch (SAXException se) { LOGGER.error(se.getMessage(), se); } }
From source file:org.roda.core.common.RodaUtils.java
public static Reader applyMetadataStylesheet(Binary binary, String basePath, String metadataType, String metadataVersion, Map<String, String> parameters) throws GenericException { try (Reader descMetadataReader = new InputStreamReader( new BOMInputStream(binary.getContent().createInputStream()))) { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new RodaEntityResolver()); InputSource source = new InputSource(descMetadataReader); Source text = new SAXSource(xmlReader, source); XsltExecutable xsltExecutable = CACHE.get(Triple.of(basePath, metadataType, metadataVersion)); XsltTransformer transformer = xsltExecutable.load(); CharArrayWriter transformerResult = new CharArrayWriter(); transformer.setSource(text);/*from w w w . j a v a 2 s . c o m*/ transformer.setDestination(PROCESSOR.newSerializer(transformerResult)); for (Entry<String, String> parameter : parameters.entrySet()) { QName qName = new QName(parameter.getKey()); XdmValue xdmValue = new XdmAtomicValue(parameter.getValue()); transformer.setParameter(qName, xdmValue); } transformer.transform(); return new CharArrayReader(transformerResult.toCharArray()); } catch (IOException | SAXException | ExecutionException | SaxonApiException e) { throw new GenericException("Could not process descriptive metadata binary " + binary.getStoragePath() + " metadata type " + metadataType + " and version " + metadataVersion, e); } }
From source file:org.roda.core.common.RodaUtils.java
public static Reader applyEventStylesheet(Binary binary, boolean onlyDetails, Map<String, String> translations, String path) throws GenericException { try (Reader descMetadataReader = new InputStreamReader( new BOMInputStream(binary.getContent().createInputStream()))) { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new RodaEntityResolver()); InputSource source = new InputSource(descMetadataReader); Source text = new SAXSource(xmlReader, source); XsltExecutable xsltExecutable = EVENT_CACHE.get(path); XsltTransformer transformer = xsltExecutable.load(); CharArrayWriter transformerResult = new CharArrayWriter(); transformer.setSource(text);// ww w . j ava 2s . com transformer.setDestination(PROCESSOR.newSerializer(transformerResult)); // send param to filter stylesheet work transformer.setParameter(new QName("onlyDetails"), new XdmAtomicValue(Boolean.toString(onlyDetails))); for (Entry<String, String> parameter : translations.entrySet()) { QName qName = new QName(parameter.getKey()); XdmValue xdmValue = new XdmAtomicValue(parameter.getValue()); transformer.setParameter(qName, xdmValue); } transformer.transform(); return new CharArrayReader(transformerResult.toCharArray()); } catch (IOException | SAXException | ExecutionException | SaxonApiException e) { LOGGER.error(e.getMessage(), e); throw new GenericException("Could not process event binary " + binary.getStoragePath(), e); } }
From source file:org.roda.core.common.validation.ValidationUtils.java
public static ValidationReport isXMLValid(ContentPayload xmlPayload) { ValidationReport ret = new ValidationReport(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false);//from w w w. j a va 2 s . co m factory.setNamespaceAware(true); RodaErrorHandler errorHandler = new RodaErrorHandler(); try (Reader reader = new InputStreamReader(new BOMInputStream(xmlPayload.createInputStream()))) { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new RodaEntityResolver()); InputSource inputSource = new InputSource(reader); xmlReader.setErrorHandler(errorHandler); xmlReader.parse(inputSource); ret.setValid(errorHandler.getErrors().isEmpty()); for (SAXParseException saxParseException : errorHandler.getErrors()) { ret.addIssue(convertSAXParseException(saxParseException)); } } catch (SAXException e) { ret.setValid(false); for (SAXParseException saxParseException : errorHandler.getErrors()) { ret.addIssue(convertSAXParseException(saxParseException)); } } catch (IOException e) { ret.setValid(false); ret.setMessage(e.getMessage()); } return ret; }
From source file:org.roda.core.common.validation.ValidationUtils.java
/** * Validates descriptive medatada (e.g. against its schema, but other * strategies may be used)/* w ww . j a v a 2 s . c o m*/ * * @param descriptiveMetadataType * * @param failIfNoSchema * @throws ValidationException */ public static ValidationReport validateDescriptiveBinary(ContentPayload descriptiveMetadataPayload, String descriptiveMetadataType, String descriptiveMetadataVersion, boolean failIfNoSchema) { ValidationReport ret = new ValidationReport(); InputStream inputStream = null; Optional<Schema> xmlSchema = RodaCoreFactory.getRodaSchema(descriptiveMetadataType, descriptiveMetadataVersion); try { if (xmlSchema.isPresent()) { RodaErrorHandler errorHandler = new RodaErrorHandler(); try (InputStreamReader inputStreamReader = new InputStreamReader( new BOMInputStream(descriptiveMetadataPayload.createInputStream()))) { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new RodaEntityResolver()); InputSource inputSource = new InputSource(inputStreamReader); Source source = new SAXSource(xmlReader, inputSource); Validator validator = xmlSchema.get().newValidator(); validator.setErrorHandler(errorHandler); validator.validate(source); ret.setValid(errorHandler.getErrors().isEmpty()); for (SAXParseException saxParseException : errorHandler.getErrors()) { ret.addIssue(convertSAXParseException(saxParseException)); } } catch (SAXException e) { LOGGER.debug("Error validating descriptive binary " + descriptiveMetadataType, e); ret.setValid(false); for (SAXParseException saxParseException : errorHandler.getErrors()) { ret.addIssue(convertSAXParseException(saxParseException)); } } } else { if (failIfNoSchema) { LOGGER.error( "Will fail validating descriptive metadata with type '{}' and version '{}' because couldn't find its schema", descriptiveMetadataType, descriptiveMetadataVersion); ret.setValid(false); ret.setMessage("No schema to validate " + descriptiveMetadataType); } else { LOGGER.debug( "Found no schema do validate descriptive metadata but will try to validate XML syntax..."); ret = isXMLValid(descriptiveMetadataPayload); } } } catch (IOException e) { LOGGER.error("Error validating descriptive metadata", e); ret.setValid(false); ret.setMessage(e.getMessage()); } finally { IOUtils.closeQuietly(inputStream); } return ret; }
From source file:org.sakaiproject.kernel.component.core.PersistenceUnitClassLoader.java
/** * Scans the classloader for files named META-INF/orm.xml and consolidates * them.//w ww .j a v a2 s. co m * * @return A consolidated String representing all orm.xml files found. * @throws IOException * @throws SAXException */ private String scanOrmXml() throws TransformerConfigurationException, IOException, SAXException { StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); // SAX2.0 ContentHandler SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler handler = tf.newTransformerHandler(); Transformer serializer = handler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); handler.setResult(result); JpaOrmAccumulator acc = new JpaOrmAccumulator(handler); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(acc); for (final URL url : findXMLs(ORM_XML)) { reader.parse(new InputSource(url.openStream())); } String writerOut = writer.toString(); String out = XML_HEADER + ENTITY_MAPPINGS_START + writerOut.substring(writerOut.indexOf("<entity ")) + ENTITY_MAPPINGS_END; return out; }