Example usage for javax.xml.stream XMLStreamException getMessage

List of usage examples for javax.xml.stream XMLStreamException getMessage

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:microsoft.exchange.webservices.data.autodiscover.request.AutodiscoverRequest.java

/**
 * Executes this instance.//from  ww  w.ja v a2 s.c o m
 *
 * @return the autodiscover response
 * @throws Exception the exception
 */
protected AutodiscoverResponse internalExecute() throws Exception {
    this.validate();
    HttpWebRequest request = null;
    try {
        request = this.service.prepareHttpWebRequestForUrl(this.url);
        this.service.traceHttpRequestHeaders(TraceFlags.AutodiscoverRequestHttpHeaders, request);

        boolean needSignature = this.getService().getCredentials() != null
                && this.getService().getCredentials().isNeedSignature();
        boolean needTrace = this.getService().isTraceEnabledFor(TraceFlags.AutodiscoverRequest);

        OutputStream urlOutStream = request.getOutputStream();
        // OutputStreamWriter out = new OutputStreamWriter(request
        // .getOutputStream());

        ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
        EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.getService(), memoryStream);
        writer.setRequireWSSecurityUtilityNamespace(needSignature);
        this.writeSoapRequest(this.url, writer);

        if (needSignature) {
            this.service.getCredentials().sign(memoryStream);
        }

        if (needTrace) {
            memoryStream.flush();
            this.service.traceXml(TraceFlags.AutodiscoverRequest, memoryStream);
        }
        memoryStream.writeTo(urlOutStream);
        urlOutStream.flush();
        urlOutStream.close();
        memoryStream.close();
        // out.write(memoryStream.toString());
        // out.close();
        request.executeRequest();
        request.getResponseCode();
        if (AutodiscoverRequest.isRedirectionResponse(request)) {
            AutodiscoverResponse response = this.createRedirectionResponse(request);
            if (response != null) {
                return response;
            } else {
                throw new ServiceRemoteException("The service returned an invalid redirection response.");
            }
        }

        memoryStream = new ByteArrayOutputStream();
        InputStream serviceResponseStream = request.getInputStream();

        while (true) {
            int data = serviceResponseStream.read();
            if (-1 == data) {
                break;
            } else {
                memoryStream.write(data);
            }
        }
        memoryStream.flush();
        serviceResponseStream.close();

        if (this.service.isTraceEnabled()) {
            this.service.traceResponse(request, memoryStream);
        }
        ByteArrayInputStream memoryStreamIn = new ByteArrayInputStream(memoryStream.toByteArray());
        EwsXmlReader ewsXmlReader = new EwsXmlReader(memoryStreamIn);

        // WCF may not generate an XML declaration.
        ewsXmlReader.read();
        if (ewsXmlReader.getNodeType().getNodeType() == XmlNodeType.START_DOCUMENT) {
            ewsXmlReader.readStartElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName);
        } else if ((ewsXmlReader.getNodeType().getNodeType() != XmlNodeType.START_ELEMENT)
                || (!ewsXmlReader.getLocalName().equals(XmlElementNames.SOAPEnvelopeElementName))
                || (!ewsXmlReader.getNamespaceUri().equals(EwsUtilities.getNamespaceUri(XmlNamespace.Soap)))) {
            throw new ServiceXmlDeserializationException("The Autodiscover service response was invalid.");
        }

        this.readSoapHeaders(ewsXmlReader);

        AutodiscoverResponse response = this.readSoapBody(ewsXmlReader);

        ewsXmlReader.readEndElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName);

        if (response.getErrorCode() == AutodiscoverErrorCode.NoError) {
            return response;
        } else {
            throw new AutodiscoverResponseException(response.getErrorCode(), response.getErrorMessage());
        }

    } catch (XMLStreamException ex) {
        this.service.traceMessage(TraceFlags.AutodiscoverConfiguration,
                String.format("XML parsing error: %s", ex.getMessage()));

        // Wrap exception
        throw new ServiceRequestException(String.format("The request failed. %s", ex.getMessage()), ex);
    } catch (IOException ex) {
        this.service.traceMessage(TraceFlags.AutodiscoverConfiguration,
                String.format("I/O error: %s", ex.getMessage()));

        // Wrap exception
        throw new ServiceRequestException(String.format("The request failed. %s", ex.getMessage()), ex);
    } catch (Exception ex) {
        // HttpWebRequest httpWebResponse = (HttpWebRequest)ex;

        if (null != request && request.getResponseCode() == 7) {
            if (AutodiscoverRequest.isRedirectionResponse(request)) {
                this.service.processHttpResponseHeaders(TraceFlags.AutodiscoverResponseHttpHeaders, request);

                AutodiscoverResponse response = this.createRedirectionResponse(request);
                if (response != null) {
                    return response;
                }
            } else {
                this.processWebException(ex, request);
            }
        }

        // Wrap exception if the above code block didn't throw
        throw new ServiceRequestException(String.format("The request failed. %s", ex.getMessage()), ex);
    } finally {
        try {
            if (request != null) {
                request.close();
            }
        } catch (Exception e) {
            // do nothing
        }
    }
}

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;/* w w w .j a va  2s  . c  om*/
    try {
        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:davmail.exchange.ews.EWSMethod.java

protected void processResponseStream(InputStream inputStream) {
    responseItems = new ArrayList<Item>();
    XMLStreamReader reader = null;
    try {//from  w w w.j  a  va 2s  .com
        inputStream = new FilterInputStream(inputStream) {
            int totalCount;
            int lastLogCount;

            @Override
            public int read(byte[] buffer, int offset, int length) throws IOException {
                int count = super.read(buffer, offset, length);
                totalCount += count;
                if (totalCount - lastLogCount > 1024 * 128) {
                    DavGatewayTray.debug(new BundleMessage("LOG_DOWNLOAD_PROGRESS",
                            String.valueOf(totalCount / 1024), EWSMethod.this.getURI()));
                    DavGatewayTray.switchIcon();
                    lastLogCount = totalCount;
                }
                return count;
            }
        };
        reader = XMLStreamUtil.createXMLStreamReader(inputStream);
        while (reader.hasNext()) {
            reader.next();
            handleErrors(reader);
            if (serverVersion == null && XMLStreamUtil.isStartTag(reader, "ServerVersionInfo")) {
                String majorVersion = getAttributeValue(reader, "MajorVersion");
                if ("14".equals(majorVersion)) {
                    String minorVersion = getAttributeValue(reader, "MinorVersion");
                    if ("0".equals(minorVersion)) {
                        serverVersion = "Exchange2010";
                    } else {
                        serverVersion = "Exchange2010_SP1";
                    }
                } else {
                    serverVersion = "Exchange2007_SP1";
                }
            } else if (XMLStreamUtil.isStartTag(reader, "RootFolder")) {
                includesLastItemInRange = "true"
                        .equals(reader.getAttributeValue(null, "IncludesLastItemInRange"));
            } else if (XMLStreamUtil.isStartTag(reader, responseCollectionName)) {
                handleItems(reader);
            } else {
                handleCustom(reader);
            }
        }
    } catch (XMLStreamException e) {
        LOGGER.error("Error while parsing soap response: " + e, e);
        if (reader != null) {
            try {
                LOGGER.error("Current text: " + reader.getText());
            } catch (IllegalStateException ise) {
                LOGGER.error(e + " " + e.getMessage());
            }
        }
    }
    if (errorDetail != null) {
        LOGGER.debug(errorDetail);
    }
}

From source file:com.ikanow.infinit.e.harvest.extraction.document.file.FileHarvester.java

private void parse(InfiniteFile f, SourcePojo source) throws MalformedURLException, URISyntaxException {

    //NOTE: we only ever break out of here because of max docs in standalone mode
    // (because we don't know how to continue reading)

    DocumentPojo doc = null;//from  ww w .j a va 2  s. c  o  m
    //Determine File Extension
    String fileName = f.getName().toString();

    int mid = fileName.lastIndexOf(".");
    String extension = fileName.substring(mid + 1, fileName.length());

    //Checked to save processing time
    long fileTimestamp = (f.getDate() / 1000) * 1000;
    // (ensure truncated to seconds, since some operation somewhere hear does this...)

    Date modDate = new Date(fileTimestamp);
    //XML Data gets placed into MetaData

    boolean bIsXml = false;
    boolean bIsJson = false;
    boolean bIsLineOriented = false;
    if ((null != source.getFileConfig()) && (null != source.getFileConfig().type)) {
        extension = source.getFileConfig().type;
    }
    bIsXml = extension.equalsIgnoreCase("xml");
    bIsJson = extension.equalsIgnoreCase("json");
    bIsLineOriented = extension.endsWith("sv");

    if (bIsXml || bIsJson || bIsLineOriented) {
        int debugMaxDocs = Integer.MAX_VALUE; // by default don't set this, it's only for debug mode
        if (_context.isStandalone()) { // debug mode
            debugMaxDocs = maxDocsPerCycle;
        }
        //fast check to see if the file has changed before processing (or if it never existed)
        if (needsUpdated_SourceUrl(modDate, f.getUrlString(), source)) {
            if (0 != modDate.getTime()) { // if it ==0 then sourceUrl doesn't exist at all, no need to delete
                // This file already exists - in normal/managed mode will re-create
                // In streaming mode, simple skip over
                if (_streaming) {
                    return;
                } //TESTED

                DocumentPojo docRepresentingSrcUrl = new DocumentPojo();
                docRepresentingSrcUrl.setSourceUrl(f.getUrlString());
                docRepresentingSrcUrl.setSourceKey(source.getKey());
                docRepresentingSrcUrl.setCommunityId(source.getCommunityIds().iterator().next());
                sourceUrlsGettingUpdated.add(docRepresentingSrcUrl.getSourceUrl());
                this.docsToRemove.add(docRepresentingSrcUrl);
                // (can add documents with just source URL, are treated differently in the core libraries)               
            }

            SourceFileConfigPojo fileSystem = source.getFileConfig();
            if ((null == fileSystem) && (bIsXml || bIsJson)) {
                fileSystem = new SourceFileConfigPojo();
            }
            XmlToMetadataParser xmlParser = null;
            JsonToMetadataParser jsonParser = null;
            String urlType = extension;
            if (bIsXml) {
                xmlParser = new XmlToMetadataParser(fileSystem.XmlRootLevelValues, fileSystem.XmlIgnoreValues,
                        fileSystem.XmlSourceName, fileSystem.XmlPrimaryKey, fileSystem.XmlAttributePrefix,
                        fileSystem.XmlPreserveCase, debugMaxDocs);
            } //TESTED
            else if (bIsJson) {
                jsonParser = new JsonToMetadataParser(fileSystem.XmlSourceName, fileSystem.XmlRootLevelValues,
                        fileSystem.XmlPrimaryKey, fileSystem.XmlIgnoreValues, debugMaxDocs);
            } //TESTED

            List<DocumentPojo> partials = null;
            try {
                if (bIsXml) {
                    XMLStreamReader xmlStreamReader = null;
                    XMLInputFactory factory = XMLInputFactory.newInstance();
                    factory.setProperty(XMLInputFactory.IS_COALESCING, true);
                    factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
                    try {
                        xmlStreamReader = factory.createXMLStreamReader(f.getInputStream());
                        partials = xmlParser.parseDocument(xmlStreamReader);
                        long memUsage = xmlParser.getMemUsage();
                        _memUsage += memUsage;
                        _totalMemUsage.addAndGet(memUsage);
                    } finally {
                        if (null != xmlStreamReader)
                            xmlStreamReader.close();
                    }
                } //TESTED
                else if (bIsJson) {
                    JsonReader jsonReader = null;
                    try {
                        jsonReader = new JsonReader(new InputStreamReader(f.getInputStream(), "UTF-8"));
                        jsonReader.setLenient(true);
                        partials = jsonParser.parseDocument(jsonReader);
                        long memUsage = jsonParser.getMemUsage();
                        _memUsage += memUsage;
                        _totalMemUsage.addAndGet(memUsage);
                    } finally {
                        if (null != jsonReader)
                            jsonReader.close();
                    }
                } //TESTED
                else if (bIsLineOriented) { // Just generate a document for every line

                    BufferedReader lineReader = null;
                    try {
                        lineReader = new BufferedReader(new InputStreamReader(f.getInputStream(), "UTF-8"));
                        CsvToMetadataParser lineParser = new CsvToMetadataParser(debugMaxDocs);
                        partials = lineParser.parseDocument(lineReader, source);
                        long memUsage = lineParser.getMemUsage();
                        _memUsage += memUsage;
                        _totalMemUsage.addAndGet(memUsage);
                    } finally {
                        if (null != lineReader)
                            lineReader.close();
                    }
                } //TESTED

                MessageDigest md5 = null; // (generates unique urls if the user doesn't below)
                try {
                    md5 = MessageDigest.getInstance("MD5");
                } catch (NoSuchAlgorithmException e) {
                    // Do nothing, unlikely to happen...
                }
                int nIndex = 0;
                int numPartials = partials.size();
                for (DocumentPojo doctoAdd : partials) {
                    nIndex++;
                    doctoAdd.setSource(source.getTitle());
                    doctoAdd.setSourceKey(source.getKey());
                    doctoAdd.setMediaType(source.getMediaType());
                    doctoAdd.setModified(new Date(fileTimestamp));
                    doctoAdd.setCreated(new Date());

                    if (null == doctoAdd.getUrl()) { // Can be set in the parser or here
                        doctoAdd.setHasDefaultUrl(true); // (ie cannot occur in a different src URL)

                        if (1 == numPartials) {
                            String urlString = f.getUrlString();
                            if (urlString.endsWith(urlType)) {
                                doctoAdd.setUrl(urlString);
                            } else {
                                doctoAdd.setUrl(
                                        new StringBuffer(urlString).append('.').append(urlType).toString());
                            }
                            // (we always set sourceUrl as the true url of the file, so want to differentiate the URL with
                            //  some useful information)
                        } else if (null == doctoAdd.getMetadata()) { // Line oriented case
                            doctoAdd.setUrl(new StringBuffer(f.getUrlString()).append("/").append(nIndex)
                                    .append('.').append(urlType).toString());
                        } else {
                            if (null == md5) { // Will never happen, MD5 always exists
                                doctoAdd.setUrl(new StringBuffer(f.getUrlString()).append("/")
                                        .append(doctoAdd.getMetadata().hashCode()).append('.').append(urlType)
                                        .toString());
                            } else { // This is the standard call if the XML parser has not been configured to build the URL
                                doctoAdd.setUrl(new StringBuffer(f.getUrlString()).append("/")
                                        .append(DigestUtils.md5Hex(doctoAdd.getMetadata().toString()))
                                        .append('.').append(urlType).toString());
                            }
                        } //TESTED
                    }
                    doctoAdd.setTitle(f.getName().toString());
                    doctoAdd.setPublishedDate(new Date(fileTimestamp));
                    doctoAdd.setSourceUrl(f.getUrlString());

                    // Always add to files because I'm deleting the source URL
                    files.add(doctoAdd);
                } //TESTED 

            } catch (XMLStreamException e1) {
                errors++;
                _context.getHarvestStatus()
                        .logMessage(HarvestExceptionUtils.createExceptionMessage(e1).toString(), true);
            } catch (FactoryConfigurationError e1) {
                errors++;
                _context.getHarvestStatus().logMessage(e1.getMessage(), true);

            } catch (IOException e1) {
                errors++;
                _context.getHarvestStatus()
                        .logMessage(HarvestExceptionUtils.createExceptionMessage(e1).toString(), true);
            } catch (Exception e1) {
                errors++;
                _context.getHarvestStatus()
                        .logMessage(HarvestExceptionUtils.createExceptionMessage(e1).toString(), true);
            }
        } //(end if needs updated)
    } else //Tika supports Excel,Word,Powerpoint,Visio, & Outlook Documents
    {
        // (This dedup tells me if it's an add/update vs ignore - qr.isDuplicate higher up tells me if I need to add or update)
        if (needsUpdated_Url(modDate, f.getUrlString(), source)) {

            Metadata metadata = null;
            InputStream in = null;
            try {

                doc = new DocumentPojo();

                // Create a tika object (first time only)
                if (null == _tika) {
                    this.initializeTika(_context, source);
                }

                // BUGGERY
                // NEED TO LIKELY SET LIMIT TO BE 30MB or 50MB and BYPASS ANYTHING OVER THAT BELOW IS THE CODE TO DO THAT
                // tika.setMaxStringLength(30*1024*1024);
                // Disable the string length limit
                _tika.setMaxStringLength(-1);
                //input = new FileInputStream(new File(resourceLocation));
                // Create a metadata object to contain the metadata

                metadata = new Metadata();
                // Parse the file and get the text of the file
                doc.setSource(source.getTitle());
                doc.setSourceKey(source.getKey());
                doc.setMediaType(source.getMediaType());
                String fullText = "";

                in = f.getInputStream();
                try {
                    if (null == _tikaOutputFormat) { // text only
                        fullText = _tika.parseToString(in, metadata);
                    } //TESTED
                    else { // XML/HMTL
                        _tika.getParser().parse(in, _tikaOutputFormat, metadata, _tikaOutputParseContext);
                        fullText = _tikaXmlFormatWriter.toString();
                        _tikaXmlFormatWriter.getBuffer().setLength(0);
                    } //TESTED
                } finally {
                    if (null != in)
                        in.close();
                }
                int descCap = 500;
                doc.setFullText(fullText);
                if (descCap > fullText.length()) {
                    descCap = fullText.length();
                }
                doc.setDescription(fullText.substring(0, descCap));
                doc.setModified(new Date(fileTimestamp));
                doc.setCreated(new Date());
                doc.setUrl(f.getUrlString());
                doc.setTitle(f.getName().toString());
                doc.setPublishedDate(new Date(fileTimestamp));

                long memUsage = (250L * (doc.getFullText().length() + doc.getDescription().length())) / 100L; // 25% overhead, 2x for string->byte
                _memUsage += memUsage;
                _totalMemUsage.addAndGet(memUsage);

                // If the metadata contains a more plausible date then use that
                try {
                    String title = metadata.get(Metadata.TITLE);
                    if (null != title) {
                        doc.setTitle(title);
                    }
                } catch (Exception e) { // Fine just carry on                  
                }
                try {
                    Date date = metadata.getDate(Metadata.CREATION_DATE); // MS Word
                    if (null != date) {
                        doc.setPublishedDate(date);
                    } else {
                        date = metadata.getDate(Metadata.DATE); // Dublin
                        if (null != date) {
                            doc.setPublishedDate(date);
                        } else {
                            date = metadata.getDate(Metadata.ORIGINAL_DATE);
                            if (null != date) {
                                doc.setPublishedDate(date);
                            }
                        }
                    }
                } catch (Exception e) { // Fine just carry on                  
                }
                //TESTED

                // If the metadata contains a geotag then apply that:
                try {
                    String lat = metadata.get(Metadata.LATITUDE);
                    String lon = metadata.get(Metadata.LONGITUDE);
                    if ((null != lat) && (null != lon)) {
                        GeoPojo gt = new GeoPojo();
                        gt.lat = Double.parseDouble(lat);
                        gt.lon = Double.parseDouble(lon);
                        doc.setDocGeo(gt);
                    }
                } catch (Exception e) { // Fine just carry on                  
                }

                // Save the entire metadata:
                doc.addToMetadata("_FILE_METADATA_", metadata);

                for (ObjectId communityId : source.getCommunityIds()) {
                    doc.setCommunityId(communityId);
                }
                files.add(doc);

                // Close the input stream
                in.close();
                in = null;

                //TESTED

            } catch (SmbException e) {
                errors++;
                _context.getHarvestStatus()
                        .logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(), true);
            } catch (MalformedURLException e) {
                errors++;
                _context.getHarvestStatus()
                        .logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(), true);
            } catch (UnknownHostException e) {
                errors++;
                _context.getHarvestStatus()
                        .logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(), true);
            } catch (IOException e) {
                errors++;
                _context.getHarvestStatus().logMessage(e.getMessage(), true);
            } catch (TikaException e) {
                errors++;
                _context.getHarvestStatus().logMessage(e.getMessage(), true);
            } catch (Exception e) {
                errors++;
                _context.getHarvestStatus()
                        .logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(), true);
            } finally { // Close the input stream if an error occurs
                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // All good, do nothing
                    }
                }
            } // end exception handling
        } // end dedup check
    } // end XML vs "office" app

    //DEBUG
    //System.out.println("FILE=" + files.size() + " / MEM=" + _memUsage + " VS " + Runtime.getRuntime().totalMemory());
}

From source file:microsoft.exchange.webservices.data.AutodiscoverService.java

/**
 * Calls the Autodiscover service to retrieve configuration settings.
 *
 * @param <TSettings>  the generic type
 * @param cls          the cls/*from   w  ww  .j a v  a  2s .c  om*/
 * @param emailAddress The email address to retrieve configuration settings for.
 * @param currentHop   Current number of redirection urls/addresses attempted so far.
 * @return The requested configuration settings.
 * @throws Exception the exception
 */
private <TSettings extends ConfigurationSettingsBase> TSettings internalGetLegacyUserSettings(
        Class<TSettings> cls, String emailAddress, List<String> redirectionEmailAddresses,
        OutParam<Integer> currentHop) throws Exception {
    String domainName = EwsUtilities.domainFromEmailAddress(emailAddress);

    int scpUrlCount;
    OutParam<Integer> outParamInt = new OutParam<Integer>();
    List<URI> urls = this.getAutodiscoverServiceUrls(domainName, outParamInt);
    scpUrlCount = outParamInt.getParam();
    if (urls.size() == 0) {
        throw new ServiceValidationException(Strings.AutodiscoverServiceRequestRequiresDomainOrUrl);
    }

    // Assume caller is not inside the Intranet, regardless of whether SCP
    // Urls
    // were returned or not. SCP Urls are only relevent if one of them
    // returns
    // valid Autodiscover settings.
    this.isExternal = true;

    int currentUrlIndex = 0;

    // Used to save exception for later reporting.
    Exception delayedException = null;
    TSettings settings;

    do {
        URI autodiscoverUrl = urls.get(currentUrlIndex);
        boolean isScpUrl = currentUrlIndex < scpUrlCount;

        try {
            settings = this.getLegacyUserSettingsAtUrl(cls, emailAddress, autodiscoverUrl);

            switch (settings.getResponseType()) {
            case Success:
                // Not external if Autodiscover endpoint found via SCP
                // returned the settings.
                if (isScpUrl) {
                    this.isExternal = false;
                }
                this.url = autodiscoverUrl;
                return settings;
            case RedirectUrl:
                if (currentHop.getParam() < AutodiscoverMaxRedirections) {
                    currentHop.setParam(currentHop.getParam() + 1);

                    this.traceMessage(TraceFlags.AutodiscoverResponse,
                            String.format("Autodiscover " + "service " + "returned " + "redirection URL '%s'.",
                                    settings.getRedirectTarget()));

                    urls.add(currentUrlIndex, new URI(settings.getRedirectTarget()));

                    break;
                } else {
                    throw new AutodiscoverLocalException(Strings.MaximumRedirectionHopsExceeded);
                }
            case RedirectAddress:
                if (currentHop.getParam() < AutodiscoverMaxRedirections) {
                    currentHop.setParam(currentHop.getParam() + 1);

                    this.traceMessage(TraceFlags.AutodiscoverResponse, String.format(
                            "Autodiscover " + "service " + "returned " + "redirection email " + "address '%s'.",
                            settings.getRedirectTarget()));
                    // Bug E14:255576 If this email address was already tried, we may have a loop
                    // in SCP lookups. Disable consideration of SCP records.
                    this.disableScpLookupIfDuplicateRedirection(settings.getRedirectTarget(),
                            redirectionEmailAddresses);

                    return this.internalGetLegacyUserSettings(cls, settings.getRedirectTarget(),
                            redirectionEmailAddresses, currentHop);
                } else {
                    throw new AutodiscoverLocalException(Strings.MaximumRedirectionHopsExceeded);
                }
            case Error:
                // Don't treat errors from an SCP-based Autodiscover service
                // to be conclusive.
                // We'll try the next one and record the error for later.
                if (isScpUrl) {
                    this.traceMessage(TraceFlags.AutodiscoverConfiguration, "Error returned by "
                            + "Autodiscover service " + "found via SCP, treating " + "as inconclusive.");

                    delayedException = new AutodiscoverRemoteException(Strings.AutodiscoverError,
                            settings.getError());
                    currentUrlIndex++;
                } else {
                    throw new AutodiscoverRemoteException(Strings.AutodiscoverError, settings.getError());
                }
                break;
            default:
                EwsUtilities.EwsAssert(false, "Autodiscover.GetConfigurationSettings",
                        "An unexpected error has occured. " + "This code path should never be reached.");
                break;
            }
        } catch (XMLStreamException ex) {
            this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                    String.format("%s failed: XML parsing error: %s", url, ex.getMessage()));

            // The content at the URL wasn't a valid response, let's try the
            // next.
            currentUrlIndex++;
        } catch (IOException ex) {
            this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                    String.format("%s failed: I/O error: %s", url, ex.getMessage()));

            // The content at the URL wasn't a valid response, let's try the next.
            currentUrlIndex++;
        } catch (Exception ex) {
            HttpWebRequest response = null;
            URI redirectUrl;
            OutParam<URI> outParam1 = new OutParam<URI>();
            if ((response != null) && this.tryGetRedirectionResponse(response, outParam1)) {
                redirectUrl = outParam1.getParam();
                this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                        String.format("Host returned a redirection to url %s", redirectUrl.toString()));

                currentHop.setParam(currentHop.getParam() + 1);
                urls.add(currentUrlIndex, redirectUrl);
            } else {
                if (response != null) {
                    this.processHttpErrorResponse(response, ex);

                }

                this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                        String.format("%s failed: %s (%s)", url, ex.getClass().getName(), ex.getMessage()));

                // The url did not work, let's try the next.
                currentUrlIndex++;
            }
        }
    } while (currentUrlIndex < urls.size());

    // If we got this far it's because none of the URLs we tried have
    // worked. As a next-to-last chance, use GetRedirectUrl to
    // try to get a redirection URL using an HTTP GET on a non-SSL
    // Autodiscover endpoint. If successful, use this
    // redirection URL to get the configuration settings for this email
    // address. (This will be a common scenario for
    // DataCenter deployments).
    URI redirectionUrl = this.getRedirectUrl(domainName);
    OutParam<TSettings> outParam = new OutParam<TSettings>();
    if ((redirectionUrl != null)
            && this.tryLastChanceHostRedirection(cls, emailAddress, redirectionUrl, outParam)) {
        settings = outParam.getParam();
        return settings;
    } else {
        // Getting a redirection URL from an HTTP GET failed too. As a last
        // chance, try to get an appropriate SRV Record
        // using DnsQuery. If successful, use this redirection URL to get
        // the configuration settings for this email address.
        redirectionUrl = this.getRedirectionUrlFromDnsSrvRecord(domainName);
        if ((redirectionUrl != null)
                && this.tryLastChanceHostRedirection(cls, emailAddress, redirectionUrl, outParam)) {
            return outParam.getParam();
        }

        // If there was an earlier exception, throw it.
        if (delayedException != null) {
            throw delayedException;
        }

        throw new AutodiscoverLocalException(Strings.AutodiscoverCouldNotBeLocated);
    }
}

From source file:microsoft.exchange.webservices.data.autodiscover.AutodiscoverService.java

/**
 * Calls the Autodiscover service to retrieve configuration settings.
 *
 * @param <TSettings>  the generic type
 * @param cls          the cls/*from  ww  w  .j  ava2s .c  om*/
 * @param emailAddress The email address to retrieve configuration settings for.
 * @param currentHop   Current number of redirection urls/addresses attempted so far.
 * @return The requested configuration settings.
 * @throws Exception the exception
 */
private <TSettings extends ConfigurationSettingsBase> TSettings internalGetLegacyUserSettings(
        Class<TSettings> cls, String emailAddress, List<String> redirectionEmailAddresses,
        OutParam<Integer> currentHop) throws Exception {
    String domainName = EwsUtilities.domainFromEmailAddress(emailAddress);

    int scpUrlCount;
    OutParam<Integer> outParamInt = new OutParam<Integer>();
    List<URI> urls = this.getAutodiscoverServiceUrls(domainName, outParamInt);
    scpUrlCount = outParamInt.getParam();
    if (urls.size() == 0) {
        throw new ServiceValidationException(
                "This Autodiscover request requires that either the Domain or Url be specified.");
    }

    // Assume caller is not inside the Intranet, regardless of whether SCP
    // Urls
    // were returned or not. SCP Urls are only relevent if one of them
    // returns
    // valid Autodiscover settings.
    this.isExternal = true;

    int currentUrlIndex = 0;

    // Used to save exception for later reporting.
    Exception delayedException = null;
    TSettings settings;

    do {
        URI autodiscoverUrl = urls.get(currentUrlIndex);
        boolean isScpUrl = currentUrlIndex < scpUrlCount;

        try {
            settings = this.getLegacyUserSettingsAtUrl(cls, emailAddress, autodiscoverUrl);

            switch (settings.getResponseType()) {
            case Success:
                // Not external if Autodiscover endpoint found via SCP
                // returned the settings.
                if (isScpUrl) {
                    this.isExternal = false;
                }
                this.url = autodiscoverUrl;
                return settings;
            case RedirectUrl:
                if (currentHop.getParam() < AutodiscoverMaxRedirections) {
                    currentHop.setParam(currentHop.getParam() + 1);

                    this.traceMessage(TraceFlags.AutodiscoverResponse,
                            String.format("Autodiscover " + "service " + "returned " + "redirection URL '%s'.",
                                    settings.getRedirectTarget()));

                    urls.add(currentUrlIndex, new URI(settings.getRedirectTarget()));

                    break;
                } else {
                    throw new MaximumRedirectionHopsExceededException();
                }
            case RedirectAddress:
                if (currentHop.getParam() < AutodiscoverMaxRedirections) {
                    currentHop.setParam(currentHop.getParam() + 1);

                    this.traceMessage(TraceFlags.AutodiscoverResponse, String.format(
                            "Autodiscover " + "service " + "returned " + "redirection email " + "address '%s'.",
                            settings.getRedirectTarget()));
                    // Bug E14:255576 If this email address was already tried, we may have a loop
                    // in SCP lookups. Disable consideration of SCP records.
                    this.disableScpLookupIfDuplicateRedirection(settings.getRedirectTarget(),
                            redirectionEmailAddresses);

                    return this.internalGetLegacyUserSettings(cls, settings.getRedirectTarget(),
                            redirectionEmailAddresses, currentHop);
                } else {
                    throw new MaximumRedirectionHopsExceededException();
                }
            case Error:
                // Don't treat errors from an SCP-based Autodiscover service
                // to be conclusive.
                // We'll try the next one and record the error for later.
                if (isScpUrl) {
                    this.traceMessage(TraceFlags.AutodiscoverConfiguration, "Error returned by "
                            + "Autodiscover service " + "found via SCP, treating " + "as inconclusive.");

                    delayedException = new AutodiscoverRemoteException(
                            "The Autodiscover service returned an error.", settings.getError());
                    currentUrlIndex++;
                } else {
                    throw new AutodiscoverRemoteException("The Autodiscover service returned an error.",
                            settings.getError());
                }
                break;
            default:
                EwsUtilities.EwsAssert(false, "Autodiscover.GetConfigurationSettings",
                        "An unexpected error has occured. " + "This code path should never be reached.");
                break;
            }
        } catch (XMLStreamException ex) {
            this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                    String.format("%s failed: XML parsing error: %s", url, ex.getMessage()));

            // The content at the URL wasn't a valid response, let's try the
            // next.
            currentUrlIndex++;
        } catch (IOException ex) {
            this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                    String.format("%s failed: I/O error: %s", url, ex.getMessage()));

            // The content at the URL wasn't a valid response, let's try the next.
            currentUrlIndex++;
        } catch (Exception ex) {
            HttpWebRequest response = null;
            URI redirectUrl;
            OutParam<URI> outParam1 = new OutParam<URI>();
            if ((response != null) && this.tryGetRedirectionResponse(response, outParam1)) {
                redirectUrl = outParam1.getParam();
                this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                        String.format("Host returned a redirection to url %s", redirectUrl.toString()));

                currentHop.setParam(currentHop.getParam() + 1);
                urls.add(currentUrlIndex, redirectUrl);
            } else {
                if (response != null) {
                    this.processHttpErrorResponse(response, ex);

                }

                this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                        String.format("%s failed: %s (%s)", url, ex.getClass().getName(), ex.getMessage()));

                // The url did not work, let's try the next.
                currentUrlIndex++;
            }
        }
    } while (currentUrlIndex < urls.size());

    // If we got this far it's because none of the URLs we tried have
    // worked. As a next-to-last chance, use GetRedirectUrl to
    // try to get a redirection URL using an HTTP GET on a non-SSL
    // Autodiscover endpoint. If successful, use this
    // redirection URL to get the configuration settings for this email
    // address. (This will be a common scenario for
    // DataCenter deployments).
    URI redirectionUrl = this.getRedirectUrl(domainName);
    OutParam<TSettings> outParam = new OutParam<TSettings>();
    if ((redirectionUrl != null)
            && this.tryLastChanceHostRedirection(cls, emailAddress, redirectionUrl, outParam)) {
        settings = outParam.getParam();
        return settings;
    } else {
        // Getting a redirection URL from an HTTP GET failed too. As a last
        // chance, try to get an appropriate SRV Record
        // using DnsQuery. If successful, use this redirection URL to get
        // the configuration settings for this email address.
        redirectionUrl = this.getRedirectionUrlFromDnsSrvRecord(domainName);
        if ((redirectionUrl != null)
                && this.tryLastChanceHostRedirection(cls, emailAddress, redirectionUrl, outParam)) {
            return outParam.getParam();
        }

        // If there was an earlier exception, throw it.
        if (delayedException != null) {
            throw delayedException;
        }

        throw new AutodiscoverLocalException("The Autodiscover service couldn't be located.");
    }
}

From source file:org.apache.axiom.om.impl.llom.OMSourcedElementImpl.java

/**
 * Get parser from data source. Note that getDataReader may consume the underlying data source.
 *
 * @return parser/*from   ww  w  . j  a  v  a 2 s.  c om*/
 */
private XMLStreamReader getDirectReader() {
    try {
        // If expansion has occurred, then the reader from the datasource is consumed or stale.
        // In such cases use the stream reader from the OMElementImpl
        if (isExpanded()) {
            return super.getXMLStreamReader();
        } else {
            return dataSource.getReader();
        }
    } catch (XMLStreamException e) {
        log.error("Could not get parser from data source for element " + getPrintableName(), e);
        throw new RuntimeException("Error obtaining parser from data source:" + e.getMessage());
    }
}

From source file:org.apache.axis2.fastinfoset.FastInfosetMessageFormatter.java

/**
 * Retrieves the raw bytes from the SOAP envelop.
 * /*from  www. jav  a  2  s.  c  om*/
 * @see org.apache.axis2.transport.MessageFormatter#getBytes(org.apache.axis2.context.MessageContext, org.apache.axiom.om.OMOutputFormat)
 */
public byte[] getBytes(MessageContext messageContext, OMOutputFormat format) throws AxisFault {
    OMElement element = messageContext.getEnvelope();
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    try {
        //Creates StAX document serializer which actually implements the XMLStreamWriter
        XMLStreamWriter streamWriter = new StAXDocumentSerializer(outStream);
        element.serializeAndConsume(streamWriter);
        //TODO Looks like the SOAP envelop doesn't have an end document tag. Find out why?
        streamWriter.writeEndDocument();

        return outStream.toByteArray();

    } catch (XMLStreamException xmlse) {
        logger.error(xmlse.getMessage());
        throw new AxisFault(xmlse.getMessage(), xmlse);
    }
}

From source file:org.apache.axis2.fastinfoset.FastInfosetMessageFormatter.java

/**
 * Write the SOAP envelop to the given OutputStream.
 * // w  ww  .ja  v  a 2  s  .c om
 * @see org.apache.axis2.transport.MessageFormatter#writeTo(org.apache.axis2.context.MessageContext, org.apache.axiom.om.OMOutputFormat, java.io.OutputStream, boolean)
 */
public void writeTo(MessageContext messageContext, OMOutputFormat format, OutputStream outputStream,
        boolean preserve) throws AxisFault {
    OMElement element = messageContext.getEnvelope();

    try {
        //Create the StAX document serializer
        XMLStreamWriter streamWriter = new StAXDocumentSerializer(outputStream);
        if (preserve) {
            element.serialize(streamWriter);
        } else {
            element.serializeAndConsume(streamWriter);
        }
        //         TODO Looks like the SOAP envelop doesn't have a end document tag. Find out why?
        streamWriter.writeEndDocument();
    } catch (XMLStreamException xmlse) {
        logger.error(xmlse.getMessage());
        throw new AxisFault(xmlse.getMessage(), xmlse);
    }
}