Example usage for javax.xml.stream XMLStreamConstants START_ELEMENT

List of usage examples for javax.xml.stream XMLStreamConstants START_ELEMENT

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamConstants START_ELEMENT.

Prototype

int START_ELEMENT

To view the source code for javax.xml.stream XMLStreamConstants START_ELEMENT.

Click Source Link

Document

Indicates an event is a start element

Usage

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

private int countFeedElements(final InputStream is, final String elementName) throws XMLStreamException {
    final XMLEventReader reader = getEventReader(is);

    int count = 0;

    while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && elementName.equals(event.asStartElement().getName().getLocalPart())) {
            count++;//from   ww  w .ja  v a2  s  . com
        }
    }

    reader.close();
    return count;
}

From source file:ddf.catalog.source.opensearch.impl.OpenSearchSource.java

private InputTransformer getInputTransformer(InputStream inputStream) {
    XMLStreamReader xmlStreamReader = null;
    try {//w  w  w.j  a  v a2 s  .c  o  m
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(inputStream);
        while (xmlStreamReader.hasNext()) {
            int next = xmlStreamReader.next();
            if (next == XMLStreamConstants.START_ELEMENT) {
                String namespaceUri = xmlStreamReader.getNamespaceURI();
                InputTransformer transformerReference = lookupTransformerReference(namespaceUri);
                if (transformerReference != null) {
                    return transformerReference;
                }
            }
        }
    } catch (XMLStreamException | InvalidSyntaxException e) {
        LOGGER.debug("Failed to parse transformer namespace", e);
    } finally {
        try {
            if (xmlStreamReader != null) {
                xmlStreamReader.close();
            }
        } catch (XMLStreamException e) {
            LOGGER.debug("failed to close namespace reader", e);
        }
    }
    return null;
}

From source file:davmail.exchange.ews.EWSMethod.java

protected String handleTag(XMLStreamReader reader, String localName) throws XMLStreamException {
    String result = null;//  www . ja  v a  2s.c o m
    int event = reader.getEventType();
    if (event == XMLStreamConstants.START_ELEMENT && localName.equals(reader.getLocalName())) {
        while (reader.hasNext()
                && !((event == XMLStreamConstants.END_ELEMENT && localName.equals(reader.getLocalName())))) {
            event = reader.next();
            if (event == XMLStreamConstants.CHARACTERS) {
                result = reader.getText();
            }
        }
    }
    return result;
}

From source file:com.microsoft.tfs.core.ws.runtime.client.SOAPService.java

private void executeSOAPRequestInternal(final SOAPRequest request, final String responseName,
        final SOAPMethodResponseReader responseReader)
        throws SOAPFault, UnauthorizedException, ProxyUnauthorizedException, InvalidServerResponseException,
        EndpointNotFoundException, TransportException, CanceledException {
    final PostMethod method = request.getPostMethod();

    final long start = System.currentTimeMillis();
    long serverExecute = -1;
    long contentLength = -1;
    int response = -1;
    boolean isCompressed = false;

    IOException ioException = null;
    byte[] responseBytes = null;
    TraceInputStream responseStream = null;

    try {//from ww  w . j  av a2s.  c o m
        /*
         * Our implementation aims to be tolerant of connection resets
         * caused by half-open sockets. It detects them and retries the
         * operation once.
         *
         * Here's the problem: sometimes IIS's ASP.NET worker process is
         * recycled (this can happen because of an application pool time
         * threshold, number of requests served threshold, memory usage
         * threshold, etc.). When the process is recycled, most sockets that
         * were connected to it (including client sockets) will continue to
         * work fine once IIS builds a new worker. Sometimes, however, bad
         * things happen: those connected sockets will be reset by the
         * server the first time they're used.
         *
         * Since the default TFS configuration (as of RC) is to recycle the
         * application pool's worker every 29 hours, a user is likely to
         * have a half-open TCP socket if he leaves his client running
         * through the night. The client may work correctly, but in the case
         * that it receives a reset, it is pretty safe to retry the
         * operation once.
         *
         * Some JREs use the string "Connection reset by peer", others use
         * "Connection reset". We will match both.
         */
        final long serverStart = System.currentTimeMillis();
        try {
            response = client.executeMethod(method);
        } catch (final SocketException e) {
            /*
             * If the user cancelled the current task, we might get a
             * "socket closed" exception if the HTTPConnectionCanceller
             * closed the socket after timing out waiting for voluntary
             * cancel.
             */
            if (TaskMonitorService.getTaskMonitor().isCanceled() && (e.getMessage().startsWith("Socket closed") //$NON-NLS-1$
                    || e.getMessage().startsWith("Stream closed"))) //$NON-NLS-1$
            {
                throw new CanceledException();
            }

            /*
             * If this fault was not a TCP connection reset, rethrow it.
             */
            if (e.getMessage().startsWith("Connection reset") == false) //$NON-NLS-1$
            {
                throw e;
            }

            log.warn("Retrying invoke after a connection reset", e); //$NON-NLS-1$

            /*
             * Give it one more try on the user's behalf.
             */
            response = client.executeMethod(method);
        }
        serverExecute = System.currentTimeMillis() - serverStart;

        responseStream = getResponseStream(method);
        isCompressed = responseStream.isCompressed();

        switch (response) {
        case HttpStatus.SC_OK:
            XMLStreamReader reader = null;

            try {

                reader = SOAPService.xmlInputFactory.createXMLStreamReader(responseStream,
                        SOAPRequestEntity.SOAP_ENCODING);

                /*
                 * Read as far as the SOAP body from the stream.
                 */
                final QName envelopeQName = new QName(getDefaultSOAPNamespace(), "Envelope", "soap"); //$NON-NLS-1$ //$NON-NLS-2$
                final QName headerQName = new QName(getDefaultSOAPNamespace(), "Header", "soap"); //$NON-NLS-1$ //$NON-NLS-2$
                final QName bodyQName = new QName(getDefaultSOAPNamespace(), "Body", "soap"); //$NON-NLS-1$ //$NON-NLS-2$

                // Read the envelope.
                if (reader.nextTag() == XMLStreamConstants.START_ELEMENT
                        && reader.getName().equals(envelopeQName)) {
                    while (reader.nextTag() == XMLStreamConstants.START_ELEMENT) {
                        if (reader.getName().equals(headerQName)) {
                            // Ignore headers for now.
                            XMLStreamReaderHelper.readUntilElementEnd(reader);
                        } else if (reader.getName().equals(bodyQName)) {
                            /*
                             * The first element in the body should be
                             * the desired response element, which we
                             * must find (and read into) before we
                             * delegate to the reader (if there is one).
                             */
                            if (reader.nextTag() == XMLStreamConstants.START_ELEMENT
                                    && reader.getName().getLocalPart().equals(responseName)) {
                                try {
                                    if (responseReader != null) {
                                        responseReader.readSOAPResponse(reader, responseStream);
                                    }
                                } catch (final XMLStreamException e) {
                                    throw new InvalidServerResponseException(e);
                                }

                                return;
                            }
                        }
                    }
                }

                /*
                 * If we got here, some error happened (we couldn't find
                 * our envelope and body tags).
                 */
                throw new InvalidServerResponseException(
                        "The server's response does not seem to be a SOAP message."); //$NON-NLS-1$
            } catch (final XMLStreamException e) {
                final String messageFormat = "The server's response could not be parsed as XML: {0}"; //$NON-NLS-1$
                final String message = MessageFormat.format(messageFormat, e.getMessage());
                throw new InvalidServerResponseException(message);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final XMLStreamException e) {
                    }
                }
            }
        case HttpStatus.SC_UNAUTHORIZED:
        case HttpStatus.SC_MOVED_TEMPORARILY:
            /*
             * This may be an ACS or on-premises authentication failure,
             * examine the headers.
             */
            examineHeadersForFederatedAuthURL(method);
        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new ProxyUnauthorizedException(client.getHostConfiguration().getProxyHost(),
                    client.getHostConfiguration().getProxyPort(),
                    client.getState().getProxyCredentials(AuthScope.ANY));
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            /*
             * An error message may be inside the response, in the
             * headers.
             */
            examineHeadersForErrorMessage(method);
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
            /*
             * A SOAP fault may be inside the response.
             */
            examineBodyForFault(method);
        default:
            final String messageFormat = "The SOAP endpoint {0} could not be contacted.  HTTP status: {1}"; //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, method.getURI().toString(),
                    Integer.toString(response));
            throw new EndpointNotFoundException(message, response);
        }
    } catch (final IOException e) {
        ioException = e;
        throw new TransportException(e.getMessage(), e);
    } finally {
        final long total = System.currentTimeMillis() - start;

        if (responseStream != null) {
            try {
                responseStream.close();
            } catch (final IOException e) {
                ioException = e;
            }
            responseBytes = responseStream.getBytes();
            contentLength = responseStream.getTotalBytes();
        }
        /*
         * perform logging
         */
        try {
            if (log.isDebugEnabled()) {
                logExtended(method, serverExecute, total, contentLength, isCompressed, responseBytes,
                        ioException);
            } else {
                log.info(makeNormalLogEntry(method, serverExecute, total, contentLength, isCompressed));
            }
        } catch (final Throwable t) {
            /*
             * don't propogate any errors raised while logging
             */
            log.warn("Error logging SOAP call", t); //$NON-NLS-1$
        }

        method.releaseConnection();
    }
}

From source file:ddf.catalog.source.solr.DynamicSchemaResolver.java

/**
 * Given xml as a string, this method will parse out element text and CDATA text. It separates
 * each by one space character./*from w  w w.j  a va 2 s. c o  m*/
 *
 * @param xmlDatas List of XML as {@code String}
 * @return parsed CDATA and element text
 */
protected List<String> parseTextFrom(List<Serializable> xmlDatas) {

    StringBuilder builder = new StringBuilder();
    List<String> parsedTexts = new ArrayList<>();
    XMLStreamReader xmlStreamReader = null;
    StringReader sr = null;
    long starttime = System.currentTimeMillis();

    try {
        for (Serializable xmlData : xmlDatas) {
            // xml parser does not handle leading whitespace
            sr = new StringReader(xmlData.toString());
            xmlStreamReader = XML_INPUT_FACTORY.createXMLStreamReader(sr);

            while (xmlStreamReader.hasNext()) {
                int event = xmlStreamReader.next();

                if (event == XMLStreamConstants.CHARACTERS || event == XMLStreamConstants.CDATA) {

                    String text = xmlStreamReader.getText();

                    if (StringUtils.isNotBlank(text)) {
                        builder.append(" ").append(text.trim());
                    }

                }
                if (event == XMLStreamConstants.START_ELEMENT) {
                    for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) {

                        String text = xmlStreamReader.getAttributeValue(i);

                        if (StringUtils.isNotBlank(text)) {
                            builder.append(" ").append(text.trim());
                        }
                    }
                }
            }
            parsedTexts.add(builder.toString());
            builder.setLength(0);
        }
    } catch (XMLStreamException e1) {
        LOGGER.warn("Failure occurred in parsing the xml data. No data has been stored or indexed.", e1);
    } finally {
        IOUtils.closeQuietly(sr);
        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (XMLStreamException e) {
                LOGGER.debug("Exception closing XMLStreamReader", e);
            }
        }
    }
    long endTime = System.currentTimeMillis();

    LOGGER.debug("Parsing took {} ms", endTime - starttime);

    return parsedTexts;
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.ddi.DDIFileReader.java

private void processInvalrng(XMLStreamReader xmlr, SDIOMetadata smd, String variableName)
        throws XMLStreamException {
    for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (xmlr.getLocalName().equals("item")) {
                // Ranges -- not supported? (TODO)
                //VariableRange range = new VariableRange();
                //dv.getInvalidRanges().add(range);
                //range.setDataVariable(dv);
                //range.setBeginValue( xmlr.getAttributeValue(null, "VALUE") );
                //range.setBeginValueType(varService.findVariableRangeTypeByName( variableRangeTypeList, DB_VAR_RANGE_TYPE_POINT )  );

                String invalidValue = xmlr.getAttributeValue(null, "VALUE");
                // STORE  (?)
                // TODO:
                // Figure out what to do with these.
                // Aren't the same values specified as "MISSING" in the
                // categories? What's the difference? -- otherwise this
                // is kind of redundant.

                //} else if (xmlr.getLocalName().equals("range")) {
                // ... }
            } else {
                throw new XMLStreamException(
                        "Unsupported DDI Element: codeBook/dataDscr/var/invalrng/" + xmlr.getLocalName());
            }// w  w w.  j  ava  2 s  .  c  o m
        } else if (event == XMLStreamConstants.END_ELEMENT) {
            if (xmlr.getLocalName().equals("invalrng")) {
                return;
            } else if (xmlr.getLocalName().equals("item")) {
                // continue;
            } else {
                throw new XMLStreamException(
                        "Mismatched DDI Formatting: </invalrng> expected, found " + xmlr.getLocalName());
            }
        }
    }
}

From source file:de.uzk.hki.da.model.ObjectPremisXmlWriter.java

/**
 * Integrate jhove data./*from   www  .jav a  2  s  .c o  m*/
 *
 * @param jhoveFilePath the jhove file path
 * @param tab the tab
 * @throws XMLStreamException the xML stream exception
 * @author Thomas Kleinke
 * @throws FileNotFoundException 
 */
private void integrateJhoveData(String jhoveFilePath, int tab)
        throws XMLStreamException, FileNotFoundException {
    File jhoveFile = new File(jhoveFilePath);
    if (!jhoveFile.exists())
        throw new FileNotFoundException("file does not exist. " + jhoveFile);

    FileInputStream inputStream = null;

    inputStream = new FileInputStream(jhoveFile);

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader streamReader = inputFactory.createXMLStreamReader(inputStream);

    boolean textElement = false;

    while (streamReader.hasNext()) {
        int event = streamReader.next();

        switch (event) {

        case XMLStreamConstants.START_ELEMENT:
            writer.writeDTD("\n");
            indent(tab);
            tab++;

            String prefix = streamReader.getPrefix();

            if (prefix != null && !prefix.equals("")) {
                writer.setPrefix(prefix, streamReader.getNamespaceURI());
                writer.writeStartElement(streamReader.getNamespaceURI(), streamReader.getLocalName());
            } else
                writer.writeStartElement(streamReader.getLocalName());

            for (int i = 0; i < streamReader.getNamespaceCount(); i++)
                writer.writeNamespace(streamReader.getNamespacePrefix(i), streamReader.getNamespaceURI(i));

            for (int i = 0; i < streamReader.getAttributeCount(); i++) {
                QName qname = streamReader.getAttributeName(i);
                String attributeName = qname.getLocalPart();
                String attributePrefix = qname.getPrefix();
                if (attributePrefix != null && !attributePrefix.equals(""))
                    attributeName = attributePrefix + ":" + attributeName;

                writer.writeAttribute(attributeName, streamReader.getAttributeValue(i));
            }

            break;

        case XMLStreamConstants.CHARACTERS:
            if (!streamReader.isWhiteSpace()) {
                writer.writeCharacters(streamReader.getText());
                textElement = true;
            }
            break;

        case XMLStreamConstants.END_ELEMENT:
            tab--;

            if (!textElement) {
                writer.writeDTD("\n");
                indent(tab);
            }

            writer.writeEndElement();
            textElement = false;
            break;

        default:
            break;
        }
    }

    streamReader.close();
    try {
        inputStream.close();
    } catch (IOException e) {
        throw new RuntimeException("Failed to close input stream", e);
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

@Override
public InputStream selectEntity(final InputStream entity, final String[] propertyNames) throws Exception {
    final XMLEventReader reader = getEventReader(entity);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

    final List<String> found = new ArrayList<String>(Arrays.asList(propertyNames));

    boolean inProperties = false;
    boolean writeCurrent = true;
    Boolean writeNext = null;//from www  .  j av a  2s  .  c  o  m
    String currentName = null;

    final List<String> fieldToBeSaved = new ArrayList<String>(Arrays.asList(propertyNames));

    while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();
        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && LINK.equals(event.asStartElement().getName().getLocalPart())
                && !fieldToBeSaved
                        .contains(event.asStartElement().getAttributeByName(new QName("title")).getValue())
                && !"edit".equals(event.asStartElement().getAttributeByName(new QName("rel")).getValue())) {
            writeCurrent = false;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && LINK.equals(event.asEndElement().getName().getLocalPart())) {
            writeNext = true;
        } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && (PROPERTIES).equals(event.asStartElement().getName().getLocalPart())) {
            writeCurrent = true;
            writeNext = false;
            inProperties = true;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && (PROPERTIES).equals(event.asEndElement().getName().getLocalPart())) {
            writeCurrent = true;
        } else if (inProperties) {
            if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
                final String elementName = event.asStartElement().getName().getLocalPart();

                for (String propertyName : propertyNames) {
                    if ((ATOM_PROPERTY_PREFIX + propertyName.trim()).equals(elementName)) {
                        writeCurrent = true;
                        found.remove(propertyName);
                        currentName = propertyName;
                    }
                }

            } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                    && StringUtils.isNotBlank(currentName) && (ATOM_PROPERTY_PREFIX + currentName.trim())
                            .equals(event.asEndElement().getName().getLocalPart())) {
                writeNext = false;
                currentName = null;
            }

        }

        if (writeCurrent) {
            writer.add(event);
        }

        if (writeNext != null) {
            writeCurrent = writeNext;
            writeNext = null;
        }
    }

    writer.flush();
    writer.close();
    reader.close();
    IOUtils.closeQuietly(entity);

    // Do not raise any exception in order to support FC properties as well
    // if (!found.isEmpty()) {
    //     throw new Exception(String.format("Could not find a properties '%s'", found));
    // }

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:sdmx.net.service.nomis.NOMISRESTServiceRegistry.java

public static List<NOMISGeography> parseGeography(InputStream in, String cubeId, String cubeName)
        throws XMLStreamException {
    List<NOMISGeography> geogList = new ArrayList<NOMISGeography>();
    String tagContent = null;//from   www  .  j  a v a 2 s  .  c o m
    XMLInputFactory factory = XMLInputFactory.newInstance();

    XMLStreamReader reader = factory.createXMLStreamReader(in);
    int state = 0;
    String lastLang = null;
    while (reader.hasNext()) {
        int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            if (reader.getLocalName().equals("Type")) {
                NOMISGeography geog = new NOMISGeography();
                geog.setCubeId(cubeId);
                geog.setCubeName(cubeName);
                geog.setGeography(reader.getAttributeValue("", "value"));
                geog.setGeographyName(reader.getAttributeValue("", "name"));
                geogList.add(geog);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            break;
        }
    }
    return geogList;
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.ddi.DDIFileReader.java

private void processCatgry(XMLStreamReader xmlr, Map<String, String> valueLabelPairs,
        List<String> missingValues, String variableName) throws XMLStreamException {

    boolean isMissing = "Y".equals(xmlr.getAttributeValue(null, "missing"));
    // (default is N, so null sets missing to false)

    // STORE -- (TODO NOW)
    //cat.setDataVariable(dv);
    //dv.getCategories().add(cat);
    String varValue = null;/*from w w  w. j  a  v  a 2  s  .  c  o  m*/
    String valueLabel = null;

    for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (xmlr.getLocalName().equals("labl")) {
                valueLabel = processLabl(xmlr, LEVEL_CATEGORY);
            } else if (xmlr.getLocalName().equals("catValu")) {
                varValue = parseText(xmlr, false);
            } else if (xmlr.getLocalName().equals("catStat")) {
                // category statistics should not be present in the
                // TAB file + DDI card ingest:
                throw new XMLStreamException(
                        "catStat (Category Statistics) section found in a variable section; not supported!");
            }
        } else if (event == XMLStreamConstants.END_ELEMENT) {
            if (xmlr.getLocalName().equals("catgry")) {

                if (varValue != null && !varValue.equals("")) {
                    if (valueLabel != null && !valueLabel.equals("")) {
                        dbgLog.fine("DDI Reader: storing label " + valueLabel + " for value " + varValue);
                        valueLabelPairs.put(varValue, valueLabel);
                    }
                    if (isMissing) {
                        missingValues.add(varValue);
                    }
                }

                return;
            } else if (xmlr.getLocalName().equals("catValu")) {
                // continue;
            } else if (xmlr.getLocalName().equals("labl")) {
                // continue;
            } else {
                throw new XMLStreamException(
                        "Mismatched DDI Formatting: </catgry> expected, found " + xmlr.getLocalName());
            }
        }
    }
}