Example usage for javax.xml.parsers SAXParser parse

List of usage examples for javax.xml.parsers SAXParser parse

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser parse.

Prototype

public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException 

Source Link

Document

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.helpers.DefaultHandler .

Usage

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

private static void loadXMLDatabase() {
    try {//from  w w w  . j  a  va  2s . c  o  m
        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:org.adblockplus.android.AdblockPlus.java

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

/**
 * Performs a match of the root element name to find the correct content worker.
 *//*from   w w  w . j a v a 2s .  c  o  m*/
public W getWorker(ContentReader reader) {
    if (!supportedMimetypes.contains(reader.getMimetype())) {
        return null;
    }
    W worker = null;
    InputStream is = null;
    String rootElementName = null;
    try {
        is = reader.getContentInputStream();
        SAXParser saxParser = saxParserFactory.newSAXParser();
        saxParser.parse(is, this);
        // No match possible
    } catch (RootElementFoundException e) {
        rootElementName = e.getElementName();
        worker = workersByRootElementName.get(rootElementName);
    } catch (Throwable e) {
        throw new ContentIOException("\n" + "Failed to extract root element from XML document: \n"
                + "   Reader:   " + reader + "\n" + "   Selector: " + this, e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Throwable e) {
            }
        }
    }
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("\n" + "Chosen content worker for reader: \n" + "   Reader:       " + reader + "\n"
                + "   Root Element: " + rootElementName + "\n" + "   Worker:       " + worker);
    }
    return worker;
}

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  ww  .j  ava2s.co 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 ww.  j a  v a 2 s . c  o 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
 * //from w  w w.  ja  va2s  . c  om
 * @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  .  jav  a2  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);
        }
    }
}

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

/**
 * Generate the requsite//w  ww .  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;
    parser = saxParserFactory.newSAXParser();

    /**//  w w w. ja  va 2  s  .c o  m
     * 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.apache.accumulo.server.util.RestoreZookeeper.java

/**
 * @param args/*from   w  w  w .  j a v a  2 s.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();
}