Example usage for org.xml.sax XMLReader setContentHandler

List of usage examples for org.xml.sax XMLReader setContentHandler

Introduction

In this page you can find the example usage for org.xml.sax XMLReader setContentHandler.

Prototype

public void setContentHandler(ContentHandler handler);

Source Link

Document

Allow an application to register a content event handler.

Usage

From source file:org.pentaho.reporting.libraries.xmlns.parser.AbstractXmlResourceFactory.java

/**
 * A method to allow to invoke the parsing without accessing the LibLoader layer. The data to be parsed is held in the
 * given InputSource object./*from  w w  w  . ja va 2  s.c  o m*/
 *
 * @param manager    the resource manager used for all resource loading.
 * @param input      the raw-data given as SAX-InputSource.
 * @param context    the resource context used to resolve relative resource paths.
 * @param parameters the parse parameters.
 * @return the parsed result, never null.
 * @throws ResourceCreationException    if the resource could not be parsed due to syntaxctial or logical errors in
 *                                      the data.
 * @throws ResourceLoadingException     if the resource could not be accessed from the physical storage.
 * @throws ResourceKeyCreationException if creating the context key failed.
 */
public Object parseDirectly(final ResourceManager manager, final InputSource input, final ResourceKey context,
        final Map parameters)
        throws ResourceKeyCreationException, ResourceCreationException, ResourceLoadingException {
    try {
        final SAXParser parser = getParser();

        final XMLReader reader = parser.getXMLReader();

        final ResourceKey targetKey = manager.createKey(EMPTY_DATA);
        final ResourceKey contextKey;
        if (context == null) {
            contextKey = targetKey;
        } else {
            contextKey = context;
        }

        final XmlFactoryModule[] rootHandlers = getModules();
        final RootXmlReadHandler handler = createRootHandler(manager, targetKey, rootHandlers, contextKey, -1);

        final DefaultConfiguration parserConfiguration = handler.getParserConfiguration();
        final URL value = manager.toURL(contextKey);
        if (value != null) {
            parserConfiguration.setConfigProperty(CONTENTBASE_KEY, value.toExternalForm());
        }

        configureReader(reader, handler);
        reader.setContentHandler(handler);
        reader.setDTDHandler(handler);
        reader.setEntityResolver(handler.getEntityResolver());
        reader.setErrorHandler(getErrorHandler());

        final Iterator it = parameters.keySet().iterator();
        while (it.hasNext()) {
            final Object o = it.next();
            if (o instanceof FactoryParameterKey) {
                final FactoryParameterKey fpk = (FactoryParameterKey) o;
                handler.setHelperObject(fpk.getName(), parameters.get(fpk));
            }
        }

        reader.parse(input);

        return finishResult(handler.getResult(), manager, new RawResourceData(targetKey), contextKey);
    } catch (ParserConfigurationException e) {
        throw new ResourceCreationException("Unable to initialize the XML-Parser", e);
    } catch (SAXException e) {
        throw new ResourceCreationException("Unable to parse the document", e);
    } catch (IOException e) {
        throw new ResourceLoadingException("Unable to read the stream", e);
    }

}

From source file:org.pwsafe.passwordsafeswt.xml.XMLDataParser.java

/**
 * @see au.gov.centrelink.itsecurity.tokenservice.saml.SubjectConfirmationDataParser#parse(java.lang.String)
 *//*w ww .  j a va 2 s .  co m*/
public PwsEntryBean[] parse(String incomingXMLString) {

    PwsEntryBean[] entries = null;

    try {
        XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();

        XMLDataParserHandler xmlHandler = new XMLDataParserHandler();

        xmlReader.setContentHandler(xmlHandler);
        InputSource is = new InputSource(new StringReader(incomingXMLString));
        xmlReader.parse(is);
        entries = (PwsEntryBean[]) xmlHandler.entryList.toArray(new PwsEntryBean[0]);
    } catch (Exception e) {
        // Almost certainly related issues parsing the XML.
        throw new RuntimeException(e);
    }
    return entries;
}

From source file:org.radeox.filter.XHTMLFilter.java

public String filter(String input, FilterContext context) {
    String finalOutput = input;//from  www  . j  av  a 2  s . com
    try {
        DeblockFilter dbf = new DeblockFilter();
        EmptyFilter epf = new EmptyFilter();

        dbf.setBlockElements(blockElements);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        SpecialXHTMLSerializer xser = new SpecialXHTMLSerializer();
        xser.setOutputStream(baos);
        xser.setIndent(false);
        xser.setEncoding("UTF-8");
        xser.setIndentAmount(4);
        dbf.setContentHandler(epf);
        epf.setContentHander(xser.asContentHandler());

        SAXParser parser = saxParserFactory.newSAXParser();

        XMLReader xmlr = parser.getXMLReader();

        xmlr.setContentHandler(dbf);
        // log.warn("Input is "+input);
        xmlr.parse(new InputSource(new StringReader("<sr>" + input + "</sr>")));

        String output = new String(baos.toByteArray(), "UTF-8");
        int startBlock = output.indexOf("<sr>");
        int endBlock = output.indexOf("</sr>");
        finalOutput = output.substring(startBlock + 4, endBlock);
        // log.warn("Output is "+finalOutput);
    } catch (Throwable t) {
        log.error("Failed to XHTML check " + t.getMessage() + "\n Input======\n" + input + "\n=======");
        return input;
    }

    return finalOutput;
}

From source file:org.rhq.plugins.diameter.jbossas5.util.JnpConfig.java

private void parseServiceXML(File distributionDirectory, File serviceXmlFile)
        throws IOException, SAXException, ParserConfigurationException {
    FileInputStream is = null;/*from ww  w  .  jav  a  2  s.co m*/
    try {
        is = new FileInputStream(serviceXmlFile);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        EntityResolver r = new LocalEntityResolver(distributionDirectory);

        JBossServiceHandler handler = new JBossServiceHandler(serviceXmlFile);

        XMLReader reader = parser.getXMLReader();

        reader.setEntityResolver(r);

        reader.setContentHandler(handler);

        reader.parse(new InputSource(is));

        this.jnpAddress = handler.getNamingBindAddress();
        this.jnpPort = handler.getNamingPort();
        this.storeFile = handler.getStoreFile();
        this.serverName = handler.getServerName();
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.rhq.plugins.diameter.jbossas5.util.JnpConfig.java

private void parseBindingManagerXML() throws IOException {
    InputStream bindIs = null;//w ww  .  ja v  a  2s . c o  m
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        if (!this.storeFile.isFile()) {
            log.warn("Store file does not exist: " + this.storeFile);
            return;
        }

        JBossBindingManagerHandler bindingHandler = new JBossBindingManagerHandler(this.storeFile);
        bindingHandler.setServerName(this.serverName);
        XMLReader reader = parser.getXMLReader();
        bindIs = new FileInputStream(this.storeFile);
        reader.setContentHandler(bindingHandler);
        reader.parse(new InputSource(bindIs));
        this.jnpAddress = bindingHandler.getJnpAddress();
        this.jnpPort = bindingHandler.getJnpPort();
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage());
    } finally {
        if (bindIs != null) {
            bindIs.close();
        }
    }
}

From source file:org.rhq.plugins.jbossas.util.JnpConfig.java

private void parseServiceXML(File serviceXmlFile)
        throws IOException, SAXException, ParserConfigurationException {
    FileInputStream is = null;//  ww  w  .  j  a  v a  2s . c  o  m
    try {
        is = new FileInputStream(serviceXmlFile);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        XMLReader reader = parser.getXMLReader();

        EntityResolver entityResolver = SelectiveSkippingEntityResolver.getDtdAndXsdSkippingInstance();
        reader.setEntityResolver(entityResolver);

        JBossServiceHandler contentHandler = new JBossServiceHandler(serviceXmlFile);
        reader.setContentHandler(contentHandler);

        reader.parse(new InputSource(is));

        this.jnpAddress = contentHandler.getNamingBindAddress();
        this.jnpPort = contentHandler.getNamingPort();
        this.storeFile = contentHandler.getStoreFile();
        this.serverName = contentHandler.getServerName();
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.sakaiproject.kernel.component.core.PersistenceUnitClassLoader.java

/**
 * Scans the classloader for files named META-INF/orm.xml and consolidates
 * them.//w w w  .  ja va 2s.  c  o 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;
}

From source file:org.sakaiproject.search.component.service.impl.SearchListResponseImpl.java

public SearchListResponseImpl(String response, Query query, int start, int end, Analyzer analyzer,
        SearchItemFilter filter, SearchIndexBuilder searchIndexBuilder, SearchService searchService)
        throws SAXException, IOException {

    this.query = query;
    this.start = start;
    this.end = end;
    this.analyzer = analyzer;
    this.filter = filter;
    this.searchIndexBuilder = searchIndexBuilder;
    this.searchService = searchService;

    if (log.isDebugEnabled()) {
        log.debug("search response: [" + response + "]");
    }//from   ww  w  . j av a 2 s.  c o m

    XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    InputSource is = new InputSource(new StringReader(response));
    xr.parse(is);

    if (errorMessage != null) {
        log.error("Failed to perform remote request, remote exception was: \n" + errorMessage);
        throw new IOException("Failed to perform remote request ");
    }

}

From source file:org.sakaiproject.warehouse.util.db.DbLoader.java

protected void readProperties(XMLReader parser, InputStream properties) throws SAXException, IOException {
    propertiesHandler = new PropertiesHandler();
    parser.setContentHandler(propertiesHandler);
    parser.setErrorHandler(propertiesHandler);
    parser.parse(new InputSource(properties));
}

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 {// w  w w  . java2 s .  c om
        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);
    }
}