Example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream

List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream.

Prototype

public abstract InputStream getResponseBodyAsStream() throws IOException;

Source Link

Usage

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<LearningObjective> getLearningObjectives(int learningObjectId, int instanceId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectives",
            learningObjectId, instanceId);
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    List<LearningObjective> objectivesCreator = new ArrayList<LearningObjective>();
    try {/*ww  w  . j  a  va 2s  . c  o  m*/
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                objectivesCreator = deserializeXMLToListOfLearningObjectives(method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return objectivesCreator;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public LearningObjectInstanceUserReport getLearningObjectInstanceUserReport(int instanceId,
        int learningObjectId, int userId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Reports/%s",
            learningObjectId, instanceId, userId);
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    LearningObjectInstanceUserReport report = new LearningObjectInstanceUserReport();
    try {//from w w w  .j  a v a  2s  .  co  m
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                report = deserializeXMLToLearningObjectInstanceUserReport(method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return report;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<OrganisationRole> getOrganisationRolesForCurrentUser() throws Exception {
    String uri = String.format(_baseUri + "/LearningObjectService.svc/OrganizationRolesForCurrentUser");
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    List<OrganisationRole> organizationRolesForUser = new ArrayList<OrganisationRole>();
    try {//w w w  .ja v a 2  s.  c  o  m
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                organizationRolesForUser = deserializeXMLToOrganisationRoles(method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return organizationRolesForUser;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<Organisation> getOrganisationsForLearningObjectInstance(int learningObjectId, int instanceId)
        throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Organizations",
            learningObjectId, instanceId);
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    List<Organisation> organizationsForLearningToolCreator = new ArrayList<Organisation>();
    try {//from w  ww  . j  ava  2  s. com
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                organizationsForLearningToolCreator = deserializeXMLToOrganisations(
                        method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return organizationsForLearningToolCreator;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public LearningObjectiveReportSettings getLearningObjectiveReportSettings(int learningObjectId, int instanceId,
        int assessUserId) throws Exception {
    String uri = String.format(_baseUri
            + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectiveReportSettings",
            learningObjectId, instanceId);
    QueryStringBuilder query = new QueryStringBuilder(uri, false);
    query.AddParameter("assessUserId", Integer.toString(assessUserId));

    HttpMethod method = getInitializedHttpMethod(_httpClient, query.getQueryString(), HttpMethodType.GET);
    LearningObjectiveReportSettings loReportSettings = new LearningObjectiveReportSettings();
    try {/*from   w w  w  . j a  v a  2s .c o  m*/
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                loReportSettings = deserializeXMLToLearningObjectiveReportSettings(
                        method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return loReportSettings;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<LearningObjectiveAssessment> getLearningObjectiveUserAssessments(int learningObjectId,
        int instanceId, int userId) throws Exception {
    String uri = String.format(_baseUri
            + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectiveUserAssessments",
            learningObjectId, instanceId);
    QueryStringBuilder query = new QueryStringBuilder(uri, false);
    query.AddParameter("userId", Integer.toString(userId));

    HttpMethod method = getInitializedHttpMethod(_httpClient, query.getQueryString(), HttpMethodType.GET);
    List<LearningObjectiveAssessment> loAssessments = new ArrayList<LearningObjectiveAssessment>();
    try {// www.j ava 2s.  c  o  m
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                loAssessments = deserializeXMLToListOfLearningObjectiveAssessment(
                        method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return loAssessments;
}

From source file:com.groupon.odo.Proxy.java

/**
 * Execute a request//w ww.  j av  a2s  . c o  m
 *
 * @param httpMethodProxyRequest
 * @param httpServletRequest
 * @param httpServletResponse
 * @param history
 * @param outStream
 * @throws Exception
 */
private void executeRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, History history, OutputStream outStream) throws Exception {
    int intProxyResponseCode = 999;
    try {
        // Create a default HttpClient
        HttpClient httpClient = new HttpClient();
        httpMethodProxyRequest.setFollowRedirects(false);
        ArrayList<String> headersToRemove = getRemoveHeaders();

        httpClient.getParams().setSoTimeout(60000);

        httpServletRequest.setAttribute("com.groupon.odo.removeHeaders", headersToRemove);
        intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    } catch (Exception e) {
        requestInformation.get().outputString = "TIMEOUT";
        logRequestHistory(httpMethodProxyRequest, httpServletResponse, history);
        throw e;
    }
    logger.info("Response code: {}, {}", intProxyResponseCode,
            HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {

        String stringStatusCode = Integer.toString(intProxyResponseCode);
        processRedirect(stringStatusCode, httpMethodProxyRequest, httpServletRequest, httpServletResponse);
    } else {
        // Pass the response code back to the client
        httpServletResponse.setStatus(intProxyResponseCode);

        // Pass response headers back to the client
        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
        for (Header header : headerArrayResponse) {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }

        // there is no data for a HTTP 304
        if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED) {
            // Send the content to the client
            InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);

            int intNextByte;
            // Collect all of the server data
            while ((intNextByte = bufferedInputStream.read()) != -1) {
                outStream.write(intNextByte);
            }
        }
    }
}

From source file:com.zimbra.cs.dav.service.DavServlet.java

private boolean isProxyRequest(DavContext ctxt, DavMethod m)
        throws IOException, DavException, ServiceException {
    Provisioning prov = Provisioning.getInstance();
    ItemId target = null;/*w  w w.ja v a2  s . c  o m*/
    String extraPath = null;
    String requestPath = ctxt.getPath();
    try {
        if (ctxt.getUser() == null) {
            return false;
        }
        if (requestPath == null || requestPath.length() < 2) {
            return false;
        }
        Account account = prov.getAccountByName(ctxt.getUser());
        if (account == null) {
            return false;
        }
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccount(account);
        Pair<Folder, String> match = mbox.getFolderByPathLongestMatch(ctxt.getOperationContext(),
                Mailbox.ID_FOLDER_USER_ROOT, requestPath);
        Folder targetFolder = match.getFirst();
        if (!(targetFolder instanceof Mountpoint)) {
            return false;
        }
        Mountpoint mp = (Mountpoint) targetFolder;
        target = new ItemId(mp.getOwnerId(), mp.getRemoteId());
        extraPath = match.getSecond();
    } catch (ServiceException e) {
        ZimbraLog.dav.debug("can't get path", e);
        return false;
    }

    // we don't proxy zero depth PROPFIND, and all PROPPATCH on mountpoints,
    // because the mountpoint object contains WebDAV properties that are
    // private to the user.
    // we also don't proxy DELETE on a mountpoint.
    if (extraPath == null && (m.getName().equals(PropFind.PROPFIND) && ctxt.getDepth() == DavContext.Depth.zero
            || m.getName().equals(PropPatch.PROPPATCH) || m.getName().equals(Delete.DELETE))) {
        return false;
    }

    String prefix = ctxt.getPath();
    if (extraPath != null) {
        prefix = prefix.substring(0, prefix.indexOf(extraPath));
    }
    prefix = HttpUtil.urlEscape(DAV_PATH + "/" + ctxt.getUser() + prefix);

    if (!prefix.endsWith("/")) {
        prefix += "/";
    }

    // make sure the target account exists.
    Account acct = prov.getAccountById(target.getAccountId());
    if (acct == null) {
        return false;
    }
    Server server = prov.getServer(acct);
    if (server == null) {
        return false;
    }

    // get the path to the target mail item
    AuthToken authToken = AuthProvider.getAuthToken(ctxt.getAuthAccount());
    ZMailbox.Options zoptions = new ZMailbox.Options(authToken.toZAuthToken(), AccountUtil.getSoapUri(acct));
    zoptions.setNoSession(true);
    zoptions.setTargetAccount(target.getAccountId());
    zoptions.setTargetAccountBy(Key.AccountBy.id);
    ZMailbox zmbx = ZMailbox.getMailbox(zoptions);
    ZFolder f = zmbx.getFolderById("" + target.toString());
    if (f == null) {
        return false;
    }
    String path = f.getPath();
    String newPrefix = HttpUtil.urlEscape(DAV_PATH + "/" + acct.getName() + f.getPath());

    if (ctxt.hasRequestMessage()) {
        // replace the path in <href> of the request with the path to the target mail item.
        Document req = ctxt.getRequestMessage();
        for (Object hrefObj : req.getRootElement().elements(DavElements.E_HREF)) {
            if (!(hrefObj instanceof Element)) {
                continue;
            }
            Element href = (Element) hrefObj;
            String v = href.getText();
            // prefix matching is not as straightforward as we have jetty redirect from /dav to /home/dav.
            href.setText(newPrefix + "/" + v.substring(v.lastIndexOf('/') + 1));
        }
    }

    // build proxy request
    String url = getProxyUrl(ctxt.getRequest(), server, DAV_PATH)
            + HttpUtil.urlEscape("/" + acct.getName() + path + "/" + (extraPath == null ? "" : extraPath));
    HttpState state = new HttpState();
    authToken.encode(state, false, server.getAttr(Provisioning.A_zimbraServiceHostname));
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    client.setState(state);
    HttpMethod method = m.toHttpMethod(ctxt, url);
    method.setRequestHeader(new Header(DavProtocol.HEADER_USER_AGENT, "Zimbra-DAV/" + BuildInfo.VERSION));
    if (ZimbraLog.dav.isDebugEnabled()) {
        Enumeration<String> headers = ctxt.getRequest().getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = headers.nextElement();
            if (!PROXY_REQUEST_HEADERS.contains(hdr) && !IGNORABLE_PROXY_REQUEST_HEADERS.contains(hdr)) {
                ZimbraLog.dav.debug(
                        "Dropping header(s) with name [%s] from proxy request (not in PROXY_REQUEST_HEADERS)",
                        hdr);
            }
        }
    }

    for (String h : PROXY_REQUEST_HEADERS) {
        String hval = ctxt.getRequest().getHeader(h);
        if (hval != null) {
            method.addRequestHeader(h, hval);
        }
    }
    int statusCode = HttpClientUtil.executeMethod(client, method);
    if (ZimbraLog.dav.isDebugEnabled()) {
        for (Header hval : method.getResponseHeaders()) {
            String hdrName = hval.getName();
            if (!PROXY_RESPONSE_HEADERS.contains(hdrName)
                    && !IGNORABLE_PROXY_RESPONSE_HEADERS.contains(hdrName)) {
                ZimbraLog.dav.debug("Dropping header [%s] from proxy response (not in PROXY_RESPONSE_HEADERS)",
                        hval);
            }
        }
    }

    for (String h : PROXY_RESPONSE_HEADERS) {
        for (Header hval : method.getResponseHeaders(h)) {
            String hdrValue = hval.getValue();
            if (DavProtocol.HEADER_LOCATION.equals(h)) {
                int pfxLastSlashPos = prefix.lastIndexOf('/');
                int lastSlashPos = hdrValue.lastIndexOf('/');
                if ((lastSlashPos > 0) && (pfxLastSlashPos > 0)) {
                    hdrValue = prefix.substring(0, pfxLastSlashPos) + hdrValue.substring(lastSlashPos);
                    ZimbraLog.dav.debug("Original [%s] from proxy response new value '%s'", hval, hdrValue);
                }
            }
            ctxt.getResponse().addHeader(h, hdrValue);
        }
    }

    ctxt.getResponse().setStatus(statusCode);
    ctxt.setStatus(statusCode);
    try (InputStream in = method.getResponseBodyAsStream()) {
        switch (statusCode) {
        case DavProtocol.STATUS_MULTI_STATUS:
            // rewrite the <href> element in the response to point to local mountpoint.
            try {
                Document response = W3cDomUtil.parseXMLToDom4jDocUsingSecureProcessing(in);
                Element top = response.getRootElement();
                for (Object responseObj : top.elements(DavElements.E_RESPONSE)) {
                    if (!(responseObj instanceof Element)) {
                        continue;
                    }
                    Element href = ((Element) responseObj).element(DavElements.E_HREF);
                    String v = href.getText();
                    v = URLDecoder.decode(v);
                    // Bug:106438, because v contains URL encoded value(%40) for '@' the comparison fails
                    if (v.startsWith(newPrefix)) {
                        href.setText(prefix + v.substring(newPrefix.length() + 1));
                    }
                }
                if (ZimbraLog.dav.isDebugEnabled()) {
                    ZimbraLog.dav.debug("PROXY RESPONSE:\n%s", new String(DomUtil.getBytes(response), "UTF-8"));
                }
                DomUtil.writeDocumentToStream(response, ctxt.getResponse().getOutputStream());
                ctxt.responseSent();
            } catch (XmlParseException e) {
                ZimbraLog.dav.warn("proxy request failed", e);
                return false;
            }
            break;
        default:
            if (in != null) {
                ByteUtil.copy(in, true, ctxt.getResponse().getOutputStream(), false);
            }
            ctxt.responseSent();
            break;
        }
        return true;
    }
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Exchange 2003: get mailPath from welcome page
 *
 * @param method current http method/*  w w w. j  a  v  a  2s  .  c  o  m*/
 * @return mail path from body
 */
protected String getMailpathFromWelcomePage(HttpMethod method) {
    String welcomePageMailPath = null;
    // get user mail URL from html body (multi frame)
    BufferedReader mainPageReader = null;
    try {
        mainPageReader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        //noinspection StatementWithEmptyBody
        String line;
        while ((line = mainPageReader.readLine()) != null && line.toLowerCase().indexOf(BASE_HREF) == -1) {
        }
        if (line != null) {
            // Exchange 2003
            int start = line.toLowerCase().indexOf(BASE_HREF) + BASE_HREF.length();
            int end = line.indexOf('\"', start);
            String mailBoxBaseHref = line.substring(start, end);
            URL baseURL = new URL(mailBoxBaseHref);
            welcomePageMailPath = URIUtil.decode(baseURL.getPath());
            LOGGER.debug("Base href found in body, mailPath is " + welcomePageMailPath);
        }
    } catch (IOException e) {
        LOGGER.error("Error parsing main page at " + method.getPath(), e);
    } finally {
        if (mainPageReader != null) {
            try {
                mainPageReader.close();
            } catch (IOException e) {
                LOGGER.error("Error parsing main page at " + method.getPath());
            }
        }
        method.releaseConnection();
    }
    return welcomePageMailPath;
}

From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java

private byte[] executeMethod(HttpMethod method, final Context context)
        throws IOException, URIException, MalformedURLException, EngineException {
    Header[] requestHeaders, responseHeaders = null;
    byte[] result = null;
    String contents = null;//  w w w  . j  a v  a  2s .  c  o  m
    int statuscode = -1;

    if (!context.requestedObject.runningThread.bContinue)
        return null;

    Engine.logBeans
            .debug("(HttpConnector) Executing method - " + method.getName() + "(" + method.getPath() + ")");

    try {
        requestHeaders = method.getRequestHeaders();
        if (Engine.logBeans.isTraceEnabled())
            Engine.logBeans
                    .trace("(HttpConnector) Request headers :\n" + Arrays.asList(requestHeaders).toString());

        statuscode = doExecuteMethod(method, context);

        Engine.logBeans.debug("(HttpConnector) Status: " + method.getStatusLine().toString());

        responseHeaders = method.getResponseHeaders();
        context.setResponseHeaders(responseHeaders);
        if (Engine.logBeans.isTraceEnabled())
            Engine.logBeans
                    .trace("(HttpConnector) Response headers:\n" + Arrays.asList(responseHeaders).toString());

        if (statuscode != -1) {
            InputStream in = method.getResponseBodyAsStream();
            if (in != null) {

                /**
                 * Retrieve response charset if available in responseHeaders
                 */
                charset = null;
                boolean checkGZip = false; // add GZip support #320

                for (int i = 0; i < responseHeaders.length && (charset == null || !checkGZip); i++) {
                    Header head = responseHeaders[i];
                    if (HeaderName.ContentType.is(head)) {
                        context.contentType = head.getValue();
                        HeaderElement[] els = head.getElements();
                        for (int j = 0; j < els.length && charset == null; j++) {
                            NameValuePair nvp = els[j].getParameterByName("charset");
                            if (nvp != null)
                                charset = nvp.getValue();
                        }
                    } else if (HeaderName.ContentEncoding.is(head)) {
                        checkGZip = true;
                        HeaderElement[] els = head.getElements();
                        for (int j = 0; j < els.length; j++)
                            if ("gzip".equals(els[j].getName())) {
                                Engine.logBeans.debug("(HttpConnector) Decode GZip stream");
                                in = new GZIPInputStream(in);
                            }
                    }
                }

                if (context.contentType != null && context.contentType.startsWith("multipart/")
                        && context.requestedObject instanceof AbstractHttpTransaction) {
                    Engine.logBeans.debug("(HttpConnector) Decoding multipart contentType");

                    try {
                        AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject;

                        BigMimeMultipart mp = new BigMimeMultipart(new BufferedInputStream(in),
                                context.contentType);

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        mp.nextPart(bos);
                        result = bos.toByteArray();

                        if (transaction.getAllowDownloadAttachment()) {
                            Document doc = context.outputDocument;
                            Element attInfo = null;

                            File file = File.createTempFile("c8o_", ".part");

                            for (MimePart bp = mp.nextPart(file); bp != null; bp = mp.nextPart(file)) {
                                try {
                                    file.deleteOnExit();

                                    if (attInfo == null) {
                                        Engine.logBeans.debug("(HttpConnector) Saving attachment(s)");

                                        attInfo = doc.createElement("AttachmentInfo");
                                        doc.getDocumentElement().appendChild(attInfo);
                                    }

                                    Element att = doc.createElement("attachment");
                                    attInfo.appendChild(att);

                                    String cid = bp.getContentID();

                                    if (cid != null) {
                                        cid = cid.replaceFirst("^<?(.*?)>?$", "$1");
                                        att.setAttribute("cid", "cid:" + cid);
                                    }

                                    Engine.logBeans.debug("(HttpConnector) Saving the attachment cid: " + cid
                                            + " in file: " + file.getAbsolutePath());

                                    att.setAttribute("filepath", file.getAbsolutePath());

                                    Enumeration<javax.mail.Header> headers = GenericUtils
                                            .cast(bp.getAllHeaders());
                                    while (headers.hasMoreElements()) {
                                        javax.mail.Header header = headers.nextElement();
                                        Element eHeader = doc.createElement("header");
                                        att.appendChild(eHeader);

                                        eHeader.setAttribute("name", header.getName());
                                        eHeader.setAttribute("value", header.getValue());
                                    }
                                } catch (Exception e1) {
                                    Engine.logBeans
                                            .error("(HttpConnector) Failed to retrieve the attachment in "
                                                    + file.getAbsolutePath(), e1);
                                }

                                file = File.createTempFile("c8o_", ".part");
                            }

                            file.delete();
                            in.close();
                        }
                    } catch (Exception e) {
                        Engine.logBeans.error("(HttpConnector) Failed to retrieve attachments", e);
                    }
                } else {
                    result = IOUtils.toByteArray(in);
                    in.close();
                }
            }

            if (Engine.logBeans.isTraceEnabled()) {
                contents = new String((result != null) ? result : new byte[] {});
                Engine.logBeans.trace("(HttpConnector) Response content:\n" + contents);
            }

            String redirectUrl, newuri;
            GetMethod redirectMethod = null;

            // Handles REDIRECTION through Location header
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

                Header location = method.getResponseHeader("Location");
                if (location != null) {
                    newuri = location.getValue();
                    if ((newuri == null) || (newuri.equals(""))) {
                        newuri = "/";
                    }

                    // ignore any data after the ";" character
                    int split = newuri.indexOf(';');
                    if (split != -1) {
                        newuri = newuri.substring(0, split);
                    }

                    redirectUrl = getAbsoluteUrl(method, newuri);
                    Engine.logBeans.debug("(HttpConnector) Redirecting to : " + redirectUrl);
                    redirectMethod = new GetMethod(redirectUrl);

                    // set headers
                    for (int i = 0; i < requestHeaders.length; i++)
                        redirectMethod.setRequestHeader(requestHeaders[i]);

                    referer = redirectUrl.startsWith("http") ? redirectUrl
                            : (hostConfiguration.getHostURL() + redirectUrl);

                    result = executeMethod(redirectMethod, context); // recurse
                } else {
                    Engine.logBeans.debug("(HttpConnector) Invalid redirect!");
                }
            } else {
                /*
                 * String lwContents = contents.toLowerCase(); int index, i,
                 * j, k, z; // Handles REDIRECTION through META Refresh if
                 * (((index = lwContents.indexOf("http-equiv='refresh'")) !=
                 * -1) || ((index =
                 * lwContents.indexOf("http-equiv=\"refresh\"")) != -1)) {
                 * if ((i = lwContents.indexOf("content=", index + 20)) !=
                 * -1) { char c = lwContents.charAt(i+8); if ((j =
                 * lwContents.indexOf("url=", i)) != -1) { if ((k =
                 * lwContents.indexOf(c, j + 1)) != -1) { newuri =
                 * lwContents.substring(j+4, k); redirectUrl =
                 * getAbsoluteUrl(method,newuri);
                 * Engine.logBeans.debug("(HttpConnector) Redirecting to : "
                 * + redirectUrl); redirectMethod = new
                 * GetMethod(redirectUrl);
                 * 
                 * // set headers for (z=0; z<requestHeaders.length; z++)
                 * redirectMethod.setRequestHeader(requestHeaders[z]);
                 * 
                 * referer = redirectUrl; result =
                 * executeMethod(redirectMethod, context); // recurse } } }
                 * } // Handles FRAMESET else if
                 * (lwContents.indexOf("frameset") != -1) {
                 * Engine.logBeans.debug
                 * ("(HttpConnector) Analyzing frameset...");
                 * StringTokenizer st = new StringTokenizer(lwContents);
                 * StringEx newcontents = new StringEx(lwContents); while
                 * (st.hasMoreTokens()) { String token = st.nextToken();
                 * String uri; if (token.startsWith("src=")) { if
                 * ((token.indexOf("\"") != -1) || (token.indexOf("'") !=
                 * -1)) { token = token.substring(5); uri =
                 * token.substring(0,token.length()-1); newuri =
                 * getAbsoluteUrl(method,uri);
                 * Engine.logBeans.trace("(HttpConnector) Replaced uri ("+
                 * uri +") with newuri("+ newuri +")");
                 * 
                 * newcontents.replaceAll(token,newuri); } } }
                 * Engine.logBeans
                 * .trace("(HttpConnector) New response content:\n"+
                 * newcontents); result = newcontents.toString().getBytes();
                 * }
                 */
            }
        }
        //Added by julienda - #3433 - 04/03/2013
        AbstractHttpTransaction abstractHttpTransaction = (AbstractHttpTransaction) context.transaction;

        if (abstractHttpTransaction.getHttpInfo()) {
            Document doc = context.outputDocument;

            //Remove the node HTTPInfo if we have a redirect
            NodeList nodeList = XMLUtils.findElements(context.outputDocument.getDocumentElement(),
                    abstractHttpTransaction.getHttpInfoTagName());
            if (nodeList != null) {
                XMLUtils.removeNodeListContent(nodeList);
            }

            //Parent Element
            httpInfoElement = doc.createElement(abstractHttpTransaction.getHttpInfoTagName());

            //Add requested URL
            Element urlElement = doc.createElement("url");
            urlElement.setTextContent(method.getURI().toString());
            httpInfoElement.appendChild(urlElement);

            //Add status code
            Element httpStatusElement = doc.createElement("status");

            httpStatusElement.setAttribute("code", Integer.toString(statuscode));
            httpStatusElement.setAttribute("text", method.getStatusText());
            httpInfoElement.appendChild(httpStatusElement);

            //We add headers informations

            List<Header> headers = Arrays.asList(requestHeaders);
            if (!headers.isEmpty()) {
                Element httpHeadersElement = doc.createElement("headers");

                for (int i = 0; i < headers.size(); i++) {
                    Element elt = doc.createElement("header");
                    elt.setAttribute("name", headers.get(i).getName());
                    elt.setAttribute("value", headers.get(i).getValue());
                    httpHeadersElement.appendChild(elt);
                }
                httpInfoElement.appendChild(httpHeadersElement);
            }

            // we add response header information
            if (responseHeaders.length != 0) {
                Element httpHeadersElement = doc.createElement("responseHeaders");

                for (int i = 0; i < responseHeaders.length; i++) {
                    Element elt = doc.createElement("header");
                    elt.setAttribute("name", responseHeaders[i].getName());
                    elt.setAttribute("value", responseHeaders[i].getValue());
                    httpHeadersElement.appendChild(elt);
                }
                httpInfoElement.appendChild(httpHeadersElement);
            }

            doc.getDocumentElement().appendChild(httpInfoElement);
        }
    } finally {
        method.releaseConnection();
    }

    return result;
}