Example usage for javax.xml.stream XMLStreamReader getName

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

Introduction

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

Prototype

public QName getName();

Source Link

Document

Returns a QName for the current START_ELEMENT or END_ELEMENT event

Usage

From source file:com.evolveum.midpoint.common.validator.Validator.java

public void validate(InputStream inputStream, OperationResult validatorResult,
        String objectResultOperationName) {

    XMLStreamReader stream = null;
    try {//  ww  w .j a va  2 s  . com

        Map<String, String> rootNamespaceDeclarations = new HashMap<String, String>();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        stream = xmlInputFactory.createXMLStreamReader(inputStream);

        int eventType = stream.nextTag();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (!stream.getName().equals(SchemaConstants.C_OBJECTS)) {
                // This has to be an import file with a single objects. Try
                // to process it.
                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);

                EventResult cont = null;
                try {
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations,
                            validatorResult);
                } catch (RuntimeException e) {
                    // Make sure that unexpected error is recorded.
                    objectResult.recordFatalError(e);
                    throw e;
                }

                if (!cont.isCont()) {
                    String message = null;
                    if (cont.getReason() != null) {
                        message = cont.getReason();
                    } else {
                        message = "Object validation failed (no reason given)";
                    }
                    if (objectResult.isUnknown()) {
                        objectResult.recordFatalError(message);
                    }
                    validatorResult.recordFatalError(message);
                    return;
                }
                // return to avoid processing objects in loop
                validatorResult.computeStatus("Validation failed", "Validation warnings");
                return;
            }
            // Extract root namespace declarations
            for (int i = 0; i < stream.getNamespaceCount(); i++) {
                rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i));
            }
        } else {
            throw new SystemException("StAX Malfunction?");
        }

        while (stream.hasNext()) {
            eventType = stream.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {

                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);

                EventResult cont = null;
                try {
                    // Read and validate individual object from the stream
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations,
                            validatorResult);
                } catch (RuntimeException e) {
                    if (objectResult.isUnknown()) {
                        // Make sure that unexpected error is recorded.
                        objectResult.recordFatalError(e);
                    }
                    throw e;
                }

                if (objectResult.isError()) {
                    errors++;
                }

                objectResult.cleanupResult();
                validatorResult.summarize();

                if (cont.isStop()) {
                    if (cont.getReason() != null) {
                        validatorResult.recordFatalError("Processing has been stopped: " + cont.getReason());
                    } else {
                        validatorResult.recordFatalError("Processing has been stopped");
                    }
                    // This means total stop, no other objects will be
                    // processed
                    return;
                }
                if (!cont.isCont()) {
                    if (stopAfterErrors > 0 && errors >= stopAfterErrors) {
                        validatorResult.recordFatalError("Too many errors (" + errors + ")");
                        return;
                    }
                }
            }
        }

    } catch (XMLStreamException ex) {
        // validatorResult.recordFatalError("XML parsing error: " +
        // ex.getMessage()+" on line "+stream.getLocation().getLineNumber(),ex);
        validatorResult.recordFatalError("XML parsing error: " + ex.getMessage(), ex);
        if (handler != null) {
            handler.handleGlobalError(validatorResult);
        }
        return;
    }

    // Error count is sufficient. Detailed messages are in subresults
    validatorResult.computeStatus(errors + " errors, " + (progress - errors) + " passed");

}

From source file:com.microsoft.alm.plugin.context.soap.CatalogServiceImpl.java

private void readResponse(final HttpResponse httpResponse, final ElementDeserializable readFromElement) {

    InputStream responseStream = null;
    try {/*from   w w  w. j a v  a 2 s  . c  o m*/

        final Header encoding = httpResponse.getFirstHeader("Content-Encoding"); //$NON-NLS-1$
        if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) //$NON-NLS-1$
        {
            responseStream = new GZIPInputStream(httpResponse.getEntity().getContent());
        } else {
            responseStream = httpResponse.getEntity().getContent();
        }
        XMLStreamReader reader = null;
        try {

            reader = XML_INPUT_FACTORY.createXMLStreamReader(responseStream);

            final QName envelopeQName = new QName(SOAP, "Envelope", "soap"); //$NON-NLS-1$ //$NON-NLS-2$
            final QName headerQName = new QName(SOAP, "Header", "soap"); //$NON-NLS-1$ //$NON-NLS-2$
            final QName bodyQName = new QName(SOAP, "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.
                        readUntilElementEnd(reader);
                    } else if (reader.getName().equals(bodyQName)) {
                        if (reader.nextTag() == XMLStreamConstants.START_ELEMENT
                                && reader.getName().getLocalPart().equals(QUERY_NODE_RESPONSE)) {
                            readFromElement.readFromElement(reader);
                            return;
                        }
                    }
                }
            }
        } catch (final XMLStreamException e) {
            logger.warn("readResponse", e);
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (final XMLStreamException e) {
                    // Ignore and continue
                }
            }
        }
    } catch (IOException e) {
        logger.warn("readResponse", e);
        throw new RuntimeException(e);
    } finally {
        if (responseStream != null) {
            try {
                responseStream.close();
            } catch (IOException e) {
                // Ignore and continue
            }
        }
    }
}

From source file:com.cedarsoft.serialization.test.performance.XmlParserPerformance.java

private void benchParse(XMLInputFactory inputFactory, @Nonnull String contentSample) throws XMLStreamException {
    for (int i = 0; i < BIG; i++) {
        XMLStreamReader parser = inputFactory.createXMLStreamReader(new StringReader(contentSample));

        assertEquals(XMLStreamReader.START_ELEMENT, parser.nextTag());
        assertEquals("fileType", parser.getLocalName());
        assertEquals("fileType", parser.getName().getLocalPart());

        boolean dependent = Boolean.parseBoolean(parser.getAttributeValue(null, "dependent"));

        assertEquals(XMLStreamReader.START_ELEMENT, parser.nextTag());
        assertEquals("id", parser.getName().getLocalPart());
        assertEquals(XMLStreamReader.CHARACTERS, parser.next());

        String id = parser.getText();

        assertEquals(XMLStreamReader.END_ELEMENT, parser.nextTag());

        assertEquals(XMLStreamReader.START_ELEMENT, parser.nextTag());
        assertEquals("extension", parser.getName().getLocalPart());

        boolean isDefault = Boolean.parseBoolean(parser.getAttributeValue(null, "default"));
        String delimiter = parser.getAttributeValue(null, "delimiter");

        assertEquals(XMLStreamReader.CHARACTERS, parser.next());

        String extension = parser.getText();
        assertEquals(XMLStreamReader.END_ELEMENT, parser.nextTag());
        assertEquals("extension", parser.getName().getLocalPart());

        assertEquals(XMLStreamReader.END_ELEMENT, parser.nextTag());
        assertEquals("fileType", parser.getName().getLocalPart());
        assertEquals(XMLStreamReader.END_DOCUMENT, parser.next());

        parser.close();/*from w ww. jav  a 2 s.  c  o m*/

        FileType type = new FileType(id, new Extension(delimiter, extension, isDefault), dependent);
        assertNotNull(type);
    }
}

From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Reads the properties of an entity from the stream into a map of property names to
 * typed values. Reads the entity data as an AtomPub Entry Resource from the specified {@link XMLStreamReader} into
 * a map of <code>String</code> property names to {@link EntityProperty} data typed values.
 * //from w w  w . ja  va  2s.co  m
 * @param xmlr
 *            The <code>XMLStreamReader</code> to read the data from.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @return
 *         A <code>java.util.HashMap</code> containing a map of <code>String</code> property names to
 *         {@link EntityProperty} data typed values found in the entity data.
 * @throws XMLStreamException
 *             if an error occurs accessing the stream.
 * @throws ParseException
 *             if an error occurs converting the input to a particular data type.
 */
protected static HashMap<String, EntityProperty> readProperties(final XMLStreamReader xmlr,
        final OperationContext opContext) throws XMLStreamException, ParseException {
    int eventType = xmlr.getEventType();
    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.PROPERTIES);
    final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>();

    while (xmlr.hasNext()) {
        eventType = xmlr.next();
        if (eventType == XMLStreamConstants.CHARACTERS) {
            xmlr.getText();
            continue;
        }

        if (eventType == XMLStreamConstants.START_ELEMENT
                && xmlr.getNamespaceURI().equals(ODataConstants.DATA_SERVICES_NS)) {
            final String key = xmlr.getLocalName();
            String val = Constants.EMPTY_STRING;
            String edmType = null;

            if (xmlr.getAttributeCount() > 0) {
                edmType = xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE);
            }

            // move to chars
            eventType = xmlr.next();

            if (eventType == XMLStreamConstants.CHARACTERS) {
                val = xmlr.getText();

                // end element
                eventType = xmlr.next();
            }

            xmlr.require(XMLStreamConstants.END_ELEMENT, null, key);

            final EntityProperty newProp = new EntityProperty(val, EdmType.parse(edmType));
            properties.put(key, newProp);
        } else if (eventType == XMLStreamConstants.END_ELEMENT && xmlr.getName().toString()
                .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) {
            // End read properties
            break;
        }
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.PROPERTIES);
    return properties;
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the
 * specified stream in AtomPub format into a {@link TableResult} containing an entity of the specified class type
 * projected using the specified resolver.
 * /*ww  w . j  a  va 2s .c  om*/
 * @param xmlr
 *            An <code>XMLStreamReader</code> on the input stream.
 * @param clazzType
 *            The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to
 *            <code>null</code> to ignore the returned entity and copy only response properties into the
 *            {@link TableResult} object.
 * @param resolver
 *            An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set
 *            to <code>null</code> to return the entity as an instance of the class type <code>T</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         A {@link TableResult} containing the parsed entity result of the operation.
 * 
 * @throws XMLStreamException
 *             if an error occurs while accessing the stream.
 * @throws ParseException
 *             if an error occurs while parsing the stream.
 * @throws InstantiationException
 *             if an error occurs while constructing the result.
 * @throws IllegalAccessException
 *             if an error occurs in reflection while parsing the result.
 * @throws StorageException
 *             if a storage service error occurs.
 */
private static <T extends TableEntity, R> TableResult parseAtomEntity(final XMLStreamReader xmlr,
        final Class<T> clazzType, final EntityResolver<R> resolver, final OperationContext opContext)
        throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException,
        StorageException {
    int eventType = xmlr.getEventType();
    final TableResult res = new TableResult();

    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.ENTRY);

    String etag = StringEscapeUtils.unescapeHtml4(
            xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.ETAG));

    res.setEtag(etag);

    while (xmlr.hasNext()) {
        eventType = xmlr.next();
        if (eventType == XMLStreamConstants.CHARACTERS) {
            xmlr.getText();
            continue;
        }

        final String name = xmlr.getName().toString();

        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.ID)) {
                Utility.readElementFromXMLReader(xmlr, ODataConstants.ID);
            } else if (name
                    .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) {
                // Do read properties
                if (resolver == null && clazzType == null) {
                    return res;
                } else {
                    res.setProperties(readAtomProperties(xmlr, opContext));
                    break;
                }
            }
        }
    }

    // Move to end Content
    eventType = xmlr.next();
    if (eventType == XMLStreamConstants.CHARACTERS) {
        eventType = xmlr.next();
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.CONTENT);

    eventType = xmlr.next();
    if (eventType == XMLStreamConstants.CHARACTERS) {
        eventType = xmlr.next();
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.ENTRY);

    String rowKey = null;
    String partitionKey = null;
    Date timestamp = null;

    // Remove core properties from map and set individually
    EntityProperty tempProp = res.getProperties().remove(TableConstants.PARTITION_KEY);
    if (tempProp != null) {
        partitionKey = tempProp.getValueAsString();
    }

    tempProp = res.getProperties().remove(TableConstants.ROW_KEY);
    if (tempProp != null) {
        rowKey = tempProp.getValueAsString();
    }

    tempProp = res.getProperties().remove(TableConstants.TIMESTAMP);
    if (tempProp != null) {
        timestamp = tempProp.getValueAsDate();
    }

    if (resolver != null) {
        // Call resolver
        res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag()));
    } else if (clazzType != null) {
        // Generate new entity and return
        final T entity = clazzType.newInstance();
        entity.setEtag(res.getEtag());

        entity.setPartitionKey(partitionKey);
        entity.setRowKey(rowKey);
        entity.setTimestamp(timestamp);

        entity.readEntity(res.getProperties(), opContext);

        res.setResult(entity);
    }

    return res;
}

From source file:com.evolveum.midpoint.prism.lex.dom.DomLexicalProcessor.java

@Override
public void readObjectsIteratively(@NotNull ParserSource source, @NotNull ParsingContext parsingContext,
        RootXNodeHandler handler) throws SchemaException, IOException {
    InputStream is = source.getInputStream();
    XMLStreamReader stream = null;
    try {/* w  w  w.  j  av  a  2s  .c  om*/
        stream = XMLInputFactory.newInstance().createXMLStreamReader(is);

        int eventType = stream.nextTag();
        if (eventType != XMLStreamConstants.START_ELEMENT) {
            throw new SystemException("StAX Malfunction?");
        }
        DOMConverter domConverter = new DOMConverter();
        Map<String, String> rootNamespaceDeclarations = new HashMap<>();

        QName objectsMarker = schemaRegistry.getPrismContext().getObjectsElementName();
        if (objectsMarker != null && !QNameUtil.match(stream.getName(), objectsMarker)) {
            readSingleObjectIteratively(stream, rootNamespaceDeclarations, domConverter, handler);
        }
        for (int i = 0; i < stream.getNamespaceCount(); i++) {
            rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i));
        }
        while (stream.hasNext()) {
            eventType = stream.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (!readSingleObjectIteratively(stream, rootNamespaceDeclarations, domConverter, handler)) {
                    return;
                }
            }
        }
    } catch (XMLStreamException ex) {
        String lineInfo = stream != null ? " on line " + stream.getLocation().getLineNumber() : "";
        throw new SchemaException("Exception while parsing XML" + lineInfo + ": " + ex.getMessage(), ex);
    } finally {
        if (source.closeStreamAfterParsing()) {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Reads the properties of an entity from the stream into a map of property names to
 * typed values. Reads the entity data as an AtomPub Entry Resource from the specified {@link XMLStreamReader} into
 * a map of <code>String</code> property names to {@link EntityProperty} data typed values.
 * /*from ww w. j  ava  2  s. com*/
 * @param xmlr
 *            The <code>XMLStreamReader</code> to read the data from.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @return
 *         A <code>java.util.HashMap</code> containing a map of <code>String</code> property names to
 *         {@link EntityProperty} data typed values found in the entity data.
 * @throws XMLStreamException
 *             if an error occurs accessing the stream.
 * @throws ParseException
 *             if an error occurs converting the input to a particular data type.
 */
private static HashMap<String, EntityProperty> readAtomProperties(final XMLStreamReader xmlr,
        final OperationContext opContext) throws XMLStreamException, ParseException {
    int eventType = xmlr.getEventType();
    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.PROPERTIES);
    final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>();

    while (xmlr.hasNext()) {
        eventType = xmlr.next();
        if (eventType == XMLStreamConstants.CHARACTERS) {
            xmlr.getText();
            continue;
        }

        if (eventType == XMLStreamConstants.START_ELEMENT
                && xmlr.getNamespaceURI().equals(ODataConstants.DATA_SERVICES_NS)) {
            final String key = xmlr.getLocalName();
            String val = Constants.EMPTY_STRING;
            String edmType = null;

            if (xmlr.getAttributeCount() > 0) {
                edmType = xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE);
            }

            // move to chars
            eventType = xmlr.next();

            if (eventType == XMLStreamConstants.CHARACTERS) {
                val = xmlr.getText();

                // end element
                eventType = xmlr.next();
            }

            xmlr.require(XMLStreamConstants.END_ELEMENT, null, key);

            final EntityProperty newProp = new EntityProperty(val, EdmType.parse(edmType));
            properties.put(key, newProp);
        } else if (eventType == XMLStreamConstants.END_ELEMENT && xmlr.getName().toString()
                .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) {
            // End read properties
            break;
        }
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.PROPERTIES);
    return properties;
}

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 {//  w w  w  .  j  a va  2  s.co 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:net.sourceforge.subsonic.service.ITunesParser.java

private String readKey(XMLStreamReader streamReader) {
    try {//  w ww.j av  a2 s.  c o  m
        if (streamReader.getEventType() == XMLStreamConstants.START_ELEMENT
                && "key".equals(streamReader.getName().getLocalPart())) {
            return streamReader.getElementText();
        }
    } catch (XMLStreamException e) {
        // TODO
        System.out.println(streamReader.getName().getLocalPart() + " " + e);
    }
    return null;
}

From source file:net.xy.jcms.controller.configurations.parser.TranslationParser.java

/**
 * parses an xml configuration from an input streams. throwes
 * IllegalArgumentExceptions in case of syntax error.
 * //  w w w . ja  v a  2s.  co m
 * @param in
 * @return value
 * @throws XMLStreamException
 * @throws ClassNotFoundException
 *             in case there are problems with an params type converter
 */
public static TranslationRule[] parse(final InputStream in, final ClassLoader loader)
        throws XMLStreamException, ClassNotFoundException {
    @SuppressWarnings("deprecation")
    final XMLInputFactory factory = XMLInputFactory.newInstance(
            "com.sun.xml.internal.stream.XMLInputFactoryImpl", TranslationParser.class.getClassLoader());
    LOG.info("XMLInputFactory loaded: " + factory.getClass().getName());
    factory.setProperty("javax.xml.stream.isCoalescing", true);
    // not supported be the reference implementation
    // factory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.TRUE);
    final XMLStreamReader parser = factory.createXMLStreamReader(in);
    while (parser.hasNext()) {
        final int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT && parser.getName().getLocalPart().equals("rules")) {
            return parseRules(parser, loader);
        }
    }
    throw new IllegalArgumentException("No rules section found.");
}