Example usage for javax.xml.stream XMLInputFactory newInstance

List of usage examples for javax.xml.stream XMLInputFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.stream XMLInputFactory newInstance.

Prototype

public static XMLInputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:com.stevpet.sonar.plugins.dotnet.mscover.parser.XmlParserSubject.java

/**
 * Gets the cursor for the given file/*  ww w .j a  va2  s .c o m*/
 * 
 * @param file
 * @return
 * @throws FactoryConfigurationError
 * @throws XMLStreamException
 */
public SMInputCursor getCursorFromString(String string) {
    SMInputCursor result = null;
    try {
        SMInputFactory inf = new SMInputFactory(XMLInputFactory.newInstance());
        InputStream inputStream = new ByteArrayInputStream(string.getBytes());
        SMHierarchicCursor cursor = inf.rootElementCursor(inputStream);
        result = cursor.advance();
    } catch (XMLStreamException e) {
        String msg = "Could not create cursor " + e.getMessage();
        LOG.error(msg);
        throw new SonarException(msg, e);
    }
    return result;
}

From source file:edu.harvard.i2b2.eclipse.plugins.admin.utilities.ws.CRCServiceDriver.java

/**
 * Function to convert PFT requestPdo to OMElement
 * //  ww  w .  ja v a2s.c om
 * @param requestPdo   String requestPdo to send to PFT web service
 * @return An OMElement containing the PFT web service requestPdo
 */
public static OMElement getStatusPayLoad(String request) throws Exception {
    OMElement method = null;
    try {
        OMFactory fac = OMAbstractFactory.getOMFactory();

        StringReader strReader = new StringReader(request);
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader reader = xif.createXMLStreamReader(strReader);

        StAXOMBuilder builder = new StAXOMBuilder(reader);
        method = builder.getDocumentElement();
        //   method.addChild(lineItem);
    } catch (FactoryConfigurationError e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        log.error(e.getMessage());
        throw new Exception(e);
    }
    return method;
}

From source file:com.predic8.membrane.core.ws.relocator.Relocator.java

public void relocate(InputStreamReader isr) throws Exception {
    XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(isr);

    while (parser.hasNext()) {
        writer.add(getEvent(parser));// w  ww.jav a2 s  .c om
    }
    writer.flush();
}

From source file:TestXjc.java

private static void processXquery(String query, String input)
        throws XQException, ParserConfigurationException, SAXException, IOException, XMLStreamException {
    XQDataSource ds = new SaxonXQDataSource();
    XQConnection xqjc = ds.getConnection();
    XQPreparedExpression xqje = //xqjc.prepareExpression(new FileInputStream("/Users/kbw19/git/res/xjctestmvn/src/main/resources/transform/I2b2ToFhir/i2b2MedsToFHIRMeds.xquery"));
            xqjc.prepareExpression(new ByteArrayInputStream(query.getBytes(StandardCharsets.UTF_8)));

    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader streamReader = //factory.createXMLStreamReader(new FileReader("/Users/kbw19/git/res/xjctestmvn/src/main/resources/example/i2b2/i2b2medspod.txt"));
            factory.createXMLStreamReader(new StringReader(input));
    xqje.bindDocument(XQConstants.CONTEXT_ITEM, streamReader, xqjc.createDocumentType());

    XQResultSequence xqjs = xqje.executeQuery();

    xqjs.writeSequence(System.out, null);
}

From source file:microsoft.exchange.webservices.data.core.EwsXmlReader.java

/**
 * Initializes the XML reader.//www.j  a  va  2s  . c o m
 *
 * @param stream the stream
 * @return An XML reader to use.
 * @throws Exception on error
 */
protected XMLEventReader initializeXmlReader(InputStream stream) throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);

    return inputFactory.createXMLEventReader(stream);
}

From source file:edu.harvard.i2b2.eclipse.plugins.fr.ws.CrcServiceDriver.java

/**
 * Function to convert Ont requestVdo to OMElement
 * /*from w  w  w.  j a  va  2  s.c o  m*/
 * @param requestVdo   String requestVdo to send to Ont web service
 * @return An OMElement containing the Ont web service requestVdo
 */
public static OMElement getCrcPayLoad(String requestVdo) throws Exception {
    OMElement lineItem = null;
    try {
        StringReader strReader = new StringReader(requestVdo);
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader reader = xif.createXMLStreamReader(strReader);

        StAXOMBuilder builder = new StAXOMBuilder(reader);
        lineItem = builder.getDocumentElement();
    } catch (FactoryConfigurationError e) {
        log.error(e.getMessage());
        throw new Exception(e);
    }
    return lineItem;
}

From source file:com.activiti.service.activiti.ProcessDefinitionService.java

protected BpmnModel executeRequestForXML(HttpUriRequest request, ServerConfig serverConfig,
        int expectedStatusCode) {

    ActivitiServiceException exception = null;
    CloseableHttpClient client = clientUtil.getHttpClient(serverConfig);
    try {/*from  w  ww  .  j av a 2 s  .c  o m*/
        CloseableHttpResponse response = client.execute(request);

        try {
            InputStream responseContent = response.getEntity().getContent();
            XMLInputFactory xif = XMLInputFactory.newInstance();
            InputStreamReader in = new InputStreamReader(responseContent, "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(in);
            BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);

            boolean success = response.getStatusLine() != null
                    && response.getStatusLine().getStatusCode() == expectedStatusCode;

            if (success) {
                return bpmnModel;
            } else {
                exception = new ActivitiServiceException(
                        "An error occured while calling Activiti: " + response.getStatusLine());
            }
        } catch (Exception e) {
            log.warn("Error consuming response from uri " + request.getURI(), e);
            exception = clientUtil.wrapException(e, request);
        } finally {
            response.close();
        }

    } catch (Exception e) {
        log.error("Error executing request to uri " + request.getURI(), e);
        exception = clientUtil.wrapException(e, request);

    } finally {
        try {
            client.close();
        } catch (Exception e) {
            log.warn("Error closing http client instance", e);
        }
    }

    if (exception != null) {
        throw exception;
    }

    return null;
}

From source file:org.flowable.admin.service.engine.ProcessDefinitionService.java

protected BpmnModel executeRequestForXML(HttpUriRequest request, ServerConfig serverConfig,
        int expectedStatusCode) {

    FlowableServiceException exception = null;
    CloseableHttpClient client = clientUtil.getHttpClient(serverConfig);
    try {/*w w w.  java 2s  . c o  m*/
        CloseableHttpResponse response = client.execute(request);

        try {
            InputStream responseContent = response.getEntity().getContent();
            XMLInputFactory xif = XMLInputFactory.newInstance();
            InputStreamReader in = new InputStreamReader(responseContent, "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(in);
            BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);

            boolean success = response.getStatusLine() != null
                    && response.getStatusLine().getStatusCode() == expectedStatusCode;

            if (success) {
                return bpmnModel;
            } else {
                exception = new FlowableServiceException(
                        "An error occurred while calling Flowable: " + response.getStatusLine());
            }
        } catch (Exception e) {
            log.warn("Error consuming response from uri {}", request.getURI(), e);
            exception = clientUtil.wrapException(e, request);
        } finally {
            response.close();
        }

    } catch (Exception e) {
        log.error("Error executing request to uri {}", request.getURI(), e);
        exception = clientUtil.wrapException(e, request);

    } finally {
        try {
            client.close();
        } catch (Exception e) {
            log.warn("Error closing http client instance", e);
        }
    }

    if (exception != null) {
        throw exception;
    }

    return null;
}

From source file:net.sf.jabref.importer.fileformat.FreeCiteImporter.java

public ParserResult importEntries(String text) {
    // URLencode the string for transmission
    String urlencodedCitation = null;
    try {//from ww  w .ja  v a 2 s  . c o  m
        urlencodedCitation = URLEncoder.encode(text, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Unsupported encoding", e);
    }

    // Send the request
    URL url;
    URLConnection conn;
    try {
        url = new URL("http://freecite.library.brown.edu/citations/create");
        conn = url.openConnection();
    } catch (MalformedURLException e) {
        LOGGER.warn("Bad URL", e);
        return new ParserResult();
    } catch (IOException e) {
        LOGGER.warn("Could not download", e);
        return new ParserResult();
    }
    try {
        conn.setRequestProperty("accept", "text/xml");
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        String data = "citation=" + urlencodedCitation;
        // write parameters
        writer.write(data);
        writer.flush();
    } catch (IllegalStateException e) {
        LOGGER.warn("Already connected.", e);
    } catch (IOException e) {
        LOGGER.warn("Unable to connect to FreeCite online service.", e);
        return ParserResult
                .fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service."));
    }
    // output is in conn.getInputStream();
    // new InputStreamReader(conn.getInputStream())
    List<BibEntry> res = new ArrayList<>();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        XMLStreamReader parser = factory.createXMLStreamReader(conn.getInputStream());
        while (parser.hasNext()) {
            if ((parser.getEventType() == XMLStreamConstants.START_ELEMENT)
                    && "citation".equals(parser.getLocalName())) {
                parser.nextTag();

                StringBuilder noteSB = new StringBuilder();

                BibEntry e = new BibEntry();
                // fallback type
                EntryType type = BibtexEntryTypes.INPROCEEDINGS;

                while (!((parser.getEventType() == XMLStreamConstants.END_ELEMENT)
                        && "citation".equals(parser.getLocalName()))) {
                    if (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                        String ln = parser.getLocalName();
                        if ("authors".equals(ln)) {
                            StringBuilder sb = new StringBuilder();
                            parser.nextTag();

                            while (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                                // author is directly nested below authors
                                assert "author".equals(parser.getLocalName());

                                String author = parser.getElementText();
                                if (sb.length() == 0) {
                                    // first author
                                    sb.append(author);
                                } else {
                                    sb.append(" and ");
                                    sb.append(author);
                                }
                                assert parser.getEventType() == XMLStreamConstants.END_ELEMENT;
                                assert "author".equals(parser.getLocalName());
                                parser.nextTag();
                                // current tag is either begin:author or
                                // end:authors
                            }
                            e.setField(FieldName.AUTHOR, sb.toString());
                        } else if (FieldName.JOURNAL.equals(ln)) {
                            // we guess that the entry is a journal
                            // the alternative way is to parse
                            // ctx:context-objects / ctx:context-object / ctx:referent / ctx:metadata-by-val / ctx:metadata / journal / rft:genre
                            // the drawback is that ctx:context-objects is NOT nested in citation, but a separate element
                            // we would have to change the whole parser to parse that format.
                            type = BibtexEntryTypes.ARTICLE;
                            e.setField(ln, parser.getElementText());
                        } else if ("tech".equals(ln)) {
                            type = BibtexEntryTypes.TECHREPORT;
                            // the content of the "tech" field seems to contain the number of the technical report
                            e.setField(FieldName.NUMBER, parser.getElementText());
                        } else if (FieldName.DOI.equals(ln) || "institution".equals(ln) || "location".equals(ln)
                                || FieldName.NUMBER.equals(ln) || "note".equals(ln)
                                || FieldName.TITLE.equals(ln) || FieldName.PAGES.equals(ln)
                                || FieldName.PUBLISHER.equals(ln) || FieldName.VOLUME.equals(ln)
                                || FieldName.YEAR.equals(ln)) {
                            e.setField(ln, parser.getElementText());
                        } else if ("booktitle".equals(ln)) {
                            String booktitle = parser.getElementText();
                            if (booktitle.startsWith("In ")) {
                                // special treatment for parsing of
                                // "In proceedings of..." references
                                booktitle = booktitle.substring(3);
                            }
                            e.setField("booktitle", booktitle);
                        } else if ("raw_string".equals(ln)) {
                            // raw input string is ignored
                        } else {
                            // all other tags are stored as note
                            noteSB.append(ln);
                            noteSB.append(':');
                            noteSB.append(parser.getElementText());
                            noteSB.append(Globals.NEWLINE);
                        }
                    }
                    parser.next();
                }

                if (noteSB.length() > 0) {
                    String note;
                    if (e.hasField("note")) {
                        // "note" could have been set during the parsing as FreeCite also returns "note"
                        note = e.getFieldOptional("note").get().concat(Globals.NEWLINE)
                                .concat(noteSB.toString());
                    } else {
                        note = noteSB.toString();
                    }
                    e.setField("note", note);
                }

                // type has been derived from "genre"
                // has to be done before label generation as label generation is dependent on entry type
                e.setType(type);

                // autogenerate label (BibTeX key)
                LabelPatternUtil.makeLabel(
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getMetaData(),
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getDatabase(), e, Globals.prefs);

                res.add(e);
            }
            parser.next();
        }
        parser.close();
    } catch (IOException | XMLStreamException ex) {
        LOGGER.warn("Could not parse", ex);
        return new ParserResult();
    }

    return new ParserResult(res);
}

From source file:com.predic8.membrane.core.interceptor.schemavalidation.SchematronValidator.java

public SchematronValidator(ResolverMap resourceResolver, String schematron,
        ValidatorInterceptor.FailureHandler failureHandler, Router router, BeanFactory beanFactory)
        throws Exception {
    this.failureHandler = failureHandler;

    //works as standalone "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"
    TransformerFactory fac;//from w w w .ja  v a 2 s .  c  om
    try {
        fac = beanFactory.getBean("transformerFactory", TransformerFactory.class);
    } catch (NoSuchBeanDefinitionException e) {
        throw new RuntimeException(
                "Please define a bean called 'transformerFactory' in monitor-beans.xml, e.g. with "
                        + "<spring:bean id=\"transformerFactory\" class=\"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl\" />",
                e);
    }
    fac.setURIResolver(new URIResolver() {
        @Override
        public Source resolve(String href, String base) throws TransformerException {
            return new StreamSource(SchematronValidator.class.getResourceAsStream(href));
        }
    });
    Transformer t = fac.newTransformer(
            new StreamSource(SchematronValidator.class.getResourceAsStream("conformance1-5.xsl")));

    // transform schematron-XML into XSLT
    DOMResult r = new DOMResult();
    t.transform(new StreamSource(router.getResolverMap().resolve(schematron)), r);

    // build XSLT transformers
    fac.setURIResolver(null);
    int concurrency = Runtime.getRuntime().availableProcessors() * 2;
    transformers = new ArrayBlockingQueue<Transformer>(concurrency);
    for (int i = 0; i < concurrency; i++) {
        Transformer transformer = fac.newTransformer(new DOMSource(r.getNode()));
        transformer.setErrorListener(new NullErrorListener()); // silence console logging
        transformers.put(transformer);
    }

    xmlInputFactory = XMLInputFactory.newInstance();
    xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
}