List of usage examples for org.xml.sax XMLReader setFeature
public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException;
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 av a2 s . c o m*/ return filter; }
From source file:org.opennms.netmgt.measurements.impl.RrdtoolXportFetchStrategy.java
/** * {@inheritDoc}//w w w. j a v a 2 s . c om */ @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}//from ww w . j av a 2 s. 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, 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.openrdf.rio.rdfxml.RDFXMLParser.java
private void parse(InputSource inputSource) throws IOException, RDFParseException, RDFHandlerException { try {/* w ww .j a v a 2s . c o m*/ 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.orbeon.oxf.xforms.XFormsUtils.java
private static void htmlStringToResult(String value, LocationData locationData, Result result) { try {/*w ww . ja v a2 s . com*/ final XMLReader xmlReader = new org.ccil.cowan.tagsoup.Parser(); xmlReader.setProperty(org.ccil.cowan.tagsoup.Parser.schemaProperty, TAGSOUP_HTML_SCHEMA); xmlReader.setFeature(org.ccil.cowan.tagsoup.Parser.ignoreBogonsFeature, true); final TransformerHandler identity = TransformerUtils.getIdentityTransformerHandler(); identity.setResult(result); xmlReader.setContentHandler(identity); final InputSource inputSource = new InputSource(); inputSource.setCharacterStream(new StringReader(value)); xmlReader.parse(inputSource); } catch (Exception e) { throw new ValidationException("Cannot parse value as text/html for value: '" + value + "'", locationData); } // r.setFeature(Parser.CDATAElementsFeature, false); // r.setFeature(Parser.namespacesFeature, false); // r.setFeature(Parser.ignoreBogonsFeature, true); // r.setFeature(Parser.bogonsEmptyFeature, false); // r.setFeature(Parser.defaultAttributesFeature, false); // r.setFeature(Parser.translateColonsFeature, true); // r.setFeature(Parser.restartElementsFeature, false); // r.setFeature(Parser.ignorableWhitespaceFeature, true); // r.setProperty(Parser.scannerProperty, new PYXScanner()); // r.setProperty(Parser.lexicalHandlerProperty, h); }
From source file:org.pentaho.reporting.engine.classic.extensions.datasources.cda.CdaResponseParser.java
public static TypedTableModel performParse(final InputStream postResult) throws IOException, ReportDataFactoryException { try {//from www . ja v a 2s .c o m final CdaResponseParser contentHandler = new CdaResponseParser(); final SAXParserFactory factory = SAXParserFactory.newInstance(); final SAXParser parser = factory.newSAXParser(); final XMLReader reader = parser.getXMLReader(); try { reader.setFeature("http://xml.org/sax/features/xmlns-uris", false); } catch (SAXException e) { // ignored } try { reader.setFeature("http://xml.org/sax/features/namespaces", false); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); } catch (final SAXException e) { logger.warn("No Namespace features will be available. (Yes, this is serious)", e); } reader.setContentHandler(contentHandler); reader.parse(new InputSource(postResult)); return (contentHandler.getResult()); } catch (final ParserConfigurationException e) { throw new ReportDataFactoryException("Failed to init XML system", e); } catch (final SAXException e) { throw new ReportDataFactoryException("Failed to parse document", e); } }
From source file:org.pentaho.reporting.libraries.pensol.vfs.XmlSolutionFileModel.java
protected FileInfo performParse(final InputStream postResult) throws IOException { ArgumentNullException.validate("postResult", postResult); try {/* w w w . j a va2 s . com*/ final FileInfoParser contentHandler = new FileInfoParser(); final SAXParserFactory factory = SAXParserFactory.newInstance(); final SAXParser parser = factory.newSAXParser(); final XMLReader reader = parser.getXMLReader(); try { reader.setFeature("http://xml.org/sax/features/xmlns-uris", false); } catch (SAXException e) { // ignored } try { reader.setFeature("http://xml.org/sax/features/namespaces", false); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); } catch (final SAXException e) { logger.warn("No Namespace features will be available. (Yes, this is serious)", e); } reader.setContentHandler(contentHandler); reader.parse(new InputSource(postResult)); majorVersion = contentHandler.getMajorVersion(); minorVersion = contentHandler.getMinorVersion(); releaseVersion = contentHandler.getReleaseVersion(); buildVersion = contentHandler.getBuildVersion(); milestoneVersion = contentHandler.getMilestoneVersion(); return (contentHandler.getRoot()); } catch (final ParserConfigurationException e) { throw new FileSystemException("Failed to init XML system", e); } catch (final SAXException e) { throw new FileSystemException("Failed to parse document", e); } }
From source file:org.pentaho.reporting.libraries.xmlns.parser.AbstractXmlResourceFactory.java
/** * Configures the xml reader. Use this to set features or properties before the documents get parsed. * * @param handler the parser implementation that will handle the SAX-Callbacks. * @param reader the xml reader that should be configured. *//*from w ww. j a va2 s.co m*/ protected void configureReader(final XMLReader reader, final RootXmlReadHandler handler) { try { reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler.getCommentHandler()); } catch (final SAXException se) { // ignore .. logger.debug("Comments are not supported by this SAX implementation."); } try { reader.setFeature("http://xml.org/sax/features/xmlns-uris", true); } catch (final SAXException e) { // ignore handler.setXmlnsUrisNotAvailable(true); } try { // disable validation, as our parsers should handle that already. And we do not want to read // external DTDs that may not exist at all. reader.setFeature("http://xml.org/sax/features/validation", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); } catch (final SAXException e) { // ignore if (logger.isDebugEnabled()) { logger.debug( "Disabling external validation failed. Parsing may or may not fail with a parse error later."); } } try { reader.setFeature("http://xml.org/sax/features/namespaces", true); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); } catch (final SAXException e) { if (logger.isDebugEnabled()) { logger.warn("No Namespace features will be available. (Yes, this is serious)", e); } else if (logger.isWarnEnabled()) { logger.warn("No Namespace features will be available. (Yes, this is serious)"); } } }
From source file:org.portletbridge.portlet.PortletBridgePortlet.java
/** * @return// w w w . ja v a2s . co m * @throws PortletException * @throws IllegalAccessException * @throws */ protected BridgeViewPortlet createViewPortlet(ResourceBundle resourceBundle, TemplateFactory templateFactory) throws PortletException { PortletConfig config = this.getPortletConfig(); // get the memento session key String mementoSessionKey = config.getInitParameter("mementoSessionKey"); if (mementoSessionKey == null) { throw new PortletException(resourceBundle.getString("error.mementoSessionKey")); } // get the servlet name String servletName = config.getInitParameter("servletName"); if (servletName == null) { throw new PortletException(resourceBundle.getString("error.servletName")); } // get parserClassName String parserClassName = config.getInitParameter("parserClassName"); if (parserClassName == null) { throw new PortletException(resourceBundle.getString("error.parserClassName")); } // get authenticatorClassName String authenticatorClassName = config.getInitParameter("authenticatorClassName"); if (authenticatorClassName == null) { throw new PortletException(resourceBundle.getString("error.authenticatorClassName")); } BridgeAuthenticator bridgeAuthenticator = null; try { bridgeAuthenticator = PortletBridgeObjects.createBridgeAuthenticator(authenticatorClassName); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn( "Problem constructing BridgeAuthenticator instance, returning instance of DefaultBridgeAuthenticator", e); } bridgeAuthenticator = new DefaultBridgeAuthenticator(); } // try { // Class authenticatorClass = Class.forName(authenticatorClassName); // bridgeAuthenticator = (BridgeAuthenticator) authenticatorClass.newInstance(); // } catch (ClassNotFoundException e) { // log.warn(e, e); // throw new PortletException(resourceBundle // .getString("error.authenticator")); // } catch (InstantiationException e) { // log.warn(e, e); // throw new PortletException(resourceBundle // .getString("error.authenticator")); // } catch (IllegalAccessException e) { // log.warn(e, e); // throw new PortletException(resourceBundle // .getString("error.authenticator")); // } String initUrlFactoryClassName = config.getInitParameter("initUrlFactoryClassName"); InitUrlFactory initUrlFactory = null; if (initUrlFactoryClassName != null && initUrlFactoryClassName.trim().length() > 0) { try { initUrlFactory = PortletBridgeObjects.createInitUrlFactory(initUrlFactoryClassName); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn( "Problem constructing InitUrlFactory instance, returning instance of DefaultInitUrlFactory", e); } initUrlFactory = new DefaultInitUrlFactory(); } } String idParamKey = config.getInitParameter("idParamKey"); // setup parser BridgeTransformer transformer = null; try { String cssRegex = config.getInitParameter("cssRegex"); String javascriptRegex = config.getInitParameter("jsRegex"); XMLReader parser = XMLReaderFactory.createXMLReader(parserClassName); for (Enumeration names = config.getInitParameterNames(); names.hasMoreElements();) { String name = (String) names.nextElement(); if (name.startsWith("parserFeature-")) { parser.setFeature(name.substring("parserFeature-".length()), "true".equalsIgnoreCase(config.getInitParameter(name))); } else if (name.startsWith("parserProperty-")) { parser.setProperty(name.substring("parserProperty-".length()), config.getInitParameter(name)); } } IdGenerator idGenerator = new DefaultIdGenerator(); ContentRewriter javascriptRewriter = new RegexContentRewriter(javascriptRegex); ContentRewriter cssRewriter = new RegexContentRewriter(cssRegex); BridgeFunctionsFactory bridgeFunctionsFactory = new BridgeFunctionsFactory(idGenerator, javascriptRewriter, cssRewriter); transformer = new AltBridgeTransformer(bridgeFunctionsFactory, templateFactory, parser, servletName); } catch (SAXNotRecognizedException e) { throw new PortletException(e); } catch (SAXNotSupportedException e) { throw new PortletException(e); } catch (SAXException e) { throw new PortletException(e); } BridgeViewPortlet bridgeViewPortlet = new BridgeViewPortlet(); bridgeViewPortlet.setInitUrlFactory(initUrlFactory); bridgeViewPortlet.setHttpClientTemplate(new DefaultHttpClientTemplate()); bridgeViewPortlet.setTransformer(transformer); bridgeViewPortlet.setMementoSessionKey(mementoSessionKey); bridgeViewPortlet.setBridgeAuthenticator(bridgeAuthenticator); if (idParamKey != null) { bridgeViewPortlet.setIdParamKey(idParamKey); } return bridgeViewPortlet; }
From source file:org.slc.sli.ingestion.parser.impl.EdfiRecordParserImpl2.java
private void parseAndValidate(InputStream input, Schema schema) throws XmlParseException, IOException { ValidatorHandler vHandler = schema.newValidatorHandler(); vHandler.setContentHandler(this); vHandler.setErrorHandler(this); InputSource is = new InputSource(new InputStreamReader(input, "UTF-8")); is.setEncoding("UTF-8"); try {/*from ww w . j ava 2 s . c o m*/ XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(vHandler); parser.setErrorHandler(this); vHandler.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false); parser.setFeature("http://apache.org/xml/features/validation/id-idref-checking", false); parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false); parser.setFeature("http://xml.org/sax/features/external-general-entities", false); parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false); parser.parse(is); } catch (SAXException e) { throw new XmlParseException(e.getMessage(), e); } }