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:org.flowable.cmmn.converter.CmmnXmlConverter.java

public CmmnModel convertToCmmnModel(InputStreamProvider inputStreamProvider, boolean validateSchema,
        boolean enableSafeBpmnXml, String encoding) {
    XMLInputFactory xif = XMLInputFactory.newInstance();

    if (xif.isPropertySupported(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)) {
        xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    }//  w  ww .j  a  v a 2 s . com
    if (xif.isPropertySupported(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) {
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    }
    if (xif.isPropertySupported(XMLInputFactory.SUPPORT_DTD)) {
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    }

    if (encoding == null) {
        encoding = DEFAULT_ENCODING;
    }

    if (validateSchema) {
        try (InputStreamReader in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding)) {
            if (!enableSafeBpmnXml) {
                validateModel(inputStreamProvider);
            } else {
                validateModel(xif.createXMLStreamReader(in));
            }
        } catch (UnsupportedEncodingException e) {
            throw new CmmnXMLException("The CMMN 1.1 xml is not properly encoded", e);
        } catch (XMLStreamException e) {
            throw new CmmnXMLException("Error while reading the CMMN 1.1 XML", e);
        } catch (Exception e) {
            throw new CmmnXMLException(e.getMessage(), e);
        }
    }
    // The input stream is closed after schema validation
    try (InputStreamReader in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding)) {
        // XML conversion
        return convertToCmmnModel(xif.createXMLStreamReader(in));
    } catch (UnsupportedEncodingException e) {
        throw new CmmnXMLException("The CMMN 1.1 xml is not properly encoded", e);
    } catch (XMLStreamException e) {
        throw new CmmnXMLException("Error while reading the CMMN 1.1 XML", e);
    } catch (IOException e) {
        throw new CmmnXMLException(e.getMessage(), e);
    }
}

From source file:org.geoserver.backuprestore.reader.CatalogFileReader.java

@Override
protected void doOpen() throws Exception {
    Assert.notNull(resource, "The Resource must not be null.");

    try {/*from   ww  w.  j  ava 2 s. com*/
        noInput = true;
        if (!resource.exists()) {
            if (strict) {
                throw new IllegalStateException("Input resource must exist (reader is in 'strict' mode)");
            }
            logger.warn("Input resource does not exist " + resource.getDescription());
            return;
        }
        if (!resource.isReadable()) {
            if (strict) {
                throw new IllegalStateException("Input resource must be readable (reader is in 'strict' mode)");
            }
            logger.warn("Input resource is not readable " + resource.getDescription());
            return;
        }

        inputStream = resource.getInputStream();
        eventReader = XMLInputFactory.newInstance().createXMLEventReader(inputStream);
        fragmentReader = new DefaultFragmentEventReader(eventReader);
        noInput = false;
    } catch (Exception e) {
        logValidationExceptions((T) null, e);
    }
}

From source file:org.geowebcache.georss.StaxGeoRSSReader.java

public StaxGeoRSSReader(final Reader feed) throws XMLStreamException, FactoryConfigurationError {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    reader = factory.createXMLStreamReader(feed);

    reader.nextTag();/*from ww  w . ja  v  a2s  .co m*/
    reader.require(START_ELEMENT, null, null);
    QName name = reader.getName();

    if (!(ATOM.NSURI.equals(name.getNamespaceURI()) || "feed".equals(name.getLocalPart()))) {
        throw new IllegalArgumentException("Document is not a GeoRSS feed. Root element: " + name);
    }
    findFirstEntry();
    gmlParser = new GML31ParsingUtils();
}

From source file:org.gephi.io.importer.api.ImportUtils.java

public static XMLStreamReader getXMLReader(Reader reader) {
    try {/* w ww  .j av a 2s .  c  om*/
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        if (inputFactory.isPropertySupported("javax.xml.stream.isValidating")) {
            inputFactory.setProperty("javax.xml.stream.isValidating", Boolean.FALSE);
        }
        inputFactory.setXMLReporter(new XMLReporter() {

            @Override
            public void report(String message, String errorType, Object relatedInformation, Location location)
                    throws XMLStreamException {
                throw new RuntimeException("Error:" + errorType + ", message : " + message);
                //System.out.println("Error:" + errorType + ", message : " + message);
            }
        });
        return inputFactory.createXMLStreamReader(reader);
    } catch (XMLStreamException ex) {
        throw new RuntimeException(NbBundle.getMessage(ImportUtils.class, "ImportUtils.error_io"));
    }
}

From source file:org.gtdfree.model.GTDDataXMLTools.java

static public DataHeader load(GTDModel model, InputStream in) throws XMLStreamException, IOException {

    model.setSuspendedForMultipleChanges(true);
    model.getDataRepository().suspend(true);

    XMLStreamReader r;/*from w w w. j a va 2 s .c  om*/
    try {

        // buffer size is same as default in 1.6, we explicitly request it so, not to brake if defaut changes.
        BufferedInputStream bin = new BufferedInputStream(in, 8192);
        bin.mark(8191);

        Reader rr = new InputStreamReader(bin);
        CharBuffer b = CharBuffer.allocate(96);
        rr.read(b);
        b.position(0);
        //System.out.println(b);
        Pattern pattern = Pattern.compile("<\\?.*?encoding\\s*?=.*?\\?>", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
        Matcher matcher = pattern.matcher(b);

        // reset back to start of file
        bin.reset();

        // we check if encoding is defined in xml, by the book encoding on r should be null if not defined in xml,
        // but in reality it can be arbitrary if not defined in xml. So we have to check ourselves.
        if (matcher.find()) {
            //System.out.println(matcher);
            // if defined, then XML parser will pick it up and use it
            r = XMLInputFactory.newInstance().createXMLStreamReader(bin);
            Logger.getLogger(GTDDataXMLTools.class).info("XML declared encoding: " + r.getEncoding() //$NON-NLS-1$
                    + ", system default encoding: " + Charset.defaultCharset()); //$NON-NLS-1$
        } else {
            //System.out.println(matcher);
            // if not defined, then we assume it is generated by gtd-free version 0.4 or some local editor,
            // so we assume system default encoding.
            r = XMLInputFactory.newInstance().createXMLStreamReader(new InputStreamReader(bin));
            Logger.getLogger(GTDDataXMLTools.class)
                    .info("XML assumed system default encoding: " + Charset.defaultCharset()); //$NON-NLS-1$
        }

        r.nextTag();
        if ("gtd-data".equals(r.getLocalName())) { //$NON-NLS-1$
            DataHeader dh = new DataHeader(null, r.getAttributeValue(null, "version"), //$NON-NLS-1$
                    r.getAttributeValue(null, "modified")); //$NON-NLS-1$
            if (dh.version != null) {
                if (dh.version.equals("2.0")) { //$NON-NLS-1$
                    r.nextTag();
                    _load_2_0(model, r);
                    return dh;
                }
            }
            String s = r.getAttributeValue(null, "lastActionID"); //$NON-NLS-1$
            if (s != null) {
                try {
                    model.setLastActionID(Integer.parseInt(s));
                } catch (Exception e) {
                    Logger.getLogger(GTDDataXMLTools.class).debug("Internal error.", e); //$NON-NLS-1$
                }
            }
            if (dh.version != null) {
                if (dh.version.equals("2.1")) { //$NON-NLS-1$
                    r.nextTag();
                    _load_2_1(model, r);
                    return dh;

                }
                if (dh.version.startsWith("2.2")) { //$NON-NLS-1$
                    r.nextTag();
                    _load_2_2(model, r);
                    return dh;
                }
            }
            throw new IOException("XML gtd-free data with version number " + dh.version //$NON-NLS-1$
                    + " can not be imported. Data version is newer then supported versions. Update your GTD-Free application to latest version."); //$NON-NLS-1$
        }

        _load_1_0(model, r);

        return null;

    } catch (XMLStreamException e) {
        if (e.getNestedException() != null) {
            Logger.getLogger(GTDDataXMLTools.class).debug("Parse error.", e.getNestedException()); //$NON-NLS-1$
        } else {
            Logger.getLogger(GTDDataXMLTools.class).debug("Parse error.", e); //$NON-NLS-1$
        }
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        model.setSuspendedForMultipleChanges(false);
        model.getDataRepository().suspend(false);
    }

}

From source file:org.intalio.tempo.workflow.tas.nuxeo.NuxeoStorageStrategy.java

private static OMElement buildOMElement(String xmlData) throws IOException {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlData.getBytes());
    XMLStreamReader parser;//from   w  w  w  .ja v a2  s. co  m
    try {
        parser = XMLInputFactory.newInstance().createXMLStreamReader(byteArrayInputStream);
    } catch (XMLStreamException e) {
        throw new IOException(e.getMessage());
    }
    StAXOMBuilder builder = new StAXOMBuilder(parser);
    return builder.getDocumentElement();
}

From source file:org.intermine.webservice.client.results.XMLTableResult.java

private void init() {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {//w w  w.  ja v  a  2  s  .  c o  m
        xmlReader = factory.createXMLStreamReader(getReader());
    } catch (XMLStreamException e) {
        throw new RuntimeException("Error parsing XML result response", e);
    }
}

From source file:org.jaggeryjs.hostobjects.ws.WSRequestHostObject.java

/**
 * <p/> This method invokes the Web service with the requested payload. </p>
 * <p/>//from  ww  w.ja va 2  s .c o m
 * <pre>
 *   void send ( [in Document payload | in XMLString payload | in XMLString payload ]);
 * </pre>
 * <p/>
 * See <a href="http://www.wso2.org/wiki/display/mashup/WSRequest+Host+Object">WSRequest host
 * object reference</a> & <a href="http://www.wso2.org/wiki/display/wsfajax/wsrequest_specification">WSRequest
 * specification</a> for more details.
 */
public static void jsFunction_send(Context cx, Scriptable thisObj, Object[] arguments, Function funObj)
        throws ScriptException, AxisFault {
    WSRequestHostObject wsRequest = (WSRequestHostObject) thisObj;
    Object payload;
    QName operationName = ServiceClient.ANON_OUT_IN_OP;
    if (wsRequest.wsdlMode && arguments.length != 2) {
        throw new ScriptException("When the openWSDL method of WSRequest is used the send "
                + "function should be called with 2 parameters. The operation to invoke and " + "the payload");
    }
    if (arguments.length == 1) {
        payload = arguments[0];
    } else if (arguments.length == 2) {
        if (arguments[0] instanceof QName) {
            QName qName = (QName) arguments[0];
            String uri = qName.getNamespaceURI();
            String localName = qName.getLocalPart();
            operationName = new QName(uri, localName);
        } else if (arguments[0] instanceof String) {
            if (wsRequest.targetNamespace == null) {
                throw new ScriptException("The targetNamespace of the service is null, please specify a "
                        + "QName for the operation name");
            }
            String localName = (String) arguments[0];
            operationName = new QName(wsRequest.targetNamespace, localName);
        } else {
            throw new ScriptException("Invalid parameter type for the WSRequest.send() method");
        }
        payload = arguments[1];
    } else {
        throw new ScriptException("Invalid no. of parameters for the WSRequest.send() method");
    }

    OMElement payloadElement = null;
    if (wsRequest.readyState != 1) {
        throw new ScriptException("Invalid readyState for the WSRequest Hostobject : " + wsRequest.readyState);
    }
    if (payload instanceof String) {
        try {
            XMLStreamReader parser = XMLInputFactory.newInstance()
                    .createXMLStreamReader(new StringReader((String) payload));
            StAXOMBuilder builder = new StAXOMBuilder(parser);
            payloadElement = builder.getDocumentElement();
        } catch (Exception e) {
            String message = "Invalid input for the payload in WSRequest Hostobject : " + payload;
            log.error(message, e);
            throw new ScriptException(message, e);
        }
    } else if (payload instanceof XMLObject) {
        try {
            OMNode node = AXIOMUtil.stringToOM(payload.toString());
            if (node instanceof OMElement) {
                payloadElement = (OMElement) node;
            } else {
                throw new ScriptException("Invalid input for the payload in WSRequest Hostobject : " + payload);
            }
        } catch (Exception e) {
            String message = "Invalid input for the payload in WSRequest Hostobject : " + payload;
            log.error(message, e);
            throw new ScriptException(message, e);
        }
    }
    // else if (typeof(payload) == "object") {
    // // set DOOMRequired to true
    // DocumentBuilderFactoryImpl.setDOOMRequired(true);
    // try {
    // payload = payload.getFirstChild();
    // } catch(Exception e) {
    // throw new Error("INVALID_INPUT_EXCEPTION");
    // }
    // }
    // else if (payload == undefined) {
    // payload = null;
    // }

    try {
        if (wsRequest.async) { // asynchronous call to send()
            AxisCallback callback = new WSRequestCallback(wsRequest);
            setRampartConfigs(wsRequest, operationName);
            if (wsRequest.wsdlMode) {
                //                    setSSLProperties(wsRequest);
                if (IN_ONLY.equalsIgnoreCase(wsRequest.mep)) {
                    wsRequest.sender.fireAndForget(operationName, payloadElement);
                    wsRequest.readyState = 4;
                } else {
                    wsRequest.sender.sendReceiveNonBlocking(operationName, payloadElement, callback);
                    wsRequest.readyState = 2;
                }
            } else {
                //                    setSSLProperties(wsRequest);
                if (IN_ONLY.equalsIgnoreCase(wsRequest.mep)) {
                    wsRequest.sender.fireAndForget(payloadElement);
                    wsRequest.readyState = 4;
                } else {
                    wsRequest.sender.sendReceiveNonBlocking(payloadElement, callback);
                    wsRequest.readyState = 2;
                }
            }
        } else { // synchronous call to send()
            wsRequest.readyState = 2;
            // TODO do we need to call onreadystatechange here too
            setRampartConfigs(wsRequest, operationName);
            if (wsRequest.wsdlMode) {
                //                    setSSLProperties(wsRequest);
                if (IN_ONLY.equalsIgnoreCase(wsRequest.mep)) {
                    wsRequest.sender.fireAndForget(operationName, payloadElement);
                } else {
                    wsRequest.updateResponse(wsRequest.sender.sendReceive(operationName, payloadElement));
                }
                wsRequest.readyState = 4;
            } else {
                //                    setSSLProperties(wsRequest);
                if (IN_ONLY.equalsIgnoreCase(wsRequest.mep)) {
                    wsRequest.sender.fireAndForget(payloadElement);
                } else {
                    wsRequest.updateResponse(wsRequest.sender.sendReceive(operationName, payloadElement));
                    wsRequest.transportHeaders = (CommonsTransportHeaders) wsRequest.sender
                            .getLastOperationContext().getMessageContext("In")
                            .getProperty(MessageContext.TRANSPORT_HEADERS);

                }

                wsRequest.readyState = 4;
            }
        }
        // Calling onreadystatechange function
        if (wsRequest.onReadyStateChangeFunction != null) {
            wsRequest.onReadyStateChangeFunction.call(cx, wsRequest, wsRequest, new Object[0]);
        }
    } catch (AxisFault e) {
        wsRequest.error = new WebServiceErrorHostObject();
        OMElement detail = e.getDetail();
        if (detail != null) {
            wsRequest.error.jsSet_detail(detail.toString());
        }
        QName faultCode = e.getFaultCode();
        if (faultCode != null) {
            wsRequest.error.jsSet_code(faultCode.toString());
        }
        wsRequest.error.jsSet_reason(e.getReason());
        String message = "Error occured while invoking the service";
        log.error(message, e);
        throw new ScriptException(message, e);
    } catch (Exception e) {
        wsRequest.error = new WebServiceErrorHostObject();
        wsRequest.error.jsSet_detail(e.getMessage());
        String message = "Error occured while invoking the service";
        log.error(message, e);
        throw new ScriptException(message, e);
    } finally {
        wsRequest.sender.cleanupTransport();
    }
}

From source file:org.jaggeryjs.modules.ws.WSRequestHostObject.java

/**
 * <p/> This method invokes the Web service with the requested payload. </p>
 * <p/>/*from   w ww  . j a  v a 2  s  .c  om*/
 * <pre>
 *   void send ( [in Document payload | in XMLString payload | in XMLString payload ]);
 * </pre>
 * <p/>
 * See <a href="http://www.wso2.org/wiki/display/mashup/WSRequest+Host+Object">WSRequest host
 * object reference</a> & <a href="http://www.wso2.org/wiki/display/wsfajax/wsrequest_specification">WSRequest
 * specification</a> for more details.
 */
public static void jsFunction_send(Context cx, Scriptable thisObj, Object[] arguments, Function funObj)
        throws ScriptException, AxisFault {
    WSRequestHostObject wsRequest = (WSRequestHostObject) thisObj;
    Object payload;
    QName operationName = ServiceClient.ANON_OUT_IN_OP;
    if (wsRequest.wsdlMode && arguments.length != 2) {
        throw new ScriptException("When the openWSDL method of WSRequest is used the send "
                + "function should be called with 2 parameters. The operation to invoke and " + "the payload");
    }
    if (arguments.length == 1) {
        payload = arguments[0];
    } else if (arguments.length == 2) {
        if (arguments[0] instanceof QName) {
            QName qName = (QName) arguments[0];
            String uri = qName.getNamespaceURI();
            String localName = qName.getLocalPart();
            operationName = new QName(uri, localName);
        } else if (arguments[0] instanceof String) {
            if (wsRequest.targetNamespace == null) {
                throw new ScriptException("The targetNamespace of the service is null, please specify a "
                        + "QName for the operation name");
            }
            String localName = (String) arguments[0];
            operationName = new QName(wsRequest.targetNamespace, localName);
        } else {
            throw new ScriptException("Invalid parameter type for the WSRequest.send() method");
        }
        payload = arguments[1];
    } else {
        throw new ScriptException("Invalid no. of parameters for the WSRequest.send() method");
    }

    OMElement payloadElement = null;
    if (wsRequest.readyState != 1) {
        throw new ScriptException("Invalid readyState for the WSRequest Hostobject : " + wsRequest.readyState);
    }
    if (payload instanceof String) {
        try {
            XMLStreamReader parser = XMLInputFactory.newInstance()
                    .createXMLStreamReader(new StringReader((String) payload));
            StAXOMBuilder builder = new StAXOMBuilder(parser);
            payloadElement = builder.getDocumentElement();
        } catch (Exception e) {
            String message = "Invalid input for the payload in WSRequest Hostobject : " + payload;
            log.error(message, e);
            throw new ScriptException(message, e);
        }
    } else if (payload instanceof XMLObject) {
        try {
            OMNode node = AXIOMUtil.stringToOM(payload.toString());
            if (node instanceof OMElement) {
                payloadElement = (OMElement) node;
            } else {
                throw new ScriptException("Invalid input for the payload in WSRequest Hostobject : " + payload);
            }
        } catch (Exception e) {
            String message = "Invalid input for the payload in WSRequest Hostobject : " + payload;
            log.error(message, e);
            throw new ScriptException(message, e);
        }
    }
    // else if (typeof(payload) == "object") {
    // // set DOOMRequired to true
    // DocumentBuilderFactoryImpl.setDOOMRequired(true);
    // try {
    // payload = payload.getFirstChild();
    // } catch(Exception e) {
    // throw new Error("INVALID_INPUT_EXCEPTION");
    // }
    // }
    // else if (payload == undefined) {
    // payload = null;
    // }

    try {
        if (wsRequest.async) { // asynchronous call to send()
            AxisCallback callback = new WSRequestCallback(wsRequest);
            setRampartConfigs(wsRequest, operationName);
            if (wsRequest.wsdlMode) {
                //                    setSSLProperties(wsRequest);
                if (IN_ONLY.equalsIgnoreCase(wsRequest.mep)) {
                    if (wsRequest.robust) {
                        wsRequest.sender.sendRobust(operationName, payloadElement);
                    } else {
                        wsRequest.sender.fireAndForget(operationName, payloadElement);
                    }
                    wsRequest.readyState = 4;
                } else {
                    wsRequest.sender.sendReceiveNonBlocking(operationName, payloadElement, callback);
                    wsRequest.readyState = 2;
                }
            } else {
                //                    setSSLProperties(wsRequest);
                if (IN_ONLY.equalsIgnoreCase(wsRequest.mep)) {
                    if (wsRequest.robust) {
                        wsRequest.sender.sendRobust(payloadElement);
                    } else {
                        wsRequest.sender.fireAndForget(payloadElement);
                    }
                    wsRequest.readyState = 4;
                } else {
                    wsRequest.sender.sendReceiveNonBlocking(payloadElement, callback);
                    wsRequest.readyState = 2;
                }
            }
        } else { // synchronous call to send()
            wsRequest.readyState = 2;
            // TODO do we need to call onreadystatechange here too
            setRampartConfigs(wsRequest, operationName);
            if (wsRequest.wsdlMode) {
                //                    setSSLProperties(wsRequest);
                if (IN_ONLY.equalsIgnoreCase(wsRequest.mep)) {
                    if (wsRequest.robust) {
                        wsRequest.sender.sendRobust(operationName, payloadElement);
                    } else {
                        wsRequest.sender.fireAndForget(operationName, payloadElement);
                    }
                } else {
                    wsRequest.updateResponse(wsRequest.sender.sendReceive(operationName, payloadElement));
                }
                wsRequest.readyState = 4;
            } else {
                //                    setSSLProperties(wsRequest);
                if (IN_ONLY.equalsIgnoreCase(wsRequest.mep)) {
                    if (wsRequest.robust) {
                        wsRequest.sender.sendRobust(payloadElement);
                    } else {
                        wsRequest.sender.fireAndForget(payloadElement);
                    }
                } else {
                    wsRequest.updateResponse(wsRequest.sender.sendReceive(operationName, payloadElement));
                    wsRequest.transportHeaders = (CommonsTransportHeaders) wsRequest.sender
                            .getLastOperationContext().getMessageContext("In")
                            .getProperty(MessageContext.TRANSPORT_HEADERS);

                }

                wsRequest.readyState = 4;
            }
        }
        // Calling onreadystatechange function
        if (wsRequest.onReadyStateChangeFunction != null) {
            wsRequest.onReadyStateChangeFunction.call(cx, wsRequest, wsRequest, new Object[0]);
        }
    } catch (AxisFault e) {
        wsRequest.error = new WebServiceErrorHostObject();
        OMElement detail = e.getDetail();
        if (detail != null) {
            wsRequest.error.jsSet_detail(detail.toString());
        }
        QName faultCode = e.getFaultCode();
        if (faultCode != null) {
            wsRequest.error.jsSet_code(faultCode.toString());
        }
        wsRequest.error.jsSet_reason(e.getReason());
        throw new ScriptException(e.getMessage(), e);
    } catch (Exception e) {
        wsRequest.error = new WebServiceErrorHostObject();
        wsRequest.error.jsSet_detail(e.getMessage());
        throw new ScriptException(e.getMessage(), e);
    } finally {
        wsRequest.sender.cleanupTransport();
    }
}

From source file:org.jahia.utils.migration.Migrators.java

private <T> T unmarshal(Class<T> docClass, InputStream inputStream) throws JAXBException, XMLStreamException {
    JAXBContext jc = JAXBContext.newInstance(docClass);
    Unmarshaller u = jc.createUnmarshaller();

    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(inputStream);

    T doc = (T) u.unmarshal(xmlStreamReader);
    return doc;/*  www .ja  va2 s. c  o  m*/
}