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.padaf.xmpbox.parser.XMPDocumentBuilder.java

/**
 * Parsing method. Return a XMPMetadata object with all elements read
 * //  w  ww  .j  a v a  2s . c om
 * @param xmp
 *            serialized XMP
 * @return Metadata with all information read
 * @throws XmpParsingException
 *             When element expected not found
 * @throws XmpSchemaException
 *             When instancing schema object failed or in PDF/A Extension
 *             case, if its namespace miss
 * @throws XmpUnknownValueTypeException
 *             When ValueType found not correspond to basic type and not has
 *             been declared in current schema
 * @throws XmpExpectedRdfAboutAttribute
 *             When rdf:Description not contains rdf:about attribute
 * @throws XmpXpacketEndException
 *             When xpacket end Processing Instruction is missing or is
 *             incorrect
 * @throws BadFieldValueException
 *             When treat a Schema associed to a schema Description in PDF/A
 *             Extension schema
 */

public XMPMetadata parse(byte[] xmp)
        throws XmpParsingException, XmpSchemaException, XmpUnknownValueTypeException,
        XmpExpectedRdfAboutAttribute, XmpXpacketEndException, BadFieldValueException {

    if (!(this instanceof XMPDocumentPreprocessor)) {
        for (XMPDocumentPreprocessor processor : preprocessors) {
            NSMapping additionalNSMapping = processor.process(xmp);
            this.nsMap.importNSMapping(additionalNSMapping);
        }
    }

    ByteArrayInputStream is = new ByteArrayInputStream(xmp);
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        reader.set(factory.createXMLStreamReader(is));

        // expect xpacket processing instruction
        expectNext(XMLStreamReader.PROCESSING_INSTRUCTION,
                "Did not find initial xpacket processing instruction");
        XMPMetadata metadata = parseInitialXpacket(reader.get().getPIData());

        // expect x:xmpmeta
        expectNextTag(XMLStreamReader.START_ELEMENT, "Did not find initial x:xmpmeta");
        expectName("adobe:ns:meta/", "xmpmeta");

        // expect rdf:RDF
        expectNextTag(XMLStreamReader.START_ELEMENT, "Did not find initial rdf:RDF");
        expectName("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF");

        nsMap.resetComplexBasicTypesDeclarationInEntireXMPLevel();
        // add all namespaces which could declare nsURI of a basicValueType
        // all others declarations are ignored
        int nsCount = reader.get().getNamespaceCount();
        for (int i = 0; i < nsCount; i++) {
            if (nsMap.isComplexBasicTypes(reader.get().getNamespaceURI(i))) {
                nsMap.setComplexBasicTypesDeclarationForLevelXMP(reader.get().getNamespaceURI(i),
                        reader.get().getNamespacePrefix(i));
            }
        }

        // now work on each rdf:Description
        int type = reader.get().nextTag();
        while (type == XMLStreamReader.START_ELEMENT) {
            parseDescription(metadata);
            type = reader.get().nextTag();
        }

        // all description are finished
        // expect end of rdf:RDF
        expectType(XMLStreamReader.END_ELEMENT, "Expected end of descriptions");
        expectName("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF");

        // expect ending xmpmeta
        expectNextTag(XMLStreamReader.END_ELEMENT, "Did not find initial x:xmpmeta");
        expectName("adobe:ns:meta/", "xmpmeta");

        // expect final processing instruction
        expectNext(XMLStreamReader.PROCESSING_INSTRUCTION, "Did not find final xpacket processing instruction");
        // treats xpacket end
        if (!reader.get().getPITarget().equals("xpacket")) {
            throw new XmpXpacketEndException("Excepted PI xpacket");
        }
        String xpackData = reader.get().getPIData();
        // end attribute must be present and placed in first
        // xmp spec says Other unrecognized attributes can follow, but
        // should be ignored
        if (xpackData.startsWith("end=")) {
            // check value (5 for end='X')
            if (xpackData.charAt(5) != 'r' && xpackData.charAt(5) != 'w') {
                throw new XmpXpacketEndException("Excepted xpacket 'end' attribute with value 'r' or 'w' ");
            }
        } else {
            // should find end='r/w'
            throw new XmpXpacketEndException(
                    "Excepted xpacket 'end' attribute (must be present and placed in first)");
        }

        metadata.setEndXPacket(xpackData);
        // return constructed object
        return metadata;
    } catch (XMLStreamException e) {
        throw new XmpParsingException("An error has occured when processing the underlying XMP source", e);
    } finally {
        reader.remove();
        IOUtils.closeQuietly(is);
    }
}

From source file:org.apache.pluto.driver.services.container.PortletWindowThread.java

@Override
public void run() {
    super.run();//from ww w .j av  a 2 s . c  o  m
    while (events.size() > 0) {
        HttpServletRequest req = new PortalServletRequest(eventProvider.getRequest(), this.portletWindow);
        HttpServletResponse res = eventProvider.getResponse();
        try {
            //            synchronized (this) {
            Event event = events.remove(0);
            Object value = event.getValue();

            XMLStreamReader xml = null;
            try {
                if (value instanceof String) {
                    String in = (String) value;
                    xml = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(in));
                }
            } catch (XMLStreamException e1) {
                throw new IllegalStateException(e1);
            } catch (FactoryConfigurationError e1) {
                throw new IllegalStateException(e1);
            }

            if (xml != null) {
                //XMLStreamReader xml = (XMLStreamReader) event.getValue();

                //provider.getEventDefinition(event.getQName());
                try {
                    // now test if object is jaxb
                    EventDefinition eventDefinitionDD = getEventDefintion(event.getQName());

                    ClassLoader loader = portletContextService.getClassLoader(
                            portletWindow.getPortletEntity().getPortletDefinition().getApplication().getName());
                    Class<? extends Serializable> clazz = loader.loadClass(eventDefinitionDD.getValueType())
                            .asSubclass(Serializable.class);

                    JAXBContext jc = JAXBContext.newInstance(clazz);
                    Unmarshaller unmarshaller = jc.createUnmarshaller();

                    //                       unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());

                    JAXBElement result = unmarshaller.unmarshal(xml, clazz);

                    event = new EventImpl(event.getQName(), (Serializable) result.getValue());
                } catch (JAXBException e) {
                    throw new IllegalStateException(e);
                } catch (ClassCastException e) {
                    throw new IllegalStateException(e);
                } catch (ClassNotFoundException e) {
                    throw new IllegalStateException(e);
                } catch (PortletContainerException e) {
                    throw new IllegalStateException(e);
                }
            }
            eventContainer.fireEvent(req, res, portletWindow, event);
            //            }
        } catch (PortletException e) {
            LOG.warn(e);
        } catch (IOException e) {
            LOG.warn(e);
        } catch (PortletContainerException e) {
            LOG.warn(e);
        }
    }
}

From source file:org.apache.rahas.Token.java

private OMElement convertStringToOMElement(String stringElement) throws IOException {

    if (null == stringElement || stringElement.trim().equals("")) {
        return null;
    }/*from  w  w  w  .  j  a v  a  2 s . c  o  m*/

    try {
        Reader in = new StringReader(stringElement);
        XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(in);
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        OMElement documentElement = builder.getDocumentElement();

        XMLStreamReader llomReader = documentElement.getXMLStreamReader();
        OMFactory doomFactory = DOOMAbstractFactory.getOMFactory();
        StAXOMBuilder doomBuilder = new StAXOMBuilder(doomFactory, llomReader);
        return doomBuilder.getDocumentElement();

    } catch (XMLStreamException e) {
        log.error("Cannot convert de-serialized string to OMElement. Could not create XML stream.", e);
        // IOException only has a constructor supporting exception chaining starting with Java 1.6
        IOException ex = new IOException(
                "Cannot convert de-serialized string to OMElement. Could not create XML stream.");
        ex.initCause(e);
        throw ex;
    }
}

From source file:org.apache.rampart.util.Axis2Util.java

/**
 * Builds a SOAPEnvelope from DOM Document.
 * @param doc - The dom document that contains a SOAP message
 * @param useDoom//  w  w w  .  ja  va  2 s.  c o m
 * @return
 * @throws WSSecurityException
 */
public static SOAPEnvelope getSOAPEnvelopeFromDOMDocument(Document doc, boolean useDoom)
        throws WSSecurityException {

    if (useDoom) {
        try {
            //Get processed headers
            SOAPEnvelope env = (SOAPEnvelope) doc.getDocumentElement();
            ArrayList processedHeaderQNames = new ArrayList();
            SOAPHeader soapHeader = env.getHeader();

            if (soapHeader != null) {
                Iterator headerBlocs = soapHeader.getChildElements();
                while (headerBlocs.hasNext()) {

                    OMElement element = (OMElement) headerBlocs.next();
                    SOAPHeaderBlock header = null;

                    if (element instanceof SOAPHeaderBlock) {
                        header = (SOAPHeaderBlock) element;

                        // If a header block is not an instance of SOAPHeaderBlock, it means that
                        // it is a header we have added in rampart eg. EncryptedHeader and should
                        // be converted to SOAPHeaderBlock for processing
                    } else {
                        header = soapHeader.addHeaderBlock(element.getLocalName(), element.getNamespace());
                        Iterator attrIter = element.getAllAttributes();
                        while (attrIter.hasNext()) {
                            OMAttribute attr = (OMAttribute) attrIter.next();
                            header.addAttribute(attr.getLocalName(), attr.getAttributeValue(),
                                    attr.getNamespace());
                        }
                        Iterator nsIter = element.getAllDeclaredNamespaces();
                        while (nsIter.hasNext()) {
                            OMNamespace ns = (OMNamespace) nsIter.next();
                            header.declareNamespace(ns);
                        }
                        // retrieve all child nodes (including any text nodes)
                        // and re-attach to header block
                        Iterator children = element.getChildren();
                        while (children.hasNext()) {
                            OMNode child = (OMNode) children.next();
                            child.detach();
                            header.addChild(child);
                        }

                        element.detach();

                        soapHeader.build();

                        header.setProcessed();

                    }

                    if (header.isProcessed()) {
                        processedHeaderQNames.add(element.getQName());
                    }
                }

            }
            XMLStreamReader reader = ((OMElement) doc.getDocumentElement()).getXMLStreamReader();
            StAXSOAPModelBuilder stAXSOAPModelBuilder = new StAXSOAPModelBuilder(reader, null);
            SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope();

            //Set the processed flag of the processed headers
            SOAPHeader header = envelope.getHeader();
            for (Iterator iter = processedHeaderQNames.iterator(); iter.hasNext();) {
                QName name = (QName) iter.next();
                Iterator omKids = header.getChildrenWithName(name);
                if (omKids.hasNext()) {
                    ((SOAPHeaderBlock) omKids.next()).setProcessed();
                }
            }

            envelope.build();

            return envelope;

        } catch (FactoryConfigurationError e) {
            throw new WSSecurityException(e.getMessage());
        }
    } else {
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            XMLUtils.outputDOM(doc.getDocumentElement(), os, true);
            ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());

            StAXSOAPModelBuilder stAXSOAPModelBuilder = new StAXSOAPModelBuilder(
                    XMLInputFactory.newInstance().createXMLStreamReader(bais), null);
            return stAXSOAPModelBuilder.getSOAPEnvelope();
        } catch (Exception e) {
            throw new WSSecurityException(e.getMessage());
        }
    }
}

From source file:org.apache.sandesha2.SandeshaTestCase.java

protected SOAPEnvelope getSOAPEnvelope(String relativePath, String resourceName) {
    try {/*w  w w .  j  a va 2  s.c  o  m*/
        XMLStreamReader reader = XMLInputFactory.newInstance()
                .createXMLStreamReader(getResource(relativePath, resourceName));
        OMXMLParserWrapper wrapper = OMXMLBuilderFactory
                .createStAXSOAPModelBuilder(OMAbstractFactory.getSOAP11Factory(), reader);
        return (SOAPEnvelope) wrapper.getDocumentElement();

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

From source file:org.apache.solr.handler.AnalysisRequestHandler.java

@Override
public void init(NamedList args) {
    super.init(args);

    inputFactory = XMLInputFactory.newInstance();
    try {/*from w  ww  .j a va  2s  . co m*/
        // The java 1.6 bundled stax parser (sjsxp) does not currently have a thread-safe
        // XMLInputFactory, as that implementation tries to cache and reuse the
        // XMLStreamReader.  Setting the parser-specific "reuse-instance" property to false
        // prevents this.
        // All other known open-source stax parsers (and the bea ref impl)
        // have thread-safe factories.
        inputFactory.setProperty("reuse-instance", Boolean.FALSE);
    } catch (IllegalArgumentException ex) {
        // Other implementations will likely throw this exception since "reuse-instance"
        // isimplementation specific.
        log.debug("Unable to set the 'reuse-instance' property for the input factory: " + inputFactory);
    }
}

From source file:org.apache.solr.handler.DocumentAnalysisRequestHandler.java

@Override
public void init(NamedList args) {
    super.init(args);

    inputFactory = XMLInputFactory.newInstance();
    try {/*from w ww . j a  v  a 2s .c  om*/
        // The java 1.6 bundled stax parser (sjsxp) does not currently have a thread-safe
        // XMLInputFactory, as that implementation tries to cache and reuse the
        // XMLStreamReader.  Setting the parser-specific "reuse-instance" property to false
        // prevents this.
        // All other known open-source stax parsers (and the bea ref impl)
        // have thread-safe factories.
        inputFactory.setProperty("reuse-instance", Boolean.FALSE);
    } catch (IllegalArgumentException ex) {
        // Other implementations will likely throw this exception since "reuse-instance"
        // isimplementation specific.
        log.debug("Unable to set the 'reuse-instance' property for the input factory: " + inputFactory);
    }
    inputFactory.setXMLReporter(xmllog);
}

From source file:org.apache.solr.handler.loader.XMLLoader.java

@Override
public XMLLoader init(SolrParams args) {
    // Init StAX parser:
    inputFactory = XMLInputFactory.newInstance();
    EmptyEntityResolver.configureXMLInputFactory(inputFactory);
    inputFactory.setXMLReporter(xmllog);
    try {// w w  w. j av a2 s.c  o  m
        // The java 1.6 bundled stax parser (sjsxp) does not currently have a thread-safe
        // XMLInputFactory, as that implementation tries to cache and reuse the
        // XMLStreamReader.  Setting the parser-specific "reuse-instance" property to false
        // prevents this.
        // All other known open-source stax parsers (and the bea ref impl)
        // have thread-safe factories.
        inputFactory.setProperty("reuse-instance", Boolean.FALSE);
    } catch (IllegalArgumentException ex) {
        // Other implementations will likely throw this exception since "reuse-instance"
        // isimplementation specific.
        log.debug("Unable to set the 'reuse-instance' property for the input chain: " + inputFactory);
    }

    // Init SAX parser (for XSL):
    saxFactory = SAXParserFactory.newInstance();
    saxFactory.setNamespaceAware(true); // XSL needs this!
    EmptyEntityResolver.configureSAXParserFactory(saxFactory);

    xsltCacheLifetimeSeconds = XSLT_CACHE_DEFAULT;
    if (args != null) {
        xsltCacheLifetimeSeconds = args.getInt(XSLT_CACHE_PARAM, XSLT_CACHE_DEFAULT);
        log.debug("xsltCacheLifetimeSeconds=" + xsltCacheLifetimeSeconds);
    }
    return this;
}

From source file:org.apache.solr.handler.XmlUpdateRequestHandlerTest.java

@BeforeClass
public static void beforeTests() throws Exception {
    initCore("solrconfig.xml", "schema.xml");
    handler = new UpdateRequestHandler();
    inputFactory = XMLInputFactory.newInstance();
}

From source file:org.apache.solr.update.AddBlockUpdateTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    String oldCacheNamePropValue = System.getProperty("blockJoinParentFilterCache");
    System.setProperty("blockJoinParentFilterCache",
            (cachedMode = random().nextBoolean()) ? "blockJoinParentFilterCache" : "don't cache");
    if (oldCacheNamePropValue != null) {
        System.setProperty("blockJoinParentFilterCache", oldCacheNamePropValue);
    }//  w ww. j  a  v a2s.  c  o  m
    inputFactory = XMLInputFactory.newInstance();

    exe = // Executors.newSingleThreadExecutor();
            rarely() ? ExecutorUtil.newMDCAwareFixedThreadPool(atLeast(2),
                    new DefaultSolrThreadFactory("AddBlockUpdateTest"))
                    : ExecutorUtil
                            .newMDCAwareCachedThreadPool(new DefaultSolrThreadFactory("AddBlockUpdateTest"));

    initCore("solrconfig.xml", "schema15.xml");
}