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.apache.synapse.registry.url.SimpleURLRegistry.java

public OMNode lookup(String key) {

    if (log.isDebugEnabled()) {
        log.debug("==> Repository fetch of resource with key : " + key);

    }/*from  ww  w.  j a  v  a2 s .c om*/
    URL url = SynapseConfigUtils.getURLFromPath(root + key,
            properties.get(SynapseConstants.SYNAPSE_HOME) != null
                    ? properties.get(SynapseConstants.SYNAPSE_HOME).toString()
                    : "");
    if (url == null) {
        return null;
    }

    BufferedInputStream inputStream;
    try {
        URLConnection connection = SynapseConfigUtils.getURLConnection(url);
        if (connection == null) {
            if (log.isDebugEnabled()) {
                log.debug("Cannot create a URLConnection for given URL : " + url);
            }
            return null;
        }
        connection.connect();
        inputStream = new BufferedInputStream(connection.getInputStream());
    } catch (IOException e) {
        return null;
    }

    OMNode result = null;

    if (inputStream != null) {

        try {

            XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
            StAXOMBuilder builder = new StAXOMBuilder(parser);
            result = builder.getDocumentElement();

        } catch (OMException ignored) {

            if (log.isDebugEnabled()) {
                log.debug("The resource at the provided URL isn't " + "well-formed XML,So,takes it as a text");
            }

            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("Error in closing the input stream. ", e);
            }
            result = SynapseConfigUtils.readNonXML(url);

        } catch (XMLStreamException ignored) {

            if (log.isDebugEnabled()) {
                log.debug("The resource at the provided URL isn't " + "well-formed XML,So,takes it as a text");
            }

            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("Error in closing the input stream. ", e);
            }
            result = SynapseConfigUtils.readNonXML(url);

        } finally {
            try {
                if (result != null && result.getParent() != null) {
                    //TODO Replace following code with the correct code when synapse is moving to AXIOM 1.2.9
                    result.detach();
                    OMDocument omDocument = omFactory.createOMDocument();
                    omDocument.addChild(result);
                }
                inputStream.close();
            } catch (IOException e) {
                log.error("Error in closing the input stream.", e);
            }

        }

    }
    return result;
}

From source file:org.apache.syncope.core.workflow.activiti.ActivitiImportUtils.java

public static void fromJSON(final ProcessEngine engine, final ProcessDefinition procDef, final Model model) {
    InputStream bpmnStream = null;
    InputStreamReader isr = null;
    XMLStreamReader xtr = null;// w ww. j  av  a  2  s  .  c  o  m
    try {
        bpmnStream = engine.getRepositoryService().getResourceAsStream(procDef.getDeploymentId(),
                procDef.getResourceName());
        isr = new InputStreamReader(bpmnStream);
        xtr = XMLInputFactory.newInstance().createXMLStreamReader(isr);
        BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);

        fromJSON(engine, new BpmnJsonConverter().convertToJson(bpmnModel).toString().getBytes(), procDef,
                model);
    } catch (Exception e) {
        throw new WorkflowException("While updating process " + ActivitiUserWorkflowAdapter.WF_PROCESS_RESOURCE,
                e);
    } finally {
        if (xtr != null) {
            try {
                xtr.close();
            } catch (XMLStreamException e) {
                // ignore
            }
        }
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(bpmnStream);
    }
}

From source file:org.apache.syncope.core.workflow.user.activiti.ActivitiImportUtils.java

public void fromJSON(final ProcessDefinition procDef, final Model model) {
    InputStream bpmnStream = null;
    InputStreamReader isr = null;
    XMLStreamReader xtr = null;//from w w  w.java  2s.  co m
    try {
        bpmnStream = repositoryService.getResourceAsStream(procDef.getDeploymentId(),
                procDef.getResourceName());
        isr = new InputStreamReader(bpmnStream);
        xtr = XMLInputFactory.newInstance().createXMLStreamReader(isr);
        BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);

        fromJSON(new BpmnJsonConverter().convertToJson(bpmnModel).toString().getBytes(), procDef, model);
    } catch (Exception e) {
        throw new WorkflowException("While updating process " + ActivitiUserWorkflowAdapter.WF_PROCESS_RESOURCE,
                e);
    } finally {
        if (xtr != null) {
            try {
                xtr.close();
            } catch (XMLStreamException e) {
                // ignore
            }
        }
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(bpmnStream);
    }
}

From source file:org.apache.sysml.runtime.controlprogram.parfor.opt.PerfTestTool.java

private static void readProfile(String fname) throws XMLStreamException, IOException {
    //init profile map
    _profile = new HashMap<Integer, HashMap<Integer, CostFunction>>();

    //read existing profile
    FileInputStream fis = new FileInputStream(fname);

    try {//from w w w .  j  a  v a  2  s  .c  o  m
        //xml parsing
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader xsr = xif.createXMLStreamReader(fis);

        int e = xsr.nextTag(); // profile start

        while (true) //read all instructions
        {
            e = xsr.nextTag(); // instruction start
            if (e == XMLStreamConstants.END_ELEMENT)
                break; //reached profile end tag

            //parse instruction
            int ID = Integer.parseInt(xsr.getAttributeValue(null, XML_ID));
            //String name = xsr.getAttributeValue(null, XML_NAME).trim().replaceAll(" ", Lops.OPERAND_DELIMITOR);
            HashMap<Integer, CostFunction> tmp = new HashMap<Integer, CostFunction>();
            _profile.put(ID, tmp);

            while (true) {
                e = xsr.nextTag(); // cost function start
                if (e == XMLStreamConstants.END_ELEMENT)
                    break; //reached instruction end tag

                //parse cost function
                TestMeasure m = TestMeasure.valueOf(xsr.getAttributeValue(null, XML_MEASURE));
                TestVariable lv = TestVariable.valueOf(xsr.getAttributeValue(null, XML_VARIABLE));
                InternalTestVariable[] pv = parseTestVariables(
                        xsr.getAttributeValue(null, XML_INTERNAL_VARIABLES));
                DataFormat df = DataFormat.valueOf(xsr.getAttributeValue(null, XML_DATAFORMAT));
                int tDefID = getTestDefID(m, lv, df, pv);

                xsr.next(); //read characters
                double[] params = parseParams(xsr.getText());
                boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1;
                CostFunction cf = new CostFunction(params, multidim);
                tmp.put(tDefID, cf);

                xsr.nextTag(); // cost function end
                //System.out.println("added cost function");
            }
        }
        xsr.close();
    } finally {
        IOUtilFunctions.closeSilently(fis);
    }

    //mark profile as successfully read
    _flagReadData = true;
}

From source file:org.apache.tajo.catalog.store.XMLCatalogSchemaManager.java

protected void loadFromXmlFiles() throws IOException, XMLStreamException, URISyntaxException {
    XMLInputFactory xmlIf = XMLInputFactory.newInstance();
    final List<StoreObject> storeObjects = new ArrayList<>();

    xmlIf.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);

    for (String resname : listResources()) {
        URL filePath = ClassLoader.getSystemResource(resname);

        if (filePath == null) {
            throw new FileNotFoundException(resname);
        }/* w w w.j a v a  2 s  .  c o m*/

        loadFromXmlFile(xmlIf, filePath, storeObjects);
    }

    mergeXmlSchemas(storeObjects);
}

From source file:org.apache.tuscany.sca.binding.ws.axis2.provider.Axis2ReferenceBindingProvider.java

protected org.apache.axis2.addressing.EndpointReference getEPR(WebServiceBinding wsBinding) {
    if (wsBinding.getEndPointReference() == null) {
        return null;
    }//from   w  w  w.j  a v  a2 s.  c  o m
    try {

        DOMSource domSource = new DOMSource(wsBinding.getEndPointReference());
        XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(domSource);
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        OMElement omElement = builder.getDocumentElement();
        org.apache.axis2.addressing.EndpointReference epr = EndpointReferenceHelper.fromOM(omElement);
        return epr;

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } catch (FactoryConfigurationError e) {
        throw new RuntimeException(e);
    }
}

From source file:org.auraframework.impl.root.parser.handler.IncludeDefRefHandlerTest.java

private XMLStreamReader getReader(Source<?> source) throws XMLStreamException {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
    XMLStreamReader xmlReader = xmlInputFactory.createXMLStreamReader(source.getSystemId(),
            source.getHashingReader());/*from w  w w  . j  av a 2 s  . c  o  m*/
    xmlReader.next();
    return xmlReader;
}

From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java

public void readMessage(InMessage message, MessageContext context) throws XFireFault {
    if (this.requestInfo == null) {
        throw new XFireFault("Unable to read message: no request info was found!", XFireFault.RECEIVER);
    }//w  w  w  .  ja  v a2s . c om

    Object bean;
    try {
        Unmarshaller unmarshaller = this.jaxbContext.createUnmarshaller();
        XMLStreamReader streamReader = message.getXMLStreamReader();
        if (this.requestInfo.isSchemaValidate()) {
            try {
                TransformerFactory xformFactory = TransformerFactory.newInstance();
                DOMResult domResult = new DOMResult();
                xformFactory.newTransformer().transform(new StAXSource(streamReader, true), domResult);
                unmarshaller.getSchema().newValidator().validate(new DOMSource(domResult.getNode()));
                streamReader = XMLInputFactory.newInstance()
                        .createXMLStreamReader(new DOMSource(domResult.getNode()));
            } catch (Exception e) {
                throw new XFireRuntimeException("Unable to validate the request against the schema.");
            }
        }
        unmarshaller.setEventHandler(getValidationEventHandler());
        unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshaller(context));
        bean = unmarshaller.unmarshal(streamReader, this.requestInfo.getBeanClass()).getValue();
    } catch (JAXBException e) {
        throw new XFireRuntimeException("Unable to unmarshal type.", e);
    }

    List<Object> parameters = new ArrayList<Object>();
    if (this.requestInfo.isBare()) {
        //bare method, doesn't need to be unwrapped.
        parameters.add(bean);
    } else {
        for (PropertyDescriptor descriptor : this.requestInfo.getPropertyOrder()) {
            try {
                parameters.add(descriptor.getReadMethod().invoke(bean));
            } catch (IllegalAccessException e) {
                throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                        + this.requestInfo.getBeanClass().getName() + ".", e, XFireFault.RECEIVER);
            } catch (InvocationTargetException e) {
                throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                        + this.requestInfo.getBeanClass().getName() + ".", e, XFireFault.RECEIVER);
            }
        }
    }

    message.setBody(parameters);
}

From source file:org.codice.ddf.parser.xml.XmlParser.java

@Override
public <T> T unmarshal(ParserConfigurator configurator, Class<? extends T> cls, final InputStream stream)
        throws ParserException {
    return unmarshal(configurator, unmarshaller -> {
        try {//from  w  w  w . java  2  s .  co  m
            XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(stream);

            @SuppressWarnings("unchecked")
            T unmarshal = (T) unmarshaller.unmarshal(xmlStreamReader);
            return unmarshal;
        } catch (XMLStreamException | JAXBException e) {
            throw new RuntimeException("Error unmarshalling", e);
        }
    });
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.transformer.GmdTransformer.java

public GmdTransformer() {
    QNameMap qmap = new QNameMap();
    qmap.setDefaultNamespace(GmdMetacardType.GMD_NAMESPACE);
    qmap.setDefaultPrefix("");
    StaxDriver staxDriver = new StaxDriver(qmap);

    xstream = new XStream(staxDriver);
    xstream.setClassLoader(this.getClass().getClassLoader());
    XstreamPathConverter converter = new XstreamPathConverter();
    xstream.registerConverter(converter);
    xstream.alias("MD_Metadata", XstreamPathValueTracker.class);
    argumentHolder = xstream.newDataHolder();
    argumentHolder.put(XstreamPathConverter.PATH_KEY, buildPaths());
    xmlFactory = XMLInputFactory.newInstance();
}