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.talend.dataprep.schema.xls.XlsUtils.java

/**
 *
 * @param inputStream xls sheet inputStream
 * @return the column number from reading sheet metadata or -1 if unknown
 * @throws XMLStreamException//from ww w .j  av  a  2  s.co m
 * @throws IOException
 */
public static int getColumnsNumber(InputStream inputStream) throws XMLStreamException, IOException {
    // If doesn't support mark, wrap up
    if (!inputStream.markSupported()) {
        inputStream = new PushbackInputStream(inputStream, 8);
    }

    int colNumber = 0;

    // TDP-1781 xlsx files may not containing dimension so we fallback to col element number

    XMLStreamReader streamReader = XML_INPUT_FACTORY.createXMLStreamReader(inputStream);
    try {
        while (streamReader.hasNext()) {
            switch (streamReader.next()) {
            case START_ELEMENT:
                if (StringUtils.equals(streamReader.getLocalName(), "dimension")) {
                    Map<String, String> attributesValues = getAttributesNameValue(streamReader);
                    if (!attributesValues.isEmpty()) {
                        return getColumnsNumberFromDimension(attributesValues.get("ref"));
                    }
                }
                if (StringUtils.equals(streamReader.getLocalName(), "col")) {
                    colNumber++;
                }
                break;
            case END_ELEMENT:
                if (StringUtils.equals(streamReader.getLocalName(), "cols")) {
                    return colNumber;
                }
            default:
                // no op
            }
        }
    } finally {
        if (streamReader != null) {
            streamReader.close();
        }
    }
    return -1;
}

From source file:org.unitedinternet.cosmo.model.text.XhtmlCollectionFormat.java

public CollectionItem parse(String source, EntityFactory entityFactory) throws ParseException {
    CollectionItem collection = entityFactory.createCollection();

    try {//from   ww w.  j  a va  2s  .co m
        if (source == null) {
            throw new ParseException("Source has no XML data", -1);
        }
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inCollection = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement()) {
                continue;
            }

            if (hasClass(reader, "collection")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found collection element");
                }
                inCollection = true;
                continue;
            }

            if (inCollection && hasClass(reader, "name")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found name element");
                }

                String name = reader.getElementText();
                if (StringUtils.isBlank(name)) {
                    throw new ParseException("Empty name not allowed",
                            reader.getLocation().getCharacterOffset());
                }
                collection.setDisplayName(name);

                continue;
            }

            if (inCollection && hasClass(reader, "uuid")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found uuid element");
                }

                String uuid = reader.getElementText();
                if (StringUtils.isBlank(uuid)) {
                    throw new ParseException("Empty uuid not allowed",
                            reader.getLocation().getCharacterOffset());
                }
                collection.setUid(uuid);

                continue;
            }
        }

        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    return collection;
}

From source file:org.unitedinternet.cosmo.model.text.XhtmlPreferenceFormat.java

public Preference parse(String source, EntityFactory entityFactory) throws ParseException {
    Preference pref = entityFactory.createPreference();

    try {//from w w  w.  java 2s .c  o  m
        if (source == null) {
            throw new ParseException("Source has no XML data", -1);
        }
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inPreference = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement()) {
                continue;
            }

            if (hasClass(reader, "preference")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found preference element");
                }
                inPreference = true;
                continue;
            }

            if (inPreference && hasClass(reader, "key")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found key element");
                }

                String key = reader.getElementText();
                if (StringUtils.isBlank(key)) {
                    handleParseException("Key element must not be empty", reader);
                }
                pref.setKey(key);

                continue;
            }

            if (inPreference && hasClass(reader, "value")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found value element");
                }

                String value = reader.getElementText();
                if (StringUtils.isBlank(value)) {
                    value = "";
                }
                pref.setValue(value);

                continue;
            }
        }

        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    return pref;
}

From source file:org.unitedinternet.cosmo.model.text.XhtmlSubscriptionFormat.java

public CollectionSubscription parse(String source, EntityFactory entityFactory) throws ParseException {
    CollectionSubscription sub = entityFactory.createCollectionSubscription();

    try {//from   w  ww  . j  a  v a2s  .  c om
        if (source == null) {
            throw new ParseException("Source has no XML data", -1);
        }
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inLocalSub = false;
        boolean inCollection = false;
        boolean inTicket = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement()) {
                continue;
            }

            if (hasClass(reader, "local-subscription")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found local-subscription element");
                }
                inLocalSub = true;
                continue;
            }

            if (inLocalSub && hasClass(reader, "name")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found name element");
                }

                String name = reader.getElementText();
                if (StringUtils.isBlank(name)) {
                    handleParseException("Name element must not be empty", reader);
                }
                sub.setDisplayName(name);

                continue;
            }

            if (inLocalSub && hasClass(reader, "collection")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found collection element");
                }
                inCollection = true;
                inTicket = false;
                continue;
            }

            if (inCollection && hasClass(reader, "uuid")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found uuid element");
                }

                String uuid = reader.getElementText();
                if (StringUtils.isBlank(uuid)) {
                    handleParseException("Uuid element must not be empty", reader);
                }
                sub.setCollectionUid(uuid);

                continue;
            }

            if (inLocalSub && hasClass(reader, "ticket")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found ticket element");
                }
                inCollection = false;
                inTicket = true;
                continue;
            }

            if (inTicket && hasClass(reader, "key")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found key element");
                }

                String key = reader.getElementText();
                if (StringUtils.isBlank(key)) {
                    handleParseException("Key element must not be empty", reader);
                }
                sub.setTicketKey(key);

                continue;
            }
        }

        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    return sub;
}

From source file:org.unitedinternet.cosmo.model.text.XhtmlTicketFormat.java

public Ticket parse(String source, EntityFactory entityFactory) throws ParseException {

    String key = null;//w ww. ja v  a2  s .c  om
    TicketType type = null;
    Integer timeout = null;
    try {
        if (source == null) {
            throw new ParseException("Source has no XML data", -1);
        }
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inTicket = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement()) {
                continue;
            }

            if (hasClass(reader, "ticket")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found ticket element");
                }
                inTicket = true;
                continue;
            }

            if (inTicket && hasClass(reader, "key")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found key element");
                }

                key = reader.getElementText();
                if (StringUtils.isBlank(key)) {
                    handleParseException("Key element must not be empty", reader);
                }

                continue;
            }

            if (inTicket && hasClass(reader, "type")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found type element");
                }

                String typeId = reader.getAttributeValue(null, "title");
                if (StringUtils.isBlank(typeId)) {
                    handleParseException("Ticket type title must not be empty", reader);
                }
                type = TicketType.createInstance(typeId);

                continue;
            }
            if (inTicket && hasClass(reader, "timeout")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found timeout element");
                }

                String timeoutString = reader.getAttributeValue(null, "title");
                if (StringUtils.isBlank(timeoutString)) {
                    timeout = null;
                } else {
                    timeout = Integer.getInteger(timeoutString);
                }

                continue;
            }
        }
        if (type == null || key == null) {
            handleParseException("Ticket must have type and key", reader);
        }
        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    Ticket ticket = entityFactory.createTicket(type);
    ticket.setKey(key);
    if (timeout == null) {
        ticket.setTimeout(Ticket.TIMEOUT_INFINITE);
    } else {
        ticket.setTimeout(timeout);
    }

    return ticket;
}

From source file:org.unitedinternet.cosmo.util.DomReader.java

public static Node read(Reader in) throws ParserConfigurationException, XMLStreamException, IOException {
    XMLStreamReader reader = null;
    try {//from  www  . ja  v  a  2 s.co  m
        Document d = BUILDER_FACTORY.newDocumentBuilder().newDocument();
        reader = XML_INPUT_FACTORY.createXMLStreamReader(in);
        return readNode(d, reader);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (XMLStreamException e2) {
                LOG.warn("Unable to close XML reader", e2);
            }
        }
    }
}

From source file:org.ut.biolab.medsavant.client.plugin.AppController.java

public AppDescriptor getDescriptorFromFile(File f) throws PluginVersionException {
    XMLStreamReader reader;

    try {//from w  ww.ja va 2  s.c  o  m
        JarFile jar = new JarFile(f);
        ZipEntry entry = jar.getEntry("plugin.xml");
        if (entry != null) {
            InputStream entryStream = jar.getInputStream(entry);
            reader = XMLInputFactory.newInstance().createXMLStreamReader(entryStream);
            String className = null;
            String id = null;
            String version = null;
            String sdkVersion = null;
            String name = null;
            String category = AppDescriptor.Category.UTILITY.toString();
            String currentElement = null;
            String currentText = "";
            do {
                switch (reader.next()) {
                case XMLStreamConstants.START_ELEMENT:
                    switch (readElement(reader)) {
                    case PLUGIN:
                        className = readAttribute(reader, AppDescriptor.PluginXMLAttribute.CLASS);

                        //category can be specified as an attribute or <property>.
                        category = readAttribute(reader, AppDescriptor.PluginXMLAttribute.CATEGORY);
                        break;

                    case ATTRIBUTE:
                        if ("sdk-version".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.ID))) {
                            sdkVersion = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                        }
                        break;

                    case PARAMETER:
                        if ("name".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.ID))) {
                            name = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                        }
                        break;

                    case PROPERTY:
                        if ("name".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            name = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (name == null) {
                                currentElement = "name";
                            }
                        }

                        if ("version".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            version = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (version == null) {
                                currentElement = "version";
                            }
                        }

                        if ("sdk-version"
                                .equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            sdkVersion = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (sdkVersion == null) {
                                currentElement = "sdk-version";
                            }
                        }

                        if ("category".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            category = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (category == null) {
                                currentElement = "category";
                            }
                        }

                        break;
                    }
                    break;

                case XMLStreamConstants.CHARACTERS:
                    if (reader.isWhiteSpace()) {
                        break;
                    } else if (currentElement != null) {
                        currentText += reader.getText().trim().replace("\t", "");
                    }
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    if (readElement(reader) == AppDescriptor.PluginXMLElement.PROPERTY) {
                        if (currentElement != null && currentText.length() > 0) {
                            if (currentElement.equals("name")) {
                                name = currentText;
                            } else if (currentElement.equals("sdk-version")) {
                                sdkVersion = currentText;
                            } else if (currentElement.equals("category")) {
                                category = currentText;
                            } else if (currentElement.equals("version")) {
                                version = currentText;
                            }
                        }
                        currentText = "";
                        currentElement = null;
                    }
                    break;

                case XMLStreamConstants.END_DOCUMENT:
                    reader.close();
                    reader = null;
                    break;
                }
            } while (reader != null);

            System.out.println(className + " " + name + " " + version);

            if (className != null && name != null && version != null) {
                return new AppDescriptor(className, version, name, sdkVersion, category, f);
            }
        }
    } catch (Exception x) {
        LOG.error("Error parsing plugin.xml from " + f.getAbsolutePath() + ": " + x);
    }
    throw new PluginVersionException(f.getName() + " did not contain a valid plugin");
}

From source file:org.ut.biolab.medsavant.client.plugin.PluginIndex.java

public PluginIndex(URL url) throws IOException {
    urls = new HashMap<String, URL>();
    try {/*from  ww w. j  a  v a  2 s  .c  om*/

        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(
                ClientNetworkUtils.openStream(url, ClientNetworkUtils.NONCRITICAL_CONNECT_TIMEOUT,
                        ClientNetworkUtils.NONCRITICAL_READ_TIMEOUT));
        if (reader.getVersion() == null) {
            throw new XMLStreamException("Invalid XML at URL " + url);
        }
        boolean done = false;
        String id = null;
        do {
            if (reader.hasNext()) {
                int t = reader.next();
                switch (t) {
                case XMLStreamConstants.START_ELEMENT:
                    String elemName = reader.getLocalName();
                    if (elemName.equals("leaf")) {
                        id = reader.getAttributeValue(null, "id");
                    } else if (elemName.equals("url")) {
                        if (id != null) {
                            try {
                                urls.put(id, new URL(reader.getElementText()));
                            } catch (MalformedURLException x) {
                                LOG.warn(String.format("Unable to parse \"%s\" as a plugin URL.",
                                        reader.getElementText()));
                            }
                            id = null;
                        }
                    }
                    break;
                case XMLStreamConstants.END_DOCUMENT:
                    reader.close();
                    done = true;
                    break;
                }
            } else {
                throw new XMLStreamException("Malformed XML at " + url);
            }
        } while (!done);
    } catch (XMLStreamException x) {
        throw new IOException("Unable to get version number from web-site.", x);
    }
}

From source file:org.wso2.am.integration.test.utils.generic.APIMTestCaseUtils.java

/**
 * Loads the specified resource from the classpath and returns its content as an OMElement.
 *
 * @param path A relative path to the resource file
 * @return An OMElement containing the resource content
 *///from  ww  w  .j av a 2  s .  c  o  m
public static OMElement loadResource(String path) throws FileNotFoundException, XMLStreamException {
    OMElement documentElement = null;
    FileInputStream inputStream = null;
    XMLStreamReader parser = null;
    StAXOMBuilder builder = null;
    path = TestConfigurationProvider.getResourceLocation() + path;
    File file = new File(path);
    if (file.exists()) {
        try {
            inputStream = new FileInputStream(file);
            parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
            //create the builder
            builder = new StAXOMBuilder(parser);
            //get the root element (in this case the envelope)
            documentElement = builder.getDocumentElement().cloneOMElement();
        } finally {
            if (builder != null) {
                builder.close();
            }
            if (parser != null) {
                try {
                    parser.close();
                } catch (XMLStreamException e) {
                    //ignore
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    //ignore
                }
            }

        }
    } else {
        throw new FileNotFoundException("File Not Exist at " + path);
    }
    return documentElement;
}

From source file:org.wso2.carbon.appfactory.repository.provider.common.AbstractRepositoryProvider.java

protected Repository getRepositoryFromStream(InputStream responseBodyAsStream) throws RepositoryMgtException {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader reader = null;
    Repository repository = new Repository();
    try {/*from  ww w.j a  v a2  s. c o m*/
        reader = xif.createXMLStreamReader(responseBodyAsStream);
        StAXOMBuilder builder = new StAXOMBuilder(reader);
        OMElement rootElement = builder.getDocumentElement();
        if (REPOSITORY_XML_ROOT_ELEMENT.equals(rootElement.getLocalName())) {
            Iterator elements = rootElement.getChildElements();
            while (elements.hasNext()) {
                Object object = elements.next();
                if (object instanceof OMElement) {
                    OMElement element = (OMElement) object;
                    if (REPOSITORY_URL_ELEMENT.equals(element.getLocalName())) {
                        repository.setUrl(element.getText());
                        break;
                    }
                }
            }
        } else {
            String msg = "In the payload no repository information is found";
            log.error(msg);
            throw new RepositoryMgtException(msg);
        }
    } catch (XMLStreamException e) {
        String msg = "Error while reading the stream";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (XMLStreamException e) {
            String msg = "Error while serializing the payload";
            log.error(msg, e);
        }
    }
    return repository;
}