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:nl.coinsweb.sdk.FileManager.java

public static String getXmlBaseOrxmlns(File xmlFile) {
    final ArrayList<String> baseUriDropHere = new ArrayList<>();
    final ArrayList<String> xmlnsDropHere = new ArrayList<>();

    DefaultHandler handler = new DefaultHandler() {

        @Override//w ww .j a v a 2s  . c o m
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {

            if ("rdf:RDF".equals(qName)) {
                for (int i = 0; i < attributes.getLength(); i++) {
                    if ("xml:base".equals(attributes.getQName(i))) {
                        baseUriDropHere.add(attributes.getValue(i));
                    }
                    if ("xmlns".equals(attributes.getQName(i))) {
                        xmlnsDropHere.add(attributes.getValue(i));
                    }
                }
                return;
            }
        }
    };

    try {

        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        SAXParser parser = factory.newSAXParser();
        parser.parse(xmlFile, handler);

    } catch (ParserConfigurationException e) {
        // do not print this, this is supposed to crash for non-xml files
    } catch (SAXException e) {
        // do not print this, this is supposed to crash for non-xml files
    } catch (IOException e) {
        log.error("problem reading xml file", e);
    }

    if (baseUriDropHere.isEmpty()) {
        if (xmlnsDropHere.isEmpty()) {
            return null;
        } else {
            return xmlnsDropHere.get(0);
        }
    } else {
        return baseUriDropHere.get(0);
    }
}

From source file:nl.nn.adapterframework.validation.JavaxXmlValidator.java

@Override
public XMLReader createValidatingParser(IPipeLineSession session, ValidationContext context)
        throws XmlValidatorException, PipeRunException {
    SAXParser parser;//from   w w w .  j  ava  2 s . com
    try {
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setValidating(false);
        parserFactory.setNamespaceAware(true);
        parserFactory.setFeature(PARSING_FEATURE_SECURE, true);
        //parserFactory.setFeature(PARSING_FEATURE_EXTERNAL_GENERAL_ENTITIES, false);
        //parserFactory.setFeature(PARSING_FEATURE_EXTERNAL_PARAMETER_ENTITIES, false);
        //parserFactory.setFeature(PARSING_FEATURE_DISALLOW_INLINE_DOCTYPE, true);

        Schema schema = getSchemaObject(context.getSchemasId(), schemasProvider.getSchemas(session));
        parserFactory.setSchema(schema);

        parser = parserFactory.newSAXParser();
        return parser.getXMLReader();
    } catch (ParserConfigurationException e) {
        throw new XmlValidatorException(logPrefix + "cannot configure parser", e);
    } catch (ConfigurationException e) {
        throw new XmlValidatorException(logPrefix + "cannot configure parser", e);
    } catch (SAXException e) {
        throw new XmlValidatorException(logPrefix + "cannot create parser", e);
    }
}

From source file:no.uio.medicine.virsurveillance.parserTests.SaxTest.java

private static void loadXMLDatabase() {
    try {//from  w w  w  . j a  va 2 s. c om
        SQLManagement sqlM = new SQLManagement();
        sqlM.connect2DB();

        //Load the file
        File inputFile = new File(PUBMED_SAMPLE_XML_FILE_NAME);
        //Create the parser
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser myXMLParser = spf.newSAXParser();
        SaxXMLProcess myHandler = new SaxXMLProcess(batchSize, sqlM);
        myXMLParser.parse(inputFile, myHandler);
        //myHandler.printTitles();
        //xr.
        //cosa=xr.parse(PUBMED_SAMPLE_XML_FILE_NAME);*/

        sqlM.closeDB();
        //System.out.println(sqlM.addAuthor2DB(new PubmedAuthor("Coyote","John")));
    } catch (SQLException ex) {
        Logger.getLogger(SaxTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(SaxTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ome.dsl.SaxReader.java

private void init() {
    try {/*from  ww w.  j a  v a2s .c o  m*/
        SAXParserFactory factory = SAXParserFactory.newInstance();
        parser = factory.newSAXParser();

        // XMLReader reader = parser.getXMLReader();
    } catch (Exception e) {
        throw new RuntimeException("Error setting up SaxReader :\n" + e.getMessage(), e);
    }
}

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

/**
 * Returns list of known subscriptions./*  w  ww  .  j  a  v  a2s  .  c  o 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.content.selector.RootElementNameContentWorkerSelector.java

public RootElementNameContentWorkerSelector() {
    saxParserFactory = SAXParserFactory.newInstance();
    supportedMimetypes = new HashSet<String>();
    supportedMimetypes.add(MimetypeMap.MIMETYPE_XML);
    workersByRootElementName = Collections.emptyMap();
}

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);
    }/* w  w  w.j  a v a 2 s  .c o  m*/

    /**
     * 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 {/*from  w w w.  j  av a2s  .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 w w.  ja va  2  s.  c o  m

    /**
     * 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);
        }
    }
}