Example usage for javax.xml.stream XMLStreamReader close

List of usage examples for javax.xml.stream XMLStreamReader close

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader close.

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Frees any resources associated with this Reader.

Usage

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

/**
 * @since solr 1.2/*from   ww w.  j a  va 2 s  . c  o  m*/
 */
void processUpdate(SolrQueryRequest req, UpdateRequestProcessor processor, XMLStreamReader parser)
        throws XMLStreamException, IOException, FactoryConfigurationError, InstantiationException,
        IllegalAccessException, TransformerConfigurationException {
    AddUpdateCommand addCmd = null;
    // Need to instansiate a SolrParams, even if req is null, for backward compat with legacyUpdate
    SolrParams params = (req != null) ? req.getParams() : new ModifiableSolrParams();
    while (true) {
        int event = parser.next();
        switch (event) {
        case XMLStreamConstants.END_DOCUMENT:
            parser.close();
            return;

        case XMLStreamConstants.START_ELEMENT:
            String currTag = parser.getLocalName();
            if (currTag.equals(XmlUpdateRequestHandler.ADD)) {
                XmlUpdateRequestHandler.log.trace("SolrCore.update(add)");

                addCmd = new AddUpdateCommand();

                // First look for commitWithin parameter on the request, will be overwritten for individual <add>'s
                addCmd.commitWithin = params.getInt(UpdateParams.COMMIT_WITHIN, -1);

                boolean overwrite = true; // the default

                Boolean overwritePending = null;
                Boolean overwriteCommitted = null;
                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String attrName = parser.getAttributeLocalName(i);
                    String attrVal = parser.getAttributeValue(i);
                    if (XmlUpdateRequestHandler.OVERWRITE.equals(attrName)) {
                        overwrite = StrUtils.parseBoolean(attrVal);
                    } else if (XmlUpdateRequestHandler.ALLOW_DUPS.equals(attrName)) {
                        overwrite = !StrUtils.parseBoolean(attrVal);
                    } else if (XmlUpdateRequestHandler.COMMIT_WITHIN.equals(attrName)) {
                        addCmd.commitWithin = Integer.parseInt(attrVal);
                    } else if (XmlUpdateRequestHandler.OVERWRITE_PENDING.equals(attrName)) {
                        overwritePending = StrUtils.parseBoolean(attrVal);
                    } else if (XmlUpdateRequestHandler.OVERWRITE_COMMITTED.equals(attrName)) {
                        overwriteCommitted = StrUtils.parseBoolean(attrVal);
                    } else {
                        XmlUpdateRequestHandler.log.warn("Unknown attribute id in add:" + attrName);
                    }
                }

                // check if these flags are set
                if (overwritePending != null && overwriteCommitted != null) {
                    if (overwritePending != overwriteCommitted) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                                "can't have different values for 'overwritePending' and 'overwriteCommitted'");
                    }
                    overwrite = overwritePending;
                }
                addCmd.overwriteCommitted = overwrite;
                addCmd.overwritePending = overwrite;
                addCmd.allowDups = !overwrite;
            } else if ("doc".equals(currTag)) {
                //            if(addCmd != null) {
                XmlUpdateRequestHandler.log.trace("adding doc...");
                addCmd.clear();
                addCmd.solrDoc = readDoc(parser);
                processor.processAdd(addCmd);
                //            } else {
                //              throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unexpected <doc> tag without an <add> tag surrounding it.");
                //            }
            } else if (XmlUpdateRequestHandler.COMMIT.equals(currTag)
                    || XmlUpdateRequestHandler.OPTIMIZE.equals(currTag)) {
                XmlUpdateRequestHandler.log.trace("parsing " + currTag);

                CommitUpdateCommand cmd = new CommitUpdateCommand(
                        XmlUpdateRequestHandler.OPTIMIZE.equals(currTag));

                boolean sawWaitSearcher = false, sawWaitFlush = false;
                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String attrName = parser.getAttributeLocalName(i);
                    String attrVal = parser.getAttributeValue(i);
                    if (XmlUpdateRequestHandler.WAIT_FLUSH.equals(attrName)) {
                        cmd.waitFlush = StrUtils.parseBoolean(attrVal);
                        sawWaitFlush = true;
                    } else if (XmlUpdateRequestHandler.WAIT_SEARCHER.equals(attrName)) {
                        cmd.waitSearcher = StrUtils.parseBoolean(attrVal);
                        sawWaitSearcher = true;
                    } else if (UpdateParams.MAX_OPTIMIZE_SEGMENTS.equals(attrName)) {
                        cmd.maxOptimizeSegments = Integer.parseInt(attrVal);
                    } else if (UpdateParams.EXPUNGE_DELETES.equals(attrName)) {
                        cmd.expungeDeletes = StrUtils.parseBoolean(attrVal);
                    } else {
                        XmlUpdateRequestHandler.log.warn("unexpected attribute commit/@" + attrName);
                    }
                }

                // If waitFlush is specified and waitSearcher wasn't, then
                // clear waitSearcher.
                if (sawWaitFlush && !sawWaitSearcher) {
                    cmd.waitSearcher = false;
                }
                processor.processCommit(cmd);
            } // end commit
            else if (XmlUpdateRequestHandler.ROLLBACK.equals(currTag)) {
                XmlUpdateRequestHandler.log.trace("parsing " + currTag);

                RollbackUpdateCommand cmd = new RollbackUpdateCommand();

                processor.processRollback(cmd);
            } // end rollback
            else if (XmlUpdateRequestHandler.DELETE.equals(currTag)) {
                XmlUpdateRequestHandler.log.trace("parsing delete");
                processDelete(processor, parser);
            } // end delete
            break;
        }
    }
}

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

@Override
public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream) throws Exception {
    final DOMResult result = new DOMResult();
    final Transformer t = getTransformer(req);
    InputStream is = null;/*from   ww w  .j a  v a  2 s.c om*/
    XMLStreamReader parser = null;
    // first step: read XML and build DOM using Transformer (this is no overhead, as XSL always produces
    // an internal result DOM tree, we just access it directly as input for StAX):
    try {
        is = stream.getStream();
        final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType());
        final InputSource isrc = new InputSource(is);
        isrc.setEncoding(charset);
        final SAXSource source = new SAXSource(isrc);
        t.transform(source, result);
    } catch (TransformerException te) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, te.getMessage(), te);
    } finally {
        IOUtils.closeQuietly(is);
    }
    // second step feed the intermediate DOM tree into StAX parser:
    try {
        parser = inputFactory.createXMLStreamReader(new DOMSource(result.getNode()));
        this.processUpdate(processor, parser);
    } catch (XMLStreamException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

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;
    try {/*from  w  ww.  ja va 2 s . c  o  m*/
        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;
    try {//from   w w w .j  a  v a 2  s .  c o  m
        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 va 2s. c  om*/
        //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 loadFromXmlFile(XMLInputFactory xmlIf, URL filePath, List<StoreObject> storeObjects)
        throws IOException, XMLStreamException {
    XMLStreamReader xmlReader;

    xmlReader = xmlIf.createXMLStreamReader(filePath.openStream());

    try {//from w  ww.j a v  a2 s  .  c  o  m
        while (xmlReader.hasNext()) {
            if (xmlReader.next() == XMLStreamConstants.START_ELEMENT
                    && "store".equals(xmlReader.getLocalName())) {
                StoreObject catalogStore = loadCatalogStore(xmlReader);
                if (catalogStore != null) {
                    storeObjects.add(catalogStore);
                }
            }
        }
    } finally {
        try {
            xmlReader.close();
        } catch (XMLStreamException ignored) {
        }
    }
}

From source file:org.atomserver.core.validators.SimpleXMLContentValidator.java

private void validateWellFormed(Reader reader) throws BadContentException {
    try {// www .  j a va 2s. c o  m
        // we will simply walk the doc and see if it throws an Exception
        XMLInputFactory xif = new WstxInputFactory();
        XMLStreamReader xmlreader = xif.createXMLStreamReader(reader);

        while (xmlreader.hasNext()) {
            // Errors won't occur unless we actually access the data...
            touchEvent(xmlreader);
        }
        xmlreader.close();
    } catch (XMLStreamException ee) {
        String msg = "Not well-formed XML :: XMLStreamException:: " + ee.getMessage();
        log.error(msg);
        throw new BadContentException(msg);
    }
}

From source file:org.auraframework.impl.factory.SVGParser.java

@Override
public SVGDef getDefinition(DefDescriptor<SVGDef> descriptor, TextSource<SVGDef> source)
        throws SVGParserException, QuickFixException {
    if (descriptor.getDefType() == DefType.SVG) {
        XMLStreamReader reader = null;
        String contents = source.getContents();
        //If the file is too big throw before we parse the whole thing.
        SVGDef ret = new SVGDefHandler<>(descriptor, source).createDefinition();
        try (StringReader stringReader = new StringReader(contents)) {
            reader = xmlInputFactory.createXMLStreamReader(stringReader);
            if (reader != null) {
                LOOP: while (reader.hasNext()) {
                    int type = reader.next();
                    switch (type) {
                    case XMLStreamConstants.END_DOCUMENT:
                        break LOOP;
                    //This is plain text inside the file
                    case XMLStreamConstants.CHARACTERS:
                        if (DISSALOWED_LIST.matcher(reader.getText()).matches()) {
                            throw new InvalidDefinitionException(
                                    String.format("Text contains disallowed symbols: %s", reader.getText()),
                                    XMLParser.getLocation(reader, source));
                        }//from   www .  j ava 2 s  . co m
                        break;
                    case XMLStreamConstants.START_ELEMENT:
                        String name = reader.getName().toString().toLowerCase();
                        if (!SVG_TAG_WHITELIST.contains(name)) {
                            throw new InvalidDefinitionException(
                                    String.format("Invalid SVG tag specified: %s", name),
                                    XMLParser.getLocation(reader, source));
                        }
                        for (int i = 0; i < reader.getAttributeCount(); i++) {
                            QName qAttr = reader.getAttributeName(i);
                            String attr = qAttr.getLocalPart();
                            if (SVG_ATTR_BLACKLIST.contains(attr)) {
                                throw new InvalidDefinitionException(
                                        String.format("Invalid SVG attribute specified: %s", attr),
                                        XMLParser.getLocation(reader, source));
                            }
                        }
                        break;
                    case XMLStreamConstants.END_ELEMENT:
                    case XMLStreamConstants.COMMENT:
                    case XMLStreamConstants.DTD:
                    case XMLStreamConstants.SPACE:
                        continue;
                    default:
                        throw new InvalidDefinitionException(String.format("Found unexpected element in xml."),
                                XMLParser.getLocation(reader, source));
                    }
                }
            }
        } catch (XMLStreamException e) {
            throw new SVGParserException(StringEscapeUtils.escapeHtml4(e.getMessage()));
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (XMLStreamException e) {
                    //Well I tried to play nicely
                }
            }
        }
        return ret;
    }
    return null;
}

From source file:org.auraframework.impl.svg.parser.SVGParser.java

@Override
public SVGDef parse(DefDescriptor<SVGDef> descriptor, Source<SVGDef> source)
        throws SVGParserException, QuickFixException {
    if (descriptor.getDefType() == DefType.SVG) {
        XMLStreamReader reader = null;
        String contents = source.getContents();
        //If the file is too big throw before we parse the whole thing.
        SVGDef ret = new SVGDefHandler<>(descriptor, source).createDefinition();
        try (StringReader stringReader = new StringReader(contents)) {
            reader = xmlInputFactory.createXMLStreamReader(stringReader);
            if (reader != null) {
                LOOP: while (reader.hasNext()) {
                    int type = reader.next();
                    switch (type) {
                    case XMLStreamConstants.END_DOCUMENT:
                        break LOOP;
                    //This is plain text inside the file
                    case XMLStreamConstants.CHARACTERS:
                        if (DISSALOWED_LIST.matcher(reader.getText()).matches()) {
                            throw new InvalidDefinitionException(
                                    String.format("Text contains disallowed symbols: %s", reader.getText()),
                                    XMLParser.getLocation(reader, source));
                        }/*w ww  .  ja v  a2 s.  co  m*/
                        break;
                    case XMLStreamConstants.START_ELEMENT:
                        String name = reader.getName().toString().toLowerCase();
                        if (!SVG_TAG_WHITELIST.contains(name)) {
                            throw new InvalidDefinitionException(
                                    String.format("Invalid SVG tag specified: %s", name),
                                    XMLParser.getLocation(reader, source));
                        }
                        for (int i = 0; i < reader.getAttributeCount(); i++) {
                            QName qAttr = reader.getAttributeName(i);
                            String attr = qAttr.getLocalPart();
                            if (SVG_ATTR_BLACKLIST.contains(attr)) {
                                throw new InvalidDefinitionException(
                                        String.format("Invalid SVG attribute specified: %s", attr),
                                        XMLParser.getLocation(reader, source));
                            }
                        }
                        break;
                    case XMLStreamConstants.END_ELEMENT:
                    case XMLStreamConstants.COMMENT:
                    case XMLStreamConstants.DTD:
                    case XMLStreamConstants.SPACE:
                        continue;
                    default:
                        throw new InvalidDefinitionException(String.format("Found unexpected element in xml."),
                                XMLParser.getLocation(reader, source));
                    }
                }
            }
        } catch (XMLStreamException e) {
            throw new SVGParserException(StringEscapeUtils.escapeHtml4(e.getMessage()));
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (XMLStreamException e) {
                    //Well I tried to play nicely
                }
            }
        }
        return ret;
    }
    return null;
}

From source file:org.betaconceptframework.astroboa.engine.jcr.io.Deserializer.java

public <T> T deserializeContent(InputStream source, boolean jsonSource, Class<T> classWhoseContentIsImported,
        ImportConfiguration configuration) {

    if (configuration != null) {
        persistMode = configuration.getPersistMode();
        version = configuration.isVersion();
        updateLastModificationDate = configuration.isUpdateLastModificationTime();
    }/*  w w w. ja  va 2 s . c  om*/

    if (persistMode == null) {
        if (classWhoseContentIsImported == Repository.class
                || List.class.isAssignableFrom(classWhoseContentIsImported)) {
            persistMode = PersistMode.PERSIST_ENTITY_TREE;
        } else {
            persistMode = PersistMode.DO_NOT_PERSIST;
        }
    }

    context = new Context(cmsRepositoryEntityUtils, cmsQueryHandler, session, configuration);

    XMLStreamReader xmlStreamReader = null;
    SAXSource saxSource = null;
    try {

        Object entity = null;

        long start = System.currentTimeMillis();

        if (jsonSource) {

            xmlStreamReader = CmsEntityDeserialization.Context.createJSONReader(source, true,
                    classWhoseContentIsImported);

            JsonImportContentHandler<T> handler = new JsonImportContentHandler(classWhoseContentIsImported,
                    this);

            XMLStreamReaderToContentHandler xmlStreamReaderToContentHandler = new XMLStreamReaderToContentHandler(
                    xmlStreamReader, handler, false, false);
            xmlStreamReaderToContentHandler.bridge();
            entity = handler.getResult();

            logger.debug(" Unmarshal json to {} took {}", classWhoseContentIsImported.getSimpleName(),
                    DurationFormatUtils.formatDuration(System.currentTimeMillis() - start, "HH:mm:ss.SSSSSS"));
        } else {
            saxSource = CmsEntityDeserialization.Context.createSAXSource(source, repositoryEntityResolver,
                    false); //we explicitly disable validation because partial saves are allowed

            ImportContentHandler<T> handler = new ImportContentHandler(classWhoseContentIsImported, this);
            saxSource.getXMLReader().setContentHandler(handler);

            saxSource.getXMLReader().parse(saxSource.getInputSource());
            entity = handler.getImportResult();

            logger.debug("Unmarshal xml to {} took {}", classWhoseContentIsImported.getSimpleName(),
                    DurationFormatUtils.formatDuration(System.currentTimeMillis() - start, "HH:mm:ss.SSSSSS"));
        }

        //If entity is not of type T then a class cast exception is thrown.
        if (entity instanceof CmsRepositoryEntity) {
            entity = save((CmsRepositoryEntity) entity);
        }

        return (T) entity;

    } catch (CmsException e) {
        logger.error("", e);
        throw e;
    } catch (Exception e) {
        logger.error("", e);
        throw new CmsException(e.getMessage());
    } finally {

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
                //Ignore exception
            }
        }

        if (saxSource != null && saxSource.getInputSource() != null) {
            IOUtils.closeQuietly(saxSource.getInputSource().getByteStream());
            IOUtils.closeQuietly(saxSource.getInputSource().getCharacterStream());
        }

        if (context != null) {
            context.dispose();
            context = null;
        }

    }
}