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:nl.b3p.ogc.utils.OgcWfsClient.java

public static AnyNode xmlStringToAnyNode(String xml) throws Exception {
    AnyNode anyNode = null;/*from   w w w .ja va 2  s.c  om*/
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        XMLReader reader = saxParser.getXMLReader();

        org.exolab.castor.xml.util.SAX2ANY handler = new org.exolab.castor.xml.util.SAX2ANY();

        IgnoreEntityResolver r = new IgnoreEntityResolver();
        reader.setEntityResolver(r);

        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);
        InputSource source = new InputSource(new StringReader(xml));
        reader.parse(source);

        anyNode = handler.getStartingNode();
    } catch (Exception e) {
        log.error("error", e);
    }
    return anyNode;

}

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//  ww  w.j  ava 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.extensions.rekenbox.Adios2XmlPipe.java

protected void initializeConversionTables() throws ConfigurationException {
    // lees de template file en store het in een hashtable
    if (StringUtils.isNotEmpty(getAdiosDefinities())) {

        rubriek2nummer = new Hashtable(3000);
        record2nummer = new Hashtable(1000);
        nummer2rubriek = new Hashtable(3000);
        nummer2record = new Hashtable(1000);

        try {// ww  w . ja  v  a2s. c o  m
            handler = new Xml2AdiosHandler();
            SAXParserFactory parserFactory = XmlUtils.getSAXParserFactory();
            saxParser = parserFactory.newSAXParser();
        } catch (Throwable e) {
            throw new ConfigurationException(getLogPrefix(null) + "cannot configure a parser", e);
        }

        try {
            URL url = ClassUtils.getResourceURL(classLoader, getAdiosDefinities());
            if (url == null) {
                throw new ConfigurationException(getLogPrefix(null)
                        + "cannot find adios definitions from resource [" + getAdiosDefinities() + "]");
            }
            BufferedReader bufinput = new BufferedReader(new InputStreamReader(url.openStream()));
            String line, labelnr, waarde;

            line = bufinput.readLine();

            labelnr = "";
            waarde = "";

            // read in the rubrieken
            while (line != null && !waarde.equals(recordIdentifier)) {
                StringTokenizer st = new StringTokenizer(line, "{};= \n");
                if (st.countTokens() >= 1) {
                    waarde = st.nextToken();
                    if (!waarde.equals(recordIdentifier)) {
                        waarde = waarde.substring(3);
                    }
                    if (st.hasMoreTokens()) {
                        labelnr = st.nextToken();
                        //System.out.println("Rubriek label: " + labelnr + "   \t" + waarde);
                        if (alldigits(labelnr)) {
                            //System.out.println("rubriek label: " + labelnr + "   \t" + waarde);

                            // als de key al bestaat betekend dit dat er een fout zit in de invoer
                            if (nummer2rubriek.containsKey(labelnr)) {
                                throw new ConfigurationException(getLogPrefix(null) + "rubriek [" + labelnr
                                        + "] komt meermaals voor. Waarde1: [" + nummer2rubriek.get(labelnr)
                                        + "], Waarde2: [" + waarde + "]");
                            }
                            nummer2rubriek.put(labelnr, waarde);
                            rubriek2nummer.put(waarde, labelnr);
                        }
                    }

                }
                line = bufinput.readLine();
            }

            // Read in the records
            while (line != null) {
                StringTokenizer st1 = new StringTokenizer(line, "{};= \n");
                if (st1.countTokens() >= 1) {
                    waarde = st1.nextToken();
                    waarde = waarde.substring(3);
                    if (st1.hasMoreTokens()) {
                        labelnr = st1.nextToken();
                        //System.out.println("Record label: " + labelnr + "   \t" + waarde);
                        if (alldigits(labelnr)) {
                            //labeln = Integer.parseInt(labelnr);
                            //System.out.println("record label: " + labelnr + "   \t" + waarde);

                            if (nummer2record.containsKey(labelnr)) {
                                throw new ConfigurationException(getLogPrefix(null) + "record [" + labelnr
                                        + "] komt meermaals voor. Waarde1: [" + nummer2record.get(labelnr)
                                        + "], Waarde2: [" + waarde + "]");
                            }
                            nummer2record.put(labelnr, waarde);
                            record2nummer.put(waarde, labelnr);
                        }
                    }

                }

                line = bufinput.readLine();
            }
            bufinput.close();
        } catch (IOException e) {
            throw new ConfigurationException(
                    getLogPrefix(null) + "IOException on [" + getAdiosDefinities() + "]", e);
        }
    }
}

From source file:nl.nn.adapterframework.pipes.XmlFileElementIteratorPipe.java

protected void iterateInput(Object input, IPipeLineSession session, String correlationID, Map threadContext,
        ItemCallback callback) throws SenderException, TimeOutException {
    InputStream xmlInput;//from   www  . jav  a 2  s .  c o m
    try {
        xmlInput = new FileInputStream((String) input);
    } catch (FileNotFoundException e) {
        throw new SenderException("could not find file [" + input + "]", e);
    }
    ItemCallbackCallingHandler handler = new ItemCallbackCallingHandler(callback);

    log.debug("obtaining list of elements [" + getElementName() + "] using sax parser");
    try {
        SAXParserFactory parserFactory = XmlUtils.getSAXParserFactory();
        parserFactory.setNamespaceAware(true);
        SAXParser saxParser = parserFactory.newSAXParser();
        saxParser.parse(xmlInput, handler);
    } catch (Exception e) {
        if (handler.getTimeOutException() != null) {
            throw handler.getTimeOutException();
        }
        if (!handler.isStopRequested()) {
            throw new SenderException(
                    "Could not extract list of elements [" + getElementName() + "] using sax parser", e);
        }
    }
}

From source file:nl.nn.adapterframework.processors.InputOutputPipeProcessor.java

public PipeRunResult processPipe(PipeLine pipeLine, IPipe pipe, String messageId, Object message,
        IPipeLineSession pipeLineSession) throws PipeRunException {
    Object preservedObject = message;
    PipeRunResult pipeRunResult = null;//from w w  w  .  j a  va2 s  .  com
    INamedObject owner = pipeLine.getOwner();

    IExtendedPipe pe = null;

    if (pipe instanceof IExtendedPipe) {
        pe = (IExtendedPipe) pipe;
    }

    if (pe != null) {
        if (StringUtils.isNotEmpty(pe.getGetInputFromSessionKey())) {
            if (log.isDebugEnabled())
                log.debug("Pipeline of adapter [" + owner.getName() + "] replacing input for pipe ["
                        + pe.getName() + "] with contents of sessionKey [" + pe.getGetInputFromSessionKey()
                        + "]");
            message = pipeLineSession.get(pe.getGetInputFromSessionKey());
        }
        if (StringUtils.isNotEmpty(pe.getGetInputFromFixedValue())) {
            if (log.isDebugEnabled())
                log.debug("Pipeline of adapter [" + owner.getName() + "] replacing input for pipe ["
                        + pe.getName() + "] with fixed value [" + pe.getGetInputFromFixedValue() + "]");
            message = pe.getGetInputFromFixedValue();
        }
        if ((message == null || StringUtils.isEmpty(message.toString()))
                && StringUtils.isNotEmpty(pe.getEmptyInputReplacement())) {
            if (log.isDebugEnabled())
                log.debug("Pipeline of adapter [" + owner.getName() + "] replacing empty input for pipe ["
                        + pe.getName() + "] with fixed value [" + pe.getEmptyInputReplacement() + "]");
            message = pe.getEmptyInputReplacement();
        }
    }

    if (pipe instanceof FixedForwardPipe) {
        FixedForwardPipe ffPipe = (FixedForwardPipe) pipe;
        pipeRunResult = ffPipe.doInitialPipe(message, pipeLineSession);
    }

    if (pipeRunResult == null) {
        pipeRunResult = pipeProcessor.processPipe(pipeLine, pipe, messageId, message, pipeLineSession);
    }
    if (pipeRunResult == null) {
        throw new PipeRunException(pipe, "Pipeline of [" + pipeLine.getOwner().getName()
                + "] received null result from pipe [" + pipe.getName() + "]d");
    }

    if (pe != null) {
        if (pe.isRestoreMovedElements()) {
            if (log.isDebugEnabled())
                log.debug("Pipeline of adapter [" + owner.getName()
                        + "] restoring from compacted result for pipe [" + pe.getName() + "]");
            Object result = pipeRunResult.getResult();
            if (result != null) {
                String resultString = (String) result;
                pipeRunResult.setResult(restoreMovedElements(resultString, pipeLineSession));
            }
        }

        if (pe.getChompCharSize() != null || pe.getElementToMove() != null
                || pe.getElementToMoveChain() != null) {
            log.debug("Pipeline of adapter [" + owner.getName() + "] compact received message");
            Object result = pipeRunResult.getResult();
            if (result != null) {
                String resultString = (String) result;
                try {
                    InputStream xmlInput = IOUtils.toInputStream(resultString, "UTF-8");
                    CompactSaxHandler handler = new CompactSaxHandler();
                    handler.setChompCharSize(pe.getChompCharSize());
                    handler.setElementToMove(pe.getElementToMove());
                    handler.setElementToMoveChain(pe.getElementToMoveChain());
                    handler.setElementToMoveSessionKey(pe.getElementToMoveSessionKey());
                    handler.setRemoveCompactMsgNamespaces(pe.isRemoveCompactMsgNamespaces());
                    handler.setContext(pipeLineSession);
                    SAXParserFactory parserFactory = XmlUtils.getSAXParserFactory();
                    parserFactory.setNamespaceAware(true);
                    SAXParser saxParser = parserFactory.newSAXParser();
                    try {
                        saxParser.parse(xmlInput, handler);
                        resultString = handler.getXmlString();
                    } catch (Exception e) {
                        log.warn("Pipeline of adapter [" + owner.getName()
                                + "] could not compact received message: " + e.getMessage());
                    }
                    handler = null;
                } catch (Exception e) {
                    throw new PipeRunException(pipe,
                            "Pipeline of [" + pipeLine.getOwner().getName()
                                    + "] got error during compacting received message to more compact format: "
                                    + e.getMessage());
                }
                pipeRunResult.setResult(resultString);
            }
        }

        if (StringUtils.isNotEmpty(pe.getStoreResultInSessionKey())) {
            if (log.isDebugEnabled())
                log.debug("Pipeline of adapter [" + owner.getName() + "] storing result for pipe ["
                        + pe.getName() + "] under sessionKey [" + pe.getStoreResultInSessionKey() + "]");
            Object result = pipeRunResult.getResult();
            pipeLineSession.put(pe.getStoreResultInSessionKey(), result);
        }
        if (pe.isPreserveInput()) {
            pipeRunResult.setResult(preservedObject);
        }
    }

    if (pe != null) {
        if (secLogEnabled && pe.isWriteToSecLog()) {
            String secLogMsg = "adapter [" + owner.getName() + "] pipe [" + pe.getName() + "]";
            if (pe.getSecLogSessionKeys() != null) {
                String sk = "";
                StringTokenizer st = new StringTokenizer(pe.getSecLogSessionKeys(), " ,;");
                while (st.hasMoreTokens()) {
                    if (sk.length() > 0) {
                        sk = sk + ",";
                    }
                    String key = st.nextToken();
                    Object value = pipeLineSession.get(key);
                    sk = sk + key + "=" + value;
                }
                secLogMsg = secLogMsg + " sessionKeys [" + sk + "]";
            }
            secLog.info(secLogMsg);
        }
    }

    return pipeRunResult;
}

From source file:nl.nn.adapterframework.receivers.ReceiverBase.java

private String processMessageInAdapter(IListener origin, Object rawMessage, String message, String messageId,
        String technicalCorrelationId, Map threadContext, long waitingDuration, boolean manualRetry)
        throws ListenerException {
    String result = null;/*w w  w  .  j ava  2 s.  c  o m*/
    PipeLineResult pipeLineResult = null;
    long startProcessingTimestamp = System.currentTimeMillis();
    //      if (message==null) {
    //         requestSizeStatistics.addValue(0);
    //      } else {
    //         requestSizeStatistics.addValue(message.length());
    //      }
    lastMessageDate = startProcessingTimestamp;
    log.debug(getLogPrefix() + "received message with messageId [" + messageId + "] (technical) correlationId ["
            + technicalCorrelationId + "]");

    if (StringUtils.isEmpty(messageId)) {
        messageId = Misc.createSimpleUUID();
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "generated messageId [" + messageId + "]");
    }

    if (getChompCharSize() != null || getElementToMove() != null || getElementToMoveChain() != null) {
        log.debug(getLogPrefix() + "compact received message");
        try {
            InputStream xmlInput = IOUtils.toInputStream(message, "UTF-8");
            CompactSaxHandler handler = new CompactSaxHandler();
            handler.setChompCharSize(getChompCharSize());
            handler.setElementToMove(getElementToMove());
            handler.setElementToMoveChain(getElementToMoveChain());
            handler.setElementToMoveSessionKey(getElementToMoveSessionKey());
            handler.setRemoveCompactMsgNamespaces(isRemoveCompactMsgNamespaces());
            if (threadContext != null) {
                handler.setContext(threadContext);
            }
            SAXParserFactory parserFactory = XmlUtils.getSAXParserFactory();
            parserFactory.setNamespaceAware(true);
            SAXParser saxParser = parserFactory.newSAXParser();
            try {
                saxParser.parse(xmlInput, handler);
                message = handler.getXmlString();
            } catch (Exception e) {
                warn("received message could not be compacted: " + e.getMessage());
            }
            handler = null;
        } catch (Exception e) {
            throw new ListenerException(
                    "error during compacting received message to more compact format: " + e.getMessage());
        }
    }

    String businessCorrelationId = null;
    if (correlationIDTp != null) {
        try {
            businessCorrelationId = correlationIDTp.transform(message, null);
        } catch (Exception e) {
            //throw new ListenerException(getLogPrefix()+"could not extract businessCorrelationId",e);
            log.warn(getLogPrefix() + "could not extract businessCorrelationId");
        }
        if (StringUtils.isEmpty(businessCorrelationId)) {
            String cidText;
            if (StringUtils.isNotEmpty(getCorrelationIDXPath())) {
                cidText = "xpathExpression [" + getCorrelationIDXPath() + "]";
            } else {
                cidText = "styleSheet [" + getCorrelationIDStyleSheet() + "]";
            }
            if (StringUtils.isNotEmpty(technicalCorrelationId)) {
                log.info(getLogPrefix() + "did not find correlationId using " + cidText
                        + ", reverting to correlationId of transfer [" + technicalCorrelationId + "]");
                businessCorrelationId = technicalCorrelationId;
            }
        }
    } else {
        businessCorrelationId = technicalCorrelationId;
    }
    if (StringUtils.isEmpty(businessCorrelationId)) {
        if (StringUtils.isNotEmpty(messageId)) {
            log.info(getLogPrefix() + "did not find (technical) correlationId, reverting to messageId ["
                    + messageId + "]");
            businessCorrelationId = messageId;
        }
    }
    log.info(getLogPrefix() + "messageId [" + messageId + "] technicalCorrelationId [" + technicalCorrelationId
            + "] businessCorrelationId [" + businessCorrelationId + "]");
    threadContext.put(IPipeLineSession.businessCorrelationIdKey, businessCorrelationId);
    String label = null;
    if (labelTp != null) {
        try {
            label = labelTp.transform(message, null);
        } catch (Exception e) {
            //throw new ListenerException(getLogPrefix()+"could not extract label",e);
            log.warn(getLogPrefix() + "could not extract label: (" + ClassUtils.nameOf(e) + ") "
                    + e.getMessage());
        }
    }
    if (hasProblematicHistory(messageId, manualRetry, rawMessage, message, threadContext,
            businessCorrelationId)) {
        if (!isTransacted()) {
            log.warn(getLogPrefix() + "received message with messageId [" + messageId
                    + "] which has a problematic history; aborting processing");
        }
        numRejected.increase();
        return result;
    }
    if (isDuplicateAndSkip(getMessageLog(), messageId, businessCorrelationId)) {
        numRejected.increase();
        return result;
    }
    if (getCachedProcessResult(messageId) != null) {
        numRetried.increase();
    }

    int txOption = this.getTransactionAttributeNum();
    TransactionDefinition txDef = SpringTxManagerProxy.getTransactionDefinition(txOption,
            getTransactionTimeout());
    //TransactionStatus txStatus = txManager.getTransaction(txDef);
    IbisTransaction itx = new IbisTransaction(txManager, txDef, "receiver [" + getName() + "]");
    TransactionStatus txStatus = itx.getStatus();

    // update processing statistics
    // count in processing statistics includes messages that are rolled back to input
    startProcessingMessage(waitingDuration);

    IPipeLineSession pipelineSession = null;
    String errorMessage = "";
    boolean messageInError = false;
    try {
        String pipelineMessage;
        if (origin instanceof IBulkDataListener) {
            try {
                IBulkDataListener bdl = (IBulkDataListener) origin;
                pipelineMessage = bdl.retrieveBulkData(rawMessage, message, threadContext);
            } catch (Throwable t) {
                errorMessage = t.getMessage();
                messageInError = true;
                ListenerException l = wrapExceptionAsListenerException(t);
                throw l;
            }
        } else {
            pipelineMessage = message;
        }

        numReceived.increase();
        // Note: errorMessage is used to pass value from catch-clause to finally-clause!
        pipelineSession = createProcessingContext(businessCorrelationId, threadContext, messageId);
        //         threadContext=pipelineSession; // this is to enable Listeners to use session variables, for instance in afterProcessMessage()
        try {
            if (getMessageLog() != null) {
                getMessageLog().storeMessage(messageId, businessCorrelationId, new Date(),
                        RCV_MESSAGE_LOG_COMMENTS, label, pipelineMessage);
            }
            log.debug(getLogPrefix() + "preparing TimeoutGuard");
            TimeoutGuard tg = new TimeoutGuard("Receiver " + getName());
            try {
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "activating TimeoutGuard with transactionTimeout ["
                            + transactionTimeout + "]s");
                tg.activateGuard(getTransactionTimeout());
                pipeLineResult = adapter.processMessageWithExceptions(businessCorrelationId, pipelineMessage,
                        pipelineSession);
                pipelineSession.put("exitcode", "" + pipeLineResult.getExitCode());
                result = pipeLineResult.getResult();
                errorMessage = "exitState [" + pipeLineResult.getState() + "], result [" + result + "]";
                if (log.isDebugEnabled()) {
                    log.debug(getLogPrefix() + "received result: " + errorMessage);
                }
                messageInError = txStatus.isRollbackOnly();
            } finally {
                log.debug(getLogPrefix() + "canceling TimeoutGuard, isInterrupted ["
                        + Thread.currentThread().isInterrupted() + "]");
                if (tg.cancel()) {
                    errorMessage = "timeout exceeded";
                    if (StringUtils.isEmpty(result)) {
                        result = "<timeout/>";
                    }
                    messageInError = true;
                }
            }
            if (!messageInError && !isTransacted()) {
                String commitOnState = ((Adapter) adapter).getPipeLine().getCommitOnState();

                if (StringUtils.isNotEmpty(commitOnState)
                        && !commitOnState.equalsIgnoreCase(pipeLineResult.getState())) {
                    messageInError = true;
                }
            }
        } catch (Throwable t) {
            if (TransactionSynchronizationManager.isActualTransactionActive()) {
                log.debug("<*>" + getLogPrefix() + "TX Update: Received failure, transaction "
                        + (txStatus.isRollbackOnly() ? "already" : "not yet") + " marked for rollback-only");
            }
            errorMessage = t.getMessage();
            messageInError = true;
            if (pipeLineResult == null) {
                pipeLineResult = new PipeLineResult();
            }
            if (StringUtils.isEmpty(pipeLineResult.getResult())) {
                String formattedErrorMessage = adapter.formatErrorMessage("exception caught", t, message,
                        messageId, this, startProcessingTimestamp);
                pipeLineResult.setResult(formattedErrorMessage);
            }
            ListenerException l = wrapExceptionAsListenerException(t);
            throw l;
        } finally {
            putSessionKeysIntoThreadContext(threadContext, pipelineSession);
        }
        //         if (result==null) {
        //            responseSizeStatistics.addValue(0);
        //         } else {
        //            responseSizeStatistics.addValue(result.length());
        //         }
        if (getSender() != null) {
            String sendMsg = sendResultToSender(technicalCorrelationId, result);
            if (sendMsg != null) {
                errorMessage = sendMsg;
            }
        }
    } finally {
        cacheProcessResult(messageId, businessCorrelationId, errorMessage, new Date(startProcessingTimestamp));
        if (!isTransacted() && messageInError) {
            if (!manualRetry) {
                moveInProcessToError(messageId, businessCorrelationId, message,
                        new Date(startProcessingTimestamp), errorMessage, rawMessage, TXNEW_CTRL);
            }
        }
        try {
            Map afterMessageProcessedMap;
            if (threadContext != null) {
                afterMessageProcessedMap = threadContext;
                if (pipelineSession != null) {
                    threadContext.putAll(pipelineSession);
                }
            } else {
                afterMessageProcessedMap = pipelineSession;
            }
            origin.afterMessageProcessed(pipeLineResult, rawMessage, afterMessageProcessedMap);
        } finally {
            long finishProcessingTimestamp = System.currentTimeMillis();
            finishProcessingMessage(finishProcessingTimestamp - startProcessingTimestamp);
            if (!txStatus.isCompleted()) {
                // NB: Spring will take care of executing a commit or a rollback;
                // Spring will also ONLY commit the transaction if it was newly created
                // by the above call to txManager.getTransaction().
                //txManager.commit(txStatus);
                itx.commit();
            } else {
                throw new ListenerException(
                        getLogPrefix() + "Transaction already completed; we didn't expect this");
            }
        }
    }
    if (log.isDebugEnabled())
        log.debug(getLogPrefix() + "messageId [" + messageId + "] correlationId [" + businessCorrelationId
                + "] returning result [" + result + "]");
    return result;
}

From source file:nl.nn.adapterframework.util.XmlUtils.java

public static SAXSource stringToSAXSource(String xmlString, boolean namespaceAware,
        boolean resolveExternalEntities) throws DomBuilderException {
    Variant in = new Variant(xmlString);
    InputSource is = in.asXmlInputSource();
    SAXParserFactory factory = getSAXParserFactory(namespaceAware);
    try {//  w  w  w.j  a va2  s .  c  o  m
        XMLReader xmlReader = factory.newSAXParser().getXMLReader();
        if (!resolveExternalEntities) {
            xmlReader.setEntityResolver(new XmlExternalEntityResolver());
        }
        return new SAXSource(xmlReader, is);
    } catch (Exception e) {
        // TODO Use DomBuilderException as the stringToSource and calling
        // methods use them a lot. Rename DomBuilderException to
        // SourceBuilderException?
        throw new DomBuilderException(e);
    }
}

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

@Override
public XMLReader createValidatingParser(IPipeLineSession session, ValidationContext context)
        throws XmlValidatorException, PipeRunException {
    SAXParser parser;// w  w  w.  j a va 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 ww.  j av  a  2  s. com
        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 www.j a va  2s .  c om
        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);
    }
}