Example usage for javax.xml.parsers SAXParserFactory newSAXParser

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

Introduction

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

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:org.adblockplus.android.AdblockPlus.java

/**
 * Returns list of known subscriptions./*from  ww w  .  j a  v  a2 s . co  m*/
 */
public List<Subscription> getSubscriptions() {
    if (subscriptions == null) {
        subscriptions = new ArrayList<Subscription>();

        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser;
        try {
            parser = factory.newSAXParser();
            parser.parse(getAssets().open("subscriptions.xml"), new SubscriptionParser(subscriptions));
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, e.getMessage(), e);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, e.getMessage(), e);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, e.getMessage(), e);
        }
    }
    return subscriptions;
}

From source file:org.alfresco.repo.transfer.fsr.FileTransferReceiver.java

public void commit(String transferId) throws TransferException {
    if (log.isDebugEnabled()) {
        log.debug("Committing transferId=" + transferId);
    }/*from   www . j a  v a2  s.  c  om*/

    /**
     * A side-effect of checking the lock here is that it ensures that the lock timeout is suspended.
     */
    checkLock(transferId);

    final String fTransferId = transferId;

    try {
        progressMonitor.updateStatus(transferId, TransferProgress.Status.COMMITTING);

        List<TransferManifestProcessor> commitProcessors = manifestProcessorFactory
                .getCommitProcessors(FileTransferReceiver.this, fTransferId);

        try {
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            SAXParser parser = saxParserFactory.newSAXParser();
            File snapshotFile = getSnapshotFile(fTransferId);

            if (snapshotFile.exists()) {
                if (log.isDebugEnabled()) {
                    log.debug("Processing manifest file:" + snapshotFile.getAbsolutePath());
                }
                // We parse the file as many times as we have processors
                for (TransferManifestProcessor processor : commitProcessors) {
                    XMLTransferManifestReader reader = new XMLTransferManifestReader(processor);
                    parser.parse(snapshotFile, reader);
                    parser.reset();
                }
            } else {
                progressMonitor.logException(fTransferId, "Unable to start commit. No snapshot file received",
                        new TransferException(MSG_NO_SNAPSHOT_RECEIVED, new Object[] { fTransferId }));
            }
        } catch (Exception ex) {
            progressMonitor.logException(transferId, "Caught exception while committing the transfer", ex);
        }

        //Was there an error? If so, change the transfer status to "ERROR" and throw the exception
        Throwable error = progressMonitor.getProgress(transferId).getError();
        if (error != null) {
            progressMonitor.updateStatus(transferId, TransferProgress.Status.ERROR);
            if (TransferException.class.isAssignableFrom(error.getClass())) {
                throw (TransferException) error;
            } else {
                throw new TransferException(MSG_ERROR_WHILE_COMMITTING_TRANSFER, new Object[] { transferId },
                        error);
            }
        }

        /**
         * If we get to this point then the commit has taken place without error.
         */
        progressMonitor.updateStatus(transferId, TransferProgress.Status.COMPLETE);
        if (log.isDebugEnabled()) {
            log.debug("Commit success transferId=" + transferId);
        }
    } finally {
        /**
         * Clean up at the end of the transfer
         */
        try {
            end(transferId);
        } catch (Exception ex) {
            log.error("Failed to clean up transfer. Lock may still be in place: " + transferId, ex);
        }

        // let's run postCommit
        if (postCommit != null && postCommit.size() > 0) {
            for (FSRRunnable runnable : postCommit) {
                try {
                    runnable.setTransferId(transferId);
                    runnable.run();
                } catch (Throwable t) {
                    log.error("Error from postCommit event t:" + t.toString(), t);
                }
            }
        }
    }

}

From source file:org.alfresco.repo.transfer.fsr.FileTransferReceiver.java

public void generateRequsite(String transferId, OutputStream requsiteStream) throws TransferException {
    log.debug("Generate Requisite for transfer:" + transferId);
    try {/*ww  w  .ja va 2  s. co  m*/
        File snapshotFile = getSnapshotFile(transferId);

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

            XMLTransferRequsiteWriter writer = new XMLTransferRequsiteWriter(dest);
            TransferManifestProcessor processor = manifestProcessorFactory
                    .getRequsiteProcessor(FileTransferReceiver.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 Requisite 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.report.TransferReporterImpl.java

/**
 * Create a new transfer report of success
 * /*w  w  w  .ja  va 2s  . c o m*/
 * @return NodeRef the node ref of the new transfer report
 */
public NodeRef createTransferReport(String transferName, Transfer transfer, TransferTarget target,
        TransferDefinition definition, List<TransferEvent> events, File snapshotFile) {
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>();

    String title = transferName;
    String description = "Transfer Report - target: " + target.getName();
    String name = transferName + ".xml";

    properties.put(ContentModel.PROP_NAME, name);
    properties.put(ContentModel.PROP_TITLE, title);
    properties.put(ContentModel.PROP_DESCRIPTION, description);
    ChildAssociationRef ref = nodeService.createNode(target.getNodeRef(), ContentModel.ASSOC_CONTAINS,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), TransferModel.TYPE_TRANSFER_REPORT,
            properties);
    ContentWriter writer = contentService.getWriter(ref.getChildRef(), ContentModel.PROP_CONTENT, true);
    writer.setLocale(Locale.getDefault());
    writer.setMimetype(MimetypeMap.MIMETYPE_XML);
    writer.setEncoding(DEFAULT_ENCODING);

    //
    final XMLTransferReportWriter reportWriter = new XMLTransferReportWriter();

    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(writer.getContentOutputStream()));

    try {
        reportWriter.startTransferReport(DEFAULT_ENCODING, bufferedWriter);

        // Header
        reportWriter.writeTarget(target);

        // Definition of transfer
        reportWriter.writeDefinition(definition);

        // Events of transfer
        reportWriter.writeTransferEvents(events);

        /**
         * Write the node summary details to the transfer report
         */
        TransferManifestProcessor processor = new TransferManifestProcessor() {
            public void processTransferManifestNode(TransferManifestNormalNode node) {

                try {
                    reportWriter.writeNodeSummary(node);
                } catch (SAXException error) {
                    error.printStackTrace();
                }
            }

            public void processTransferManifestNode(TransferManifestDeletedNode node) {
                try {
                    reportWriter.writeNodeSummary(node);
                } catch (SAXException error) {
                    error.printStackTrace();
                }
            }

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

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

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

        /**
         * Step 3: wire up the manifest reader to a manifest processor
         */
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser parser;
        parser = saxParserFactory.newSAXParser();
        XMLTransferManifestReader reader = new XMLTransferManifestReader(processor);

        /**
         * Step 4: start the magic Give the manifest file to the manifest reader
         */
        try {
            parser.parse(snapshotFile, reader);
        } catch (IOException error) {
            //TODO temp code
            error.printStackTrace();
            return null;
        }

        reportWriter.endTransferReport();

        return ref.getChildRef();
    }

    catch (SAXException se) {
        //TODO Temp code
        return null;
    } catch (ParserConfigurationException error) {
        // TODO temp code
        error.printStackTrace();
        return null;
    } finally {
        try {
            bufferedWriter.close();
        } catch (IOException error) {
            error.printStackTrace();
        }
    }
}

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

public void commit(final String transferId) throws TransferException {
    if (log.isDebugEnabled()) {
        log.debug("Committing transferId=" + transferId);
    }/*from w  ww  .j  a  v a2 s.com*/

    /**
     * A side-effect of checking the lock here is that it ensures that the lock timeout is suspended.
     */
    checkLock(transferId);

    /**
     * Turn off rules while transfer is being committed.
     */
    boolean rulesEnabled = ruleService.isEnabled();
    ruleService.disableRules();

    try {
        /* lock is going to be released */ checkLock(transferId);
        progressMonitor.updateStatus(transferId, Status.COMMITTING);

        RetryingTransactionHelper.RetryingTransactionCallback<Object> commitWork = new RetryingTransactionCallback<Object>() {
            public Object execute() throws Throwable {
                AlfrescoTransactionSupport.bindListener(
                        new TransferCommitTransactionListener(transferId, RepoTransferReceiverImpl.this));

                List<TransferManifestProcessor> commitProcessors = manifestProcessorFactory
                        .getCommitProcessors(RepoTransferReceiverImpl.this, transferId);

                Set<TransferSummaryReport> summaryReports = new HashSet<TransferSummaryReport>();

                SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
                SAXParser parser = saxParserFactory.newSAXParser();
                File snapshotFile = getSnapshotFile(transferId);

                if (snapshotFile.exists()) {
                    if (log.isDebugEnabled()) {
                        log.debug("Processing manifest file:" + snapshotFile.getAbsolutePath());
                    }
                    // We parse the file as many times as we have processors
                    for (TransferManifestProcessor processor : commitProcessors) {
                        XMLTransferManifestReader reader = new XMLTransferManifestReader(processor);

                        //behaviourFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE);
                        behaviourFilter.disableBehaviour();
                        if (processor instanceof TransferSummaryAware) {
                            summaryReports.add(((TransferSummaryAware) processor).getTransferSummaryReport());
                        }
                        try {
                            parser.parse(snapshotFile, reader);
                        } finally {
                            behaviourFilter.enableBehaviour();
                        }
                        parser.reset();
                    }

                    for (TransferSummaryReport transferSummaryReport : summaryReports) {
                        if (transferSummaryReport != null) {
                            transferSummaryReport.finishSummaryReport();
                        }
                    }
                } else {
                    progressMonitor.logException(transferId,
                            "Unable to start commit. No snapshot file received",
                            new TransferException(MSG_NO_SNAPSHOT_RECEIVED, new Object[] { transferId }));
                }
                return null;
            }
        };

        transactionService.getRetryingTransactionHelper().doInTransaction(commitWork, false, true);

        Throwable error = progressMonitor.getProgress(transferId).getError();
        if (error != null) {
            if (TransferException.class.isAssignableFrom(error.getClass())) {
                throw (TransferException) error;
            } else {
                throw new TransferException(MSG_ERROR_WHILE_COMMITTING_TRANSFER, new Object[] { transferId },
                        error);
            }
        }

        /**
         * Successfully committed
         */
        if (log.isDebugEnabled()) {
            log.debug("Commit success transferId=" + transferId);
        }
    } catch (Exception ex) {
        if (TransferException.class.isAssignableFrom(ex.getClass())) {
            throw (TransferException) ex;
        } else {
            throw new TransferException(MSG_ERROR_WHILE_COMMITTING_TRANSFER, ex);
        }
    } finally {
        if (rulesEnabled) {
            /**
             * Turn rules back on if we turned them off earlier.
             */
            ruleService.enableRules();
        }

        /**
         * Clean up at the end of the transfer
         */
        try {
            end(transferId);
        } catch (Exception ex) {
            log.error("Failed to clean up transfer. Lock may still be in place: " + transferId, ex);
        }
    }
}

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

/**
 * Generate the requsite//ww w.j av  a  2s .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;/*  w  w  w  .  j  a  v a2s . c om*/
    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 w  w w  .  ja v a2  s  .c o  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//from w  w w. ja  v  a 2s  .c o  m
 * @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 ww .  jav a  2 s. com
 * @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;
}