Example usage for javax.xml.parsers SAXParserFactory newInstance

List of usage examples for javax.xml.parsers SAXParserFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory newInstance.

Prototype


public static SAXParserFactory newInstance() 

Source Link

Document

Obtain a new instance of a SAXParserFactory .

Usage

From source file:org.alfresco.repo.transfer.RepoTransferReceiverImpl.java

/**
 * Generate the requsite/*from  w w w. jav a2s  .c  o m*/
 */
public void generateRequsite(String transferId, OutputStream out) throws TransferException {
    log.debug("Generate Requsite for transfer:" + transferId);
    try {
        File snapshotFile = getSnapshotFile(transferId);

        if (snapshotFile.exists()) {
            log.debug("snapshot does exist");
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            SAXParser parser = saxParserFactory.newSAXParser();
            OutputStreamWriter dest = new OutputStreamWriter(out, "UTF-8");

            XMLTransferRequsiteWriter writer = new XMLTransferRequsiteWriter(dest);
            TransferManifestProcessor processor = manifestProcessorFactory
                    .getRequsiteProcessor(RepoTransferReceiverImpl.this, transferId, writer);

            XMLTransferManifestReader reader = new XMLTransferManifestReader(processor);

            /**
             * Now run the parser
             */
            parser.parse(snapshotFile, reader);

            /**
             * And flush the destination in case any content remains in the writer.
             */
            dest.flush();

        }
        log.debug("Generate Requsite done transfer:" + transferId);

    } catch (Exception ex) {
        if (TransferException.class.isAssignableFrom(ex.getClass())) {
            throw (TransferException) ex;
        } else {
            throw new TransferException(MSG_ERROR_WHILE_GENERATING_REQUISITE, ex);
        }
    }
}

From source file:org.alfresco.repo.transfer.TransferServiceImpl2.java

private void sendContent(final Transfer transfer, final TransferDefinition definition,
        final TransferEventProcessor eventProcessor, File manifest, File requisite)
        throws SAXException, ParserConfigurationException, IOException {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser parser;/*from  w  ww .jav  a  2  s. co  m*/
    parser = saxParserFactory.newSAXParser();

    /**
     * Parse the requisite file to generate the delta list
     */
    DeltaListRequsiteProcessor reqProcessor = new DeltaListRequsiteProcessor();
    XMLTransferRequsiteReader reqReader = new XMLTransferRequsiteReader(reqProcessor);
    parser.parse(requisite, reqReader);

    final DeltaList deltaList = reqProcessor.getDeltaList();

    /**
     * Parse the manifest file and transfer chunks over
     * 
     * ManifestFile -> Manifest Processor -> Chunker -> Transmitter
     * 
     * Step 1: Create a chunker and wire it up to the transmitter
     */
    final ContentChunker chunker = new ContentChunkerImpl();
    final Long removeNodesRange = Long
            .valueOf(definition.getNodesToRemove() != null ? definition.getNodesToRemove().size() : 0);
    final Long nodesRange = Long.valueOf(definition.getNodes() != null ? definition.getNodes().size() : 0);

    final Long fRange = removeNodesRange + nodesRange;
    chunker.setHandler(new ContentChunkProcessor() {
        private long counter = 0;

        public void processChunk(Set<ContentData> data) {
            checkCancel(transfer.getTransferId());
            logger.debug("send chunk to transmitter");
            for (ContentData file : data) {
                counter++;
                eventProcessor.sendContent(file, fRange, counter);
            }
            transmitter.sendContent(transfer, data);
        }
    });

    /**
     * Step 2 : create a manifest processor and wire it up to the chunker
     */
    TransferManifestProcessor processor = new TransferManifestProcessor() {
        public void processTransferManifestNode(TransferManifestNormalNode node) {
            Set<ContentData> data = TransferManifestNodeHelper.getContentData(node);
            for (ContentData d : data) {
                checkCancel(transfer.getTransferId());
                logger.debug("add content to chunker");

                /**
                 * Check with the deltaList whether we need to send the content item
                 */
                if (deltaList != null) {
                    String partName = TransferCommons.URLToPartName(d.getContentUrl());
                    if (deltaList.getRequiredParts().contains(partName)) {
                        logger.debug("content is required :" + d.getContentUrl());
                        chunker.addContent(d);
                    }
                } else {
                    // No delta list - so send all content items
                    chunker.addContent(d);
                }
            }
        }

        public void processTransferManifiestHeader(TransferManifestHeader header) {
            /* NO-OP */ }

        public void startTransferManifest() {
            /* NO-OP */ }

        public void endTransferManifest() {
            /* NO-OP */ }

        public void processTransferManifestNode(TransferManifestDeletedNode node) { /* NO-OP */
        }
    };

    /**
     * Step 3: wire up the manifest reader to a manifest processor
     */

    XMLTransferManifestReader reader = new XMLTransferManifestReader(processor);

    /**
     * Step 4: start the magic - Give the manifest file to the manifest reader
     */
    parser.parse(manifest, reader);
    chunker.flush();
}

From source file:org.ambraproject.wombat.service.ArticleTransformServiceImpl.java

private void transform(Site site, InputStream xml, OutputStream html, TransformerInitializer initialization)
        throws IOException {
    Objects.requireNonNull(site);
    Objects.requireNonNull(xml);//from   ww  w . ja  v  a  2  s .  co  m
    Objects.requireNonNull(html);

    log.debug("Starting XML transformation");
    SAXParserFactory spf = SAXParserFactory.newInstance();
    XMLReader xmlr;
    try {
        SAXParser sp = spf.newSAXParser();
        xmlr = sp.getXMLReader();
    } catch (ParserConfigurationException | SAXException e) {
        throw new RuntimeException(e);
    }

    /*
     * This is a little unorthodox.  Without setting this custom EntityResolver, the transform will
     * make ~50 HTTP calls to nlm.nih.gov to retrieve the DTD and various entity files referenced
     * in the article XML. By setting a custom EntityResolver that just returns an empty string
     * for each of these, we prevent that.  This seems to have no ill effects on the transformation
     * itself.  This is a roundabout way of turning off DTD validation, which is more
     * straightforward to do with a Document/DocumentBuilder, but the saxon library we're using
     * is much faster at XSLT if it uses its own XML parser instead of DocumentBuilder.  See
     * http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references
     * for a discussion.
     */
    xmlr.setEntityResolver((String publicId, String systemId) -> {
        // Note: returning null here will cause the HTTP request to be made.

        if (VALID_DTDS.contains(systemId)) {
            return new InputSource(new StringReader(""));
        } else {
            throw new IllegalArgumentException("Unexpected entity encountered: " + systemId);
        }
    });
    // build the transformer and add any context-dependent parameters required for the transform
    // NOTE: the XMLReader is passed here for use in creating any required secondary SAX sources
    Transformer transformer = buildTransformer(site, xmlr, initialization);
    SAXSource saxSource = new SAXSource(xmlr, new InputSource(xml));
    try {
        transformer.transform(saxSource, new StreamResult(html));
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }

    log.debug("Finished XML transformation");
}

From source file:org.apache.accumulo.server.util.RestoreZookeeper.java

/**
 * @param args//w  w w  .ja v  a2s  . c  om
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    Logger.getRootLogger().setLevel(Level.WARN);
    Opts opts = new Opts();
    opts.parseArgs(RestoreZookeeper.class.getName(), args);

    InputStream in = System.in;
    if (opts.file != null) {
        in = new FileInputStream(opts.file);
    }

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    parser.parse(in, new Restore(ZooReaderWriter.getInstance(), opts.overwrite));
    in.close();
}

From source file:org.apache.axis.client.HappyClient.java

/**
 * Create a JAXP SAXParser/*  w w w  . java2s.c om*/
 * @return parser or null for trouble
 */
private SAXParser getSAXParser() {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    if (saxParserFactory == null) {
        return null;
    }
    SAXParser saxParser = null;
    try {
        saxParser = saxParserFactory.newSAXParser();
    } catch (Exception e) {
    }
    return saxParser;
}

From source file:org.apache.axis.utils.XMLUtils.java

/** Initialize the SAX parser factory.
 *
 * @param factoryClassName The (optional) class name of the desired
 *                         SAXParserFactory implementation. Will be
 *                         assigned to the system property
 *                         <b>javax.xml.parsers.SAXParserFactory</b>
 *                         unless this property is already set.
 *                         If <code>null</code>, leaves current setting
 *                         alone.//from   w w w . ja  v  a2s.com
 * @param namespaceAware true if we want a namespace-aware parser
 * @param validating true if we want a validating parser
 *
 */
public static void initSAXFactory(String factoryClassName, boolean namespaceAware, boolean validating) {
    if (factoryClassName != null) {
        try {
            saxFactory = (SAXParserFactory) Class.forName(factoryClassName).newInstance();
            /*
             * Set the system property only if it is not already set to
             * avoid corrupting environments in which Axis is embedded.
             */
            if (System.getProperty(saxParserFactoryProperty) == null) {
                System.setProperty(saxParserFactoryProperty, factoryClassName);
            }
        } catch (Exception e) {
            log.error(Messages.getMessage("exception00"), e);
            saxFactory = null;
        }
    } else {
        saxFactory = SAXParserFactory.newInstance();
    }
    saxFactory.setNamespaceAware(namespaceAware);
    saxFactory.setValidating(validating);

    // Discard existing parsers
    saxParsers.clear();
}

From source file:org.apache.flex.compiler.internal.config.FileConfigurator.java

/**
 * Load configuration XML file into a {@link ConfigurationBuffer} object.
 * //from w  w w.j  a  v  a  2  s.  c o  m
 * @param buffer result {@link ConfigurationBuffer} object.
 * @param fileSpec configuration XML file.
 * @param context path context used for resolving relative paths in the
 * configuration options.
 * @param rootElement expected root element of the XML DOM tree.
 * @param ignoreUnknownItems if false, unknown option will cause exception.
 * @throws ConfigurationException error.
 */
public static void load(final ConfigurationBuffer buffer, final IFileSpecification fileSpec,
        final String context, final String rootElement, boolean ignoreUnknownItems)
        throws ConfigurationException {
    final String path = fileSpec.getPath();
    final Handler h = new Handler(buffer, path, context, rootElement, ignoreUnknownItems);
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    Reader reader = null;
    try {
        reader = fileSpec.createReader();
        final SAXParser parser = factory.newSAXParser();
        final InputSource source = new InputSource(reader);
        parser.parse(source, h);
    } catch (SAXConfigurationException e) {
        throw e.innerException;
    } catch (SAXParseException e) {
        throw new ConfigurationException.OtherThrowable(e, null, path, e.getLineNumber());
    } catch (Exception e) {
        throw new ConfigurationException.OtherThrowable(e, null, path, -1);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:org.apache.fop.accessibility.AccessibilityPreprocessor.java

/** {@inheritDoc} */
public void endDocument() throws SAXException {
    super.endDocument();
    // do the second transform to struct
    try {//from   w  w  w.ja  va 2  s.co  m
        //TODO this must be optimized, no buffering (ex. SAX-based tee-proxy)
        byte[] enrichedFO = enrichedFOBuffer.toByteArray();
        Source src = new StreamSource(new ByteArrayInputStream(enrichedFO));
        DOMResult res = new DOMResult();
        reduceFOTree.transform(src, res);
        StructureTree structureTree = new StructureTree();
        NodeList pageSequences = res.getNode().getFirstChild().getChildNodes();
        for (int i = 0; i < pageSequences.getLength(); i++) {
            structureTree.addPageSequenceStructure(pageSequences.item(i).getChildNodes());
        }
        userAgent.setStructureTree(structureTree);

        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);
        saxParserFactory.setValidating(false);
        SAXParser saxParser = saxParserFactory.newSAXParser();
        InputStream in = new ByteArrayInputStream(enrichedFO);
        saxParser.parse(in, fopHandler);
    } catch (Exception e) {
        throw new SAXException(e);
    }
}

From source file:org.apache.fop.cli.InputHandler.java

private XMLReader getXMLReader() throws ParserConfigurationException, SAXException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setFeature("http://xml.org/sax/features/namespaces", true);
    spf.setFeature("http://apache.org/xml/features/xinclude", true);
    XMLReader xr = spf.newSAXParser().getXMLReader();
    return xr;//from  w ww.java 2 s  .  c o m
}

From source file:org.apache.fop.complexscripts.fonts.ttx.TTXFile.java

public void parse(File f) {
    assert f != null;
    try {/*from w ww. jav a 2  s .c om*/
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        sp.parse(f, new Handler());
    } catch (FactoryConfigurationError e) {
        throw new RuntimeException(e.getMessage());
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e.getMessage());
    } catch (SAXException e) {
        throw new RuntimeException(e.getMessage());
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }
}