Example usage for java.io ByteArrayOutputStream writeTo

List of usage examples for java.io ByteArrayOutputStream writeTo

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream writeTo.

Prototype

public synchronized void writeTo(OutputStream out) throws IOException 

Source Link

Document

Writes the complete contents of this ByteArrayOutputStream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count) .

Usage

From source file:CB_Locator.Map.ManagerBase.java

/**
 * Load Tile from URL and save to MapTile-Cache
 *
 * @param layer/*from  w w  w  .j a v  a2  s. c  o  m*/
 * @param tile
 * @return
 */
public boolean cacheTile(Layer layer, Descriptor tile) {

    if (layer == null)
        return false;

    // Gibts die Kachel schon in einem Mappack? Dann kann sie bersprungen werden!
    for (PackBase pack : mapPacks)
        if (pack.layer == layer)
            if (pack.Contains(tile) != null)
                return true;

    String filename = layer.GetLocalFilename(tile);
    // String path = layer.GetLocalPath(tile);
    String url = layer.GetUrl(tile);

    // Falls Kachel schon geladen wurde, kann sie bersprungen werden
    synchronized (this) {
        if (FileIO.FileExists(filename))
            return true;
    }

    // Kachel laden
    // set the connection timeout value to 15 seconds (15000 milliseconds)
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONECTION_TIME_OUT);

    HttpClient httpclient = new DefaultHttpClient(httpParams);
    HttpResponse response = null;

    HttpGet GET = new HttpGet(url);

    try {

        response = httpclient.execute(GET);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();

            synchronized (this) {
                // Verzeichnis anlegen
                if (!FileIO.createDirectory(filename))
                    return false;

                // Datei schreiben
                FileOutputStream stream = new FileOutputStream(filename, false);
                out.writeTo(stream);
                stream.close();
            }

            NumTilesLoaded++;
            // Global.TransferredBytes += result.Length;

            // ..more logic
        } else {
            // Closes the connection.
            response.getEntity().getContent().close();
            // throw new IOException(statusLine.getReasonPhrase());
            return false;
        }
        /*
         * webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Timeout = 15000; webRequest.Proxy = Global.Proxy; webResponse
         * = webRequest.GetResponse(); if (!webRequest.HaveResponse) return false; responseStream = webResponse.GetResponseStream();
         * byte[] result = Global.ReadFully(responseStream, 64000); // Verzeichnis anlegen lock (this) if (!Directory.Exists(path))
         * Directory.CreateDirectory(path); // Datei schreiben lock (this) { stream = new FileStream(filename, FileMode.CreateNew);
         * stream.Write(result, 0, result.Length); } NumTilesLoaded++; Global.TransferredBytes += result.Length;
         */
    } catch (Exception ex) {
        // Check last Error for this URL and post massage if the last > 1 min.

        String URL = GET.getURI().getAuthority();

        boolean PostErrorMassage = false;

        if (LastRequestTimeOut.containsKey(URL)) {
            long last = LastRequestTimeOut.get(URL);
            if ((last + CONECTION_TIME_OUT_MESSAGE_INTERVALL) < System.currentTimeMillis()) {
                PostErrorMassage = true;
                LastRequestTimeOut.remove(URL);
            }
        } else {
            PostErrorMassage = true;
        }

        if (PostErrorMassage) {
            LastRequestTimeOut.put(URL, System.currentTimeMillis());
            ConnectionError INSTANCE = new ConnectionError(layer.Name + " - Provider");
            GL.that.Toast(INSTANCE);
        }

        return false;
    }
    /*
     * finally { if (stream != null) { stream.Close(); stream = null; } if (responseStream != null) { responseStream.Close();
     * responseStream = null; } if (webResponse != null) { webResponse.Close(); webResponse = null; } if (webRequest != null) {
     * webRequest.Abort(); webRequest = null; } GC.Collect(); }
     */

    return true;
}

From source file:org.bibsonomy.rest.RestServlet.java

/**
 * @param request/*from  w w w.  ja va2  s.  c  om*/
 *            the servletrequest
 * @param response
 *            the servletresponse
 * @param method
 *            httpMethod to use, see {@link HttpMethod}
 * @throws IOException
 */
private void handle(final HttpServletRequest request, final HttpServletResponse response,
        final HttpMethod method) throws IOException {
    log.debug("Incoming Request: " + method.name() + " " + request.getRequestURL() + " from IP "
            + request.getHeader("x-forwarded-for"));
    final long start = System.currentTimeMillis();

    try {
        // validate the requesting user's authorization
        final LogicInterface logic = validateAuthorization(request);

        // parse the request object to retrieve a list with all items of the
        // http request
        final MultiPartRequestParser parser = new MultiPartRequestParser(request);

        // choose rendering format (defaults to xml)
        final RenderingFormat renderingFormat = RESTUtils.getRenderingFormatForRequest(
                request.getParameterMap(), request.getHeader(HeaderUtils.HEADER_ACCEPT),
                request.getContentType());

        // create Context
        final Reader reader = RESTUtils.getInputReaderForStream(request.getInputStream(), REQUEST_ENCODING);
        final Context context = new Context(method, getPathInfo(request), renderingFormat, this.urlRenderer,
                reader, parser.getList(), logic, request.getParameterMap(), additionalInfos);

        // validate request
        context.canAccess();

        // set some response headers
        final String userAgent = request.getHeader(HeaderUtils.HEADER_USER_AGENT);
        log.debug("[USER-AGENT] " + userAgent);
        response.setContentType(context.getContentType(userAgent));
        response.setCharacterEncoding(RESPONSE_ENCODING);

        // send answer
        if (method.equals(HttpMethod.POST)) {
            // if a POST request completes successfully this means that a
            // resource has been created
            response.setStatus(HttpServletResponse.SC_CREATED);
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
        }

        // just define an ByteArrayOutputStream to store all outgoing data
        final ByteArrayOutputStream cachingStream = new ByteArrayOutputStream();
        context.perform(cachingStream);

        /*
         * XXX: note: cachingStream.size() !=
         * cachingStream.toString().length() !! the correct value is the
         * first one!
         */
        response.setContentLength(cachingStream.size());

        // some more logging
        log.debug("Size of output sent:" + cachingStream.size());
        final long elapsed = System.currentTimeMillis() - start;
        log.debug("Processing time: " + elapsed + " ms");

        cachingStream.writeTo(response.getOutputStream());
    } catch (final AuthenticationException e) {
        log.warn(e.getMessage());
        response.setHeader("WWW-Authenticate",
                "Basic realm=\"" + RestProperties.getInstance().getBasicRealm() + "\"");
        sendError(request, response, HttpURLConnection.HTTP_UNAUTHORIZED, e.getMessage());
    } catch (final InternServerException e) {
        log.error(e.getMessage());
        sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (final NoSuchResourceException e) {
        log.error(e.getMessage());
        sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (final BadRequestOrResponseException e) {
        log.error(e.getMessage());
        sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (final AccessDeniedException e) {
        log.error(e.getMessage());
        sendError(request, response, HttpServletResponse.SC_FORBIDDEN, e.getMessage());
    } catch (final ResourceMovedException e) {
        log.error(e.getMessage());
        /*
         * sending new location TODO: add date using
         */
        response.setHeader("Location", urlRenderer.createHrefForResource(e.getUserName(), e.getNewIntraHash()));
        sendError(request, response, HttpServletResponse.SC_MOVED_PERMANENTLY, e.getMessage());
    } catch (final DatabaseException e) {
        final StringBuilder returnMessage = new StringBuilder("");
        for (final String hash : e.getErrorMessages().keySet()) {
            for (final ErrorMessage em : e.getErrorMessages(hash)) {
                log.error(em.toString());
                returnMessage.append(em.toString() + "\n ");
            }
        }
        sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, returnMessage.toString());

    } catch (final Exception e) {
        log.error(e, e);
        // well, lets fetch each and every error...
        sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:org.bdval.BDVModel.java

/**
 * Save the model to a set the specified zip stream. The files will contain all the
 * information needed to apply the BDVal model to new samples.
 *
 * @param zipStream      The stream to store the model to
 * @param options        The options associated with this model
 * @param task           The classification task used for this model
 * @param splitPlan      The split plan used to generat this model
 * @param writeModelMode The mode saving the model
 * @throws IOException if there is a problem writing to the files
 *//*w w w  . j  a  v  a 2  s  .c o  m*/
protected void save(final ZipOutputStream zipStream, final DAVOptions options, final ClassificationTask task,
        final SplitPlan splitPlan, final WriteModel writeModelMode) throws IOException {
    setZipStreamComment(zipStream);

    // Add ZIP entry for the model properties to output stream.
    saveProperties(zipStream, options, task, splitPlan, writeModelMode);

    // Add ZIP entries for the model training platform to output stream.
    savePlatform(zipStream, options);

    // Add ZIP entry for the model to output stream.
    zipStream.putNextEntry(new ZipEntry(FilenameUtils.getName(modelFilename)));
    // use an intermediate stream here since the model writer will close the stream
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    helper.model.write(byteArrayOutputStream);
    byteArrayOutputStream.writeTo(zipStream);
    zipStream.closeEntry();

    if (options.scaleFeatures) {
        if (options.probesetScaleMeanMap.size() <= 0) {
            throw new IllegalArgumentException("mean map must be populated.");
        }
        if (options.probesetScaleRangeMap.size() <= 0) {
            throw new IllegalArgumentException("range map must be populated.");
        }
    }

    // Add ZIP entry for the scale mean map to output stream.
    saveMeansMap(zipStream, options);

    // Add ZIP entry for the scale range map to output stream.
    saveRangeMap(zipStream, options);
}

From source file:org.dataconservancy.ui.api.PersonController.java

/**
 * Handles the posting of a new person, this will add a new person to the
 * system with registration status of pending.
 *
 * @throws org.dataconservancy.model.builder.InvalidXmlException
 * @throws java.io.IOException// ww w .ja  va2  s .  c  om
 */
@RequestMapping(method = { RequestMethod.POST })
public void handlePersonPostRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestBody byte[] content, HttpServletRequest req, HttpServletResponse resp)
        throws BizInternalException, BizPolicyException, InvalidXmlException, IOException {
    if (req.getContentType().contains("application/x-www-form-urlencoded")) {
        content = URLDecoder.decode(new String(content, "UTF-8"), "UTF-8").getBytes("UTF-8");
    }
    //use businessobjectBuilder to deserialize content into a bop -> set of person
    Set<Person> postedPersonSet = builder.buildBusinessObjectPackage(new ByteArrayInputStream(content))
            .getPersons();
    //currently, only handle request to create 1 person
    //A request is considered BAD if it contains 0 person, or more than 1 person
    if (postedPersonSet.size() != 1) {
        try {
            resp.setStatus(HttpStatus.SC_BAD_REQUEST);
            resp.getWriter()
                    .print("Only one new person can be requested to be created via this API at a time.");
            resp.getWriter().flush();
            resp.getWriter().close();
        } catch (Exception ee) {
            log.debug("Handling exception", ee);
        }
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Person person = postedPersonSet.iterator().next();
        try {
            Person createPerson = userService.create(person);
            //Serialize the created Person to return
            Bop businessObjectPackage = new Bop();
            businessObjectPackage.addPerson(createPerson);

            resp.setStatus(HttpStatus.SC_OK);

            resp.setHeader(LOCATION, createPerson.getId());
            resp.setHeader(LAST_MODIFIED, DateTime.now().toString());
            builder.buildBusinessObjectPackage(businessObjectPackage, baos);
            resp.setHeader(ETAG, ETagCalculator.calculate(Integer.toString(businessObjectPackage.hashCode())));
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/xml");
            resp.setContentLength(baos.size());
            baos.writeTo(resp.getOutputStream());
        } catch (PersonUpdateException re) {
            resp.setStatus(HttpStatus.SC_BAD_REQUEST);
            resp.getOutputStream().println(re.getMessage());
            resp.getWriter().flush();
            resp.getWriter().close();
        }
    }
}

From source file:fr.aliasource.webmail.server.export.ExportConversationImpl.java

/**
 * The actual business logic.//from  w  ww .  java  2  s .  c o  m
 * 
 * @param requ
 *            the request object
 * @param resp
 *            the response object
 * @throws IOException
 * @throws ServletException
 */
public void service(HttpServletRequest req, HttpServletResponse response) throws IOException, ServletException {
    logger.info("Export conversation called.");

    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String uri = req.getRequestURI();
    String convAndMessageIds = extractConversationIdFromRequestURI(uri);
    MessageId messageId = getMessageIdPart(convAndMessageIds);
    ConversationId conversationId = getConversationIdPart(convAndMessageIds);

    String folder = conversationId.getSourceFolder();

    logger.info("Conversation id: " + conversationId.getConversationId() + " folder: " + folder + " uri: " + uri
            + "Message id: " + messageId);

    Folder f = new Folder(folder, folder);
    ConversationReference cr = account.findConversation(conversationId);
    ClientMessage[] cm = null;
    if (messageId == null) {
        cm = account.fetchMessages(f, cr.getMessageIds());
    } else {
        cm = account.fetchMessages(f, Arrays.asList(messageId));
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ConversationExporter exporter = new ConversationExporter(
            req.getContextPath() + "/minig/images/logo_print.jpg");
    try {
        if (req.getRequestURI().endsWith(".html")) {
            exporter.exportToHtml(account, cr, cm, baos);
            response.setContentType("text/html");
        } else {
            exporter.exportToPdf(account, cr, cm, baos);
            response.setContentType("application/pdf");
        }
    } catch (ConversationExporterException e) {
        logger.error("Cannot render conversation", e);
        throw new ServletException(e);
    }

    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");

    response.setContentLength(baos.size());
    ServletOutputStream out = response.getOutputStream();
    baos.writeTo(out);
    out.flush();

}

From source file:gov.utah.dts.det.ccl.actions.reports.ReportsPrintAction.java

private void sendToResponse(ByteArrayOutputStream ba, String filename) throws IOException {
    if (ba != null && ba.size() > 0) {
        response.setContentLength(ba.size());
        response.setContentType("application/pdf");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        if (StringUtils.isNotBlank(filename)) {
            response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");
        } else {//from  w  w  w .ja  v  a2  s  .  co  m
            response.setHeader("Content-disposition", "attachment");
        }

        ServletOutputStream out = response.getOutputStream();
        ba.writeTo(out);
        out.flush();
    }
}

From source file:airlift.servlet.rest.RestServlet.java

/**
 * Process request./*w  w w. ja  v  a  2s.c om*/
 *
 * @param _httpServletRequest the _http servlet request
 * @param _httpServletResponse the _http servlet response
 * @param _method the _method
 * @param _restContext the _rest context
 * @param _uriParameterMap the _uri parameter map
 * @throws ServletException the servlet exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
protected final void processRequest(HttpServletRequest _httpServletRequest,
        HttpServletResponse _httpServletResponse, String _method, RestContext _restContext,
        Map _uriParameterMap) throws ServletException, IOException {
    String userId = (_restContext.getUser() != null) ? _restContext.getUser().getUserId() : "";

    String appName = getServletName();
    String domainName = _restContext.getThisDomain();
    java.util.List<String> handlerPathList = _restContext.getHandlerPathList();

    try {
        String defaultMimeType = (this.getServletConfig().getInitParameter("a.default.mime.type") != null)
                ? this.getServletConfig().getInitParameter("a.default.mime.type")
                : "text/html";
        ContentContext contentContext = new SimpleContentContext(new byte[0], defaultMimeType);

        if (handlerPathList != null) {
            boolean handlerNotFound = false;

            try {
                contentContext = getHandlerContext().execute(appName, _restContext, _method, this,
                        _httpServletRequest, _httpServletResponse, _uriParameterMap);
            } catch (airlift.servlet.rest.HandlerException _handlerException) {
                if (_handlerException
                        .getErrorCode() == airlift.servlet.rest.HandlerException.ErrorCode.HANDLER_NOT_FOUND) {
                    handlerNotFound = true;
                } else {
                    throw _handlerException;
                }
            }

            if (handlerNotFound == true) {
                sendCodedPage("405", "Method Not Allowed", _httpServletResponse);
            }

            int responseCode = Integer.parseInt(contentContext.getResponseCode());

            _httpServletResponse.setStatus(responseCode);

            if (responseCode == 301 || responseCode == 302 || responseCode == 303)
            //TODO this should be checking to see if the method
            //call is a POST PUT or DELETE.  At this point the
            {
                _httpServletResponse.sendRedirect(contentContext.getRedirectUri());
            } else {
                if (contentContext.streamed != true) {
                    if (responseCode < 400
                            || contentContext.getContent() != null && contentContext.getContent().length > 0) {
                        for (java.util.Map.Entry<String, String[]> header : contentContext.getHeaderMap()
                                .entrySet()) {

                            String[] headerValues = header.getValue();

                            if (headerValues != null) {
                                for (int h = 0; h < headerValues.length; h++) {
                                    _httpServletResponse.addHeader(header.getKey(), headerValues[h]);
                                }
                            }
                        }

                        _httpServletResponse.setContentType(contentContext.getType());
                        byte[] content = contentContext.getContent();
                        _httpServletResponse.setContentLength(content.length);

                        java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
                        byteArrayOutputStream.write(content, 0, content.length);
                        byteArrayOutputStream.writeTo(_httpServletResponse.getOutputStream());
                        byteArrayOutputStream.flush();
                        _httpServletResponse.getOutputStream().flush();
                    } else {
                        sendCodedPage(contentContext.getResponseCode(), "", _httpServletResponse);
                    }
                }
            }
        } else {
            sendCodedPage("404", "Resource Not Found", _httpServletResponse);
        }
    } catch (Throwable t) {
        //log exception
        //log content generated so far
        log.severe("Airlift encountered exception: " + t.toString());

        String errorString = airlift.util.AirliftUtil.serializeStackTrace(t);
        log.severe("Airlift prints this stack trace: " + errorString);

        String reportJavaException = this.getServletConfig().getInitParameter("a.report.java.exception");

        ContentContext contentContext = new SimpleContentContext();

        if ("yes".equalsIgnoreCase(reportJavaException) == true) {

            contentContext.setType("text/html");
            contentContext.setContent(t.toString());
            _httpServletResponse.getWriter().print(contentContext.getContent());
        } else {
            sendCodedPage("500", "Internal Server Error", _httpServletResponse);
        }
    }
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java

/**
 * Canonicalize an input MathML stream./*  w  w  w .j  a va  2 s  .  co m*/
 *
 * @param in input stream to be canonicalized
 * @param out canonical output stream of input
 * @throws JDOMException problem with DOM
 * @throws IOException problem with streams
 * @throws ModuleException some module cannot canonicalize the input
 */
public void canonicalize(final InputStream in, final OutputStream out)
        throws JDOMException, IOException, ModuleException, XMLStreamException {
    if (in == null) {
        throw new NullPointerException("in");
    }
    if (out == null) {
        throw new NullPointerException("out");
    }

    InputStream inputStream = in;
    if (enforcingXHTMLPlusMathMLDTD) {
        inputStream = DTDManipulator.injectXHTMLPlusMathMLDTD(in);
    }
    ByteArrayOutputStream outputStream = null;

    // calling stream modules
    for (StreamModule module : streamModules) {
        outputStream = module.execute(inputStream);
        if (outputStream == null) {
            throw new IOException("Module " + module + "returned null.");
        }
        inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    }

    if (enforcingXHTMLPlusMathMLDTD) {
        inputStream = DTDManipulator.removeDTD(inputStream);
    }

    // do not create the JDOM representation if there are no modules
    if (domModules.isEmpty()) {
        if (streamModules.isEmpty()) {
            throw new IOException("There are no modules added.");
        }
        assert outputStream != null; // nonempty streamModules + nothing thrown in for
        outputStream.writeTo(out);
        return;
    }

    // creating the JDOM representation from the stream
    final SAXBuilder builder = Settings.setupSAXBuilder();
    final Document document = builder.build(inputStream);

    // calling JDOM modules
    for (DOMModule module : domModules) {
        module.execute(document);
    }

    // convertong the JDOM representation back to stream
    final XMLOutputter serializer = new XMLOutputter();
    serializer.output(document, out);
}

From source file:com.krawler.spring.documents.documentDAOImpl.java

public File storeFile(ByteArrayOutputStream baos, String destinationDirectory, String fileName)
        throws ServiceException {
    File uploadFile = null;/*from w w w. ja  v  a 2  s . c om*/
    try {
        File destDir = new File(destinationDirectory);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        uploadFile = new File(destinationDirectory + "/" + fileName);
        FileOutputStream oss = new FileOutputStream(uploadFile);
        baos.writeTo(oss);
    } catch (Exception ex) {
        throw ServiceException.FAILURE("documentDAOImpl.storeFile", ex);
    } finally {
        return uploadFile;
    }

}

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

/**
 * Executes this instance.//from   w w  w. ja  v a 2s  . co  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
        }
    }
}