Example usage for javax.xml.stream XMLStreamReader nextTag

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

Introduction

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

Prototype

public int nextTag() throws XMLStreamException;

Source Link

Document

Skips any white space (isWhiteSpace() returns true), COMMENT, or PROCESSING_INSTRUCTION, until a START_ELEMENT or END_ELEMENT is reached.

Usage

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

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

    InputStream responseStream = null;
    try {//  w w  w .ja va  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(javolution.xml.stream.XMLInputFactory inputFactory)
        throws XMLStreamException, javolution.xml.stream.XMLStreamException {
    for (int i = 0; i < BIG; i++) {
        javolution.xml.stream.XMLStreamReader parser = inputFactory
                .createXMLStreamReader(new StringReader(CONTENT_SAMPLE));

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

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

        assertEquals(XMLStreamReader.START_ELEMENT, parser.nextTag());
        assertEquals("id", parser.getLocalName().toString());
        assertEquals(XMLStreamReader.CHARACTERS, parser.next());

        String id = parser.getText().toString();

        assertEquals(XMLStreamReader.END_ELEMENT, parser.nextTag());
        assertEquals("id", parser.getLocalName().toString());

        assertEquals(XMLStreamReader.START_ELEMENT, parser.nextTag());
        assertEquals("extension", parser.getLocalName().toString());

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

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

        String extension = parser.getText().toString();

        assertEquals(XMLStreamReader.END_ELEMENT, parser.nextTag());
        assertEquals("extension", parser.getLocalName().toString());

        assertEquals(XMLStreamReader.END_ELEMENT, parser.nextTag());
        assertEquals("fileType", parser.getLocalName().toString());
        assertEquals(XMLStreamReader.END_DOCUMENT, parser.next());

        parser.close();// w  w w.  j ava  2s. c  o  m

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

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

private void processDDI(BufferedInputStream ddiStream, SDIOMetadata smd) throws IOException {
    XMLStreamReader xmlr = null;
    try {// w w  w. j a  v  a2  s  . com
        xmlr = xmlInputFactory.createXMLStreamReader(ddiStream);
        //processDDI( xmlr, smd );
        xmlr.nextTag();
        xmlr.require(XMLStreamConstants.START_ELEMENT, null, "codeBook");
        processCodeBook(xmlr, smd);
        dbgLog.info("processed DDI.");

    } catch (XMLStreamException ex) {
        Logger.getLogger("global").log(Level.SEVERE, null, ex);
        throw new IOException(ex.getMessage());
    } finally {
        try {
            if (xmlr != null) {
                xmlr.close();
            }
        } catch (XMLStreamException ex) {
            // The message in the exception should contain diagnostics
            // information -- what was wrong with the DDI, etc.
            throw new IOException(ex.getMessage());
        }
        if (ddiStream != null) {
            ddiStream.close();
        }
    }

    // Having processed the entire ddi, we should have obtained all the metadata
    // describing the data set.
    // Configure the SMD metadata object:

    if (getVarQnty() > 0) {
        smd.getFileInformation().put("varQnty", getVarQnty());
        dbgLog.info("var quantity: " + getVarQnty());
        // TODO:
        // Validate the value against the actual number of variable sections
        // found in the DDI.
    } else {
        throw new IOException("Failed to obtain the variable quantity from the DDI supplied.");
    }

    if (getCaseQnty() > 0) {
        smd.getFileInformation().put("caseQnty", getCaseQnty());
    }
    // It's ok if caseQnty was not defined in the DDI, we'll try to read
    // the tab file supplied and assume that the number of lines is the
    // number of observations.

    smd.setVariableName(variableNameList.toArray(new String[variableNameList.size()]));

    // "minimal" variable types: SPSS type binary definition:
    // 0 means numeric, >0 means string.

    smd.setVariableTypeMinimal(
            ArrayUtils.toPrimitive(variableTypeList.toArray(new Integer[variableTypeList.size()])));

    // This is how the "discrete" and "continuous" numeric values are
    // distinguished in the data set metadata:

    smd.setDecimalVariables(decimalVariableSet);

    //TODO: smd.getFileInformation().put("caseWeightVariableName", caseWeightVariableName);

    smd.setVariableFormat(printFormatList);
    smd.setVariableFormatName(printFormatNameTable);
    smd.setVariableFormatCategory(formatCategoryTable); //TODO: verify

    // Store the variable labels, if supplied:

    if (!variableLabelMap.isEmpty()) {
        smd.setVariableLabel(variableLabelMap);
    }

    // Value labels, if supplied:

    if (!valueLabelTable.isEmpty()) {
        smd.setValueLabelTable(valueLabelTable);
        smd.setValueLabelMappingTable(valueVariableMappingTable);
    }

    // And missing values:

    if (!missingValueTable.isEmpty()) {
        smd.setMissingValueTable(missingValueTable);
    }

}

From source file:com.liferay.portal.util.LocalizationImpl.java

private String _getRootAttribute(String xml, String name, String defaultValue) {

    String value = null;/*from   w w  w  .  ja v  a  2  s .  com*/

    XMLStreamReader xmlStreamReader = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            value = xmlStreamReader.getAttributeValue(null, name);
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

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

    if (Validator.isNull(value)) {
        value = defaultValue;
    }

    return value;
}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String getLocalization(String xml, String requestedLanguageId, boolean useDefault) {

    String value = _getCachedValue(xml, requestedLanguageId, useDefault);

    if (value != null) {
        return value;
    } else {/*  w w  w.  j a v  a2  s .  com*/
        value = StringPool.BLANK;
    }

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    String priorityLanguageId = null;

    Locale requestedLocale = LocaleUtil.fromLanguageId(requestedLanguageId);

    if (useDefault && LanguageUtil.isDuplicateLanguageCode(requestedLocale.getLanguage())) {

        Locale priorityLocale = LanguageUtil.getLocale(requestedLocale.getLanguage());

        if (!requestedLanguageId.equals(priorityLanguageId)) {
            priorityLanguageId = LocaleUtil.toLanguageId(priorityLocale);
        }
    }

    if (!Validator.isXml(xml)) {
        if (useDefault || requestedLanguageId.equals(systemDefaultLanguageId)) {

            value = xml;
        }

        _setCachedValue(xml, requestedLanguageId, useDefault, value);

        return value;
    }

    XMLStreamReader xmlStreamReader = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String defaultLanguageId = StringPool.BLANK;

        // Skip root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        // Find specified language and/or default language

        String defaultValue = StringPool.BLANK;
        String priorityValue = StringPool.BLANK;

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

            if (event == XMLStreamConstants.START_ELEMENT) {
                String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID);

                if (Validator.isNull(languageId)) {
                    languageId = defaultLanguageId;
                }

                if (languageId.equals(defaultLanguageId) || languageId.equals(priorityLanguageId)
                        || languageId.equals(requestedLanguageId)) {

                    String text = xmlStreamReader.getElementText();

                    if (languageId.equals(defaultLanguageId)) {
                        defaultValue = text;
                    }

                    if (languageId.equals(priorityLanguageId)) {
                        priorityValue = text;
                    }

                    if (languageId.equals(requestedLanguageId)) {
                        value = text;
                    }

                    if (Validator.isNotNull(value)) {
                        break;
                    }
                }
            } else if (event == XMLStreamConstants.END_DOCUMENT) {
                break;
            }
        }

        if (useDefault && Validator.isNotNull(priorityLanguageId) && Validator.isNull(value)
                && Validator.isNotNull(priorityValue)) {

            value = priorityValue;
        }

        if (useDefault && Validator.isNull(value)) {
            value = defaultValue;
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

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

    _setCachedValue(xml, requestedLanguageId, useDefault, value);

    return value;
}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String updateLocalization(String xml, String key, String value, String requestedLanguageId,
        String defaultLanguageId, boolean cdata, boolean localized) {

    xml = _sanitizeXML(xml);/*from  www  .  j  ava  2s.c  o  m*/

    XMLStreamReader xmlStreamReader = null;
    XMLStreamWriter xmlStreamWriter = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String availableLocales = StringPool.BLANK;

        // Read root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            availableLocales = xmlStreamReader.getAttributeValue(null, _AVAILABLE_LOCALES);

            if (Validator.isNull(availableLocales)) {
                availableLocales = defaultLanguageId;
            }

            if (availableLocales.indexOf(requestedLanguageId) == -1) {
                availableLocales = StringUtil.add(availableLocales, requestedLanguageId, StringPool.COMMA);
            }
        }

        UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();

        xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(unsyncStringWriter);

        xmlStreamWriter.writeStartDocument();
        xmlStreamWriter.writeStartElement(_ROOT);

        if (localized) {
            xmlStreamWriter.writeAttribute(_AVAILABLE_LOCALES, availableLocales);
            xmlStreamWriter.writeAttribute(_DEFAULT_LOCALE, defaultLanguageId);
        }

        _copyNonExempt(xmlStreamReader, xmlStreamWriter, requestedLanguageId, defaultLanguageId, cdata);

        xmlStreamWriter.writeStartElement(key);

        if (localized) {
            xmlStreamWriter.writeAttribute(_LANGUAGE_ID, requestedLanguageId);
        }

        if (cdata) {
            xmlStreamWriter.writeCData(value);
        } else {
            xmlStreamWriter.writeCharacters(value);
        }

        xmlStreamWriter.writeEndElement();
        xmlStreamWriter.writeEndElement();
        xmlStreamWriter.writeEndDocument();

        xmlStreamWriter.close();
        xmlStreamWriter = null;

        xml = unsyncStringWriter.toString();
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

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

        if (xmlStreamWriter != null) {
            try {
                xmlStreamWriter.close();
            } catch (Exception e) {
            }
        }
    }

    return xml;
}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String removeLocalization(String xml, String key, String requestedLanguageId, boolean cdata,
        boolean localized) {

    if (Validator.isNull(xml)) {
        return StringPool.BLANK;
    }//from  www  .j av  a  2s. co  m

    xml = _sanitizeXML(xml);

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    XMLStreamReader xmlStreamReader = null;
    XMLStreamWriter xmlStreamWriter = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String availableLocales = StringPool.BLANK;
        String defaultLanguageId = StringPool.BLANK;

        // Read root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            availableLocales = xmlStreamReader.getAttributeValue(null, _AVAILABLE_LOCALES);
            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        if ((availableLocales != null) && (availableLocales.indexOf(requestedLanguageId) != -1)) {

            availableLocales = StringUtil.remove(availableLocales, requestedLanguageId, StringPool.COMMA);

            UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

            XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();

            xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(unsyncStringWriter);

            xmlStreamWriter.writeStartDocument();
            xmlStreamWriter.writeStartElement(_ROOT);

            if (localized) {
                xmlStreamWriter.writeAttribute(_AVAILABLE_LOCALES, availableLocales);
                xmlStreamWriter.writeAttribute(_DEFAULT_LOCALE, defaultLanguageId);
            }

            _copyNonExempt(xmlStreamReader, xmlStreamWriter, requestedLanguageId, defaultLanguageId, cdata);

            xmlStreamWriter.writeEndElement();
            xmlStreamWriter.writeEndDocument();

            xmlStreamWriter.close();
            xmlStreamWriter = null;

            xml = unsyncStringWriter.toString();
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

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

        if (xmlStreamWriter != null) {
            try {
                xmlStreamWriter.close();
            } catch (Exception e) {
            }
        }
    }

    return xml;
}

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  v a2s.  c  om
        /*
         * 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:edu.indiana.d2i.htrc.portal.HTRCPersistenceAPIClient.java

private AlgorithmDetailsBean parseAlgorithmDetailBean(InputStream stream) throws XMLStreamException {
    AlgorithmDetailsBean res = new AlgorithmDetailsBean();
    XMLStreamReader parser = factory.createXMLStreamReader(stream);

    List<AlgorithmDetailsBean.Parameter> parameters = new ArrayList<AlgorithmDetailsBean.Parameter>();
    List<String> authors = new ArrayList<String>();
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (parser.hasName()) {
                // only parse the info tag!
                if (parser.getLocalName().equals(AlgorithmDetailsBean.NAME)) {
                    res.setName(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.VERSION)) {
                    res.setVersion(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.DESCRIPTION)) {
                    res.setDescription(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.SUPPORTURL)) {
                    res.setSupportUrl(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.PARAMETER)) {
                    AlgorithmDetailsBean.Parameter parameter = new AlgorithmDetailsBean.Parameter();
                    int count = parser.getAttributeCount();
                    for (int i = 0; i < count; i++) {
                        if (parser.getAttributeLocalName(i).equals("required"))
                            parameter.setRequired(Boolean.valueOf(parser.getAttributeValue(i)));
                        if (parser.getAttributeLocalName(i).equals("type"))
                            parameter.setType(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("name"))
                            parameter.setName(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("defaultValue"))
                            parameter.setDefaultValue(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("validation"))
                            parameter.setValidation(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("validationError"))
                            parameter.setValidationError(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("readOnly"))
                            parameter.setReadOnly(Boolean.parseBoolean(parser.getAttributeValue(i)));
                    }/*from   w w  w  . j  a  v  a2s.c  om*/
                    parser.nextTag();
                    if (parser.getLocalName().equals("label"))
                        parameter.setLabel(parser.getElementText());
                    parser.nextTag();
                    if (parser.getLocalName().equals("description"))
                        parameter.setDescription(parser.getElementText());
                    parameters.add(parameter);
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.AUTHOR)) {
                    int count = parser.getAttributeCount();
                    for (int i = 0; i < count; i++) {
                        if (parser.getAttributeLocalName(i).equals("name"))
                            authors.add(parser.getAttributeValue(i));
                    }
                }
            }
        }
    }
    res.setParameters(parameters);
    res.setAuthors(authors);
    return res;
}

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

/**
 * goes over any <rule reactOn="^du" buildOff="du" usecase="contentgroup">
 * //from   w  w  w  .  java2  s.  com
 * @param parser
 * @return value
 * @throws XMLStreamException
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
private static TranslationRule[] parseRules(final XMLStreamReader parser, final ClassLoader loader)
        throws XMLStreamException, ClassNotFoundException {
    final List<TranslationRule> rules = new LinkedList<TranslationRule>();
    while (parser.nextTag() == XMLStreamConstants.START_ELEMENT) {
        if (parser.getLocalName().equals("rule")) {
            rules.add(parseRule(parser, loader));
        } else {
            throw new IllegalArgumentException("Syntax error nothing allowed between rule sections.");
        }
    }
    return rules.toArray(new TranslationRule[rules.size()]);
}