Example usage for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY

List of usage examples for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY.

Prototype

int SC_MOVED_PERMANENTLY

To view the source code for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY.

Click Source Link

Document

<tt>301 Moved Permanently</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Check if status is a redirect (various 30x values).
 *
 * @param status Http status//from  w  w  w.j a v a2  s  . c  om
 * @return true if status is a redirect
 */
public static boolean isRedirect(int status) {
    return status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY
            || status == HttpStatus.SC_SEE_OTHER || status == HttpStatus.SC_TEMPORARY_REDIRECT;
}

From source file:JiraWebSession.java

private HostConfiguration login(HttpClient httpClient, IProgressMonitor monitor) throws JiraException {
    RedirectTracker tracker = new RedirectTracker();

    final String restLogin = "/rest/gadget/1.0/login"; //$NON-NLS-1$ // JIRA 4.x has additional endpoint for login that tells if CAPTCHA limit was hit
    final String loginAction = "/secure/Dashboard.jspa"; //$NON-NLS-1$;
    boolean jira4x = true;

    for (int i = 0; i <= MAX_REDIRECTS; i++) {
        AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
        if (credentials == null) {
            // TODO prompt user?
            credentials = new AuthenticationCredentials("", ""); //$NON-NLS-1$ //$NON-NLS-2$
        }/*w  w  w.ja  v  a 2 s .c o m*/

        String url = baseUrl + (jira4x ? restLogin : loginAction);

        PostMethod login = new PostMethod(url);
        login.setFollowRedirects(false);
        login.setRequestHeader("Content-Type", getContentType()); //$NON-NLS-1$
        login.addParameter("os_username", credentials.getUserName()); //$NON-NLS-1$
        login.addParameter("os_password", credentials.getPassword()); //$NON-NLS-1$
        login.addParameter("os_destination", "/success"); //$NON-NLS-1$ //$NON-NLS-2$

        tracker.addUrl(url);

        try {
            HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location,
                    monitor);
            int statusCode = WebUtil.execute(httpClient, hostConfiguration, login, monitor);

            if (statusCode == HttpStatus.SC_NOT_FOUND) {
                jira4x = false;
                continue;
            }

            if (needsReauthentication(httpClient, login, monitor)) {
                continue;
            } else if (statusCode != HttpStatus.SC_MOVED_TEMPORARILY
                    && statusCode != HttpStatus.SC_MOVED_PERMANENTLY) {
                throw new JiraServiceUnavailableException("Unexpected status code during login: " + statusCode); //$NON-NLS-1$
            }

            tracker.addRedirect(url, login, statusCode);

            this.characterEncoding = login.getResponseCharSet();

            Header locationHeader = login.getResponseHeader("location"); //$NON-NLS-1$
            if (locationHeader == null) {
                throw new JiraServiceUnavailableException("Invalid redirect, missing location"); //$NON-NLS-1$
            }
            url = locationHeader.getValue();
            tracker.checkForCircle(url);
            if (!insecureRedirect && isSecure() && url.startsWith("http://")) { //$NON-NLS-1$
                tracker.log("Redirect to insecure location during login to repository: " + client.getBaseUrl()); //$NON-NLS-1$
                insecureRedirect = true;
            }
            if (url.endsWith("/success")) { //$NON-NLS-1$
                String newBaseUrl = url.substring(0, url.lastIndexOf("/success")); //$NON-NLS-1$
                if (baseUrl.equals(newBaseUrl) || !client.getLocalConfiguration().getFollowRedirects()) {
                    // success
                    addAuthenticationCookie(httpClient, login);
                    return hostConfiguration;
                } else {
                    // need to login to make sure HttpClient picks up the session cookie
                    baseUrl = newBaseUrl;
                }
            }
        } catch (IOException e) {
            throw new JiraServiceUnavailableException(e);
        } finally {
            login.releaseConnection();
        }
    }

    tracker.log(
            "Exceeded maximum number of allowed redirects during login to repository: " + client.getBaseUrl()); //$NON-NLS-1$

    throw new JiraServiceUnavailableException("Exceeded maximum number of allowed redirects during login"); //$NON-NLS-1$
}

From source file:com.dtolabs.client.utils.HttpClientChannel.java

private HttpMethod checkFollowRedirect(final HttpMethod method, final int res)
        throws IOException, HttpClientException {

    if ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY)
            || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        final Header locHeader = method.getResponseHeader("Location");
        if (locHeader == null) {
            throw new HttpClientException("Redirect with no Location header, request URL: " + method.getURI());
        }/* www .ja va 2s. c  o m*/
        final String location = locHeader.getValue();
        logger.debug("Follow redirect: " + res + ": " + location);

        method.releaseConnection();
        final GetMethod followMethod = new GetMethod(location);
        followMethod.setFollowRedirects(true);
        resultCode = httpc.executeMethod(followMethod);
        reasonCode = followMethod.getStatusText();
        logger.debug("Result: " + resultCode);
        return followMethod;
    }
    return method;
}

From source file:com.jaspersoft.jasperserver.war.common.HeartbeatBean.java

private synchronized void httpCall(String url, HeartbeatContributor contributor) {
    if (log.isDebugEnabled())
        log.debug("Heartbeat calling: " + url);

    HttpClient httpClient = new HttpClient();

    PostMethod post = new PostMethod(url);

    try {/*from   ww w . j  a  va  2  s .c o  m*/
        if (heartbeatId != null) {
            post.addParameter("id", heartbeatId);
        }

        if (contributor != null) {
            contributor.contributeToHttpCall(post);
        }

        int statusCode = httpClient.executeMethod(post);
        if (statusCode == HttpStatus.SC_OK) {
            if (heartbeatId == null) {
                heartbeatId = post.getResponseBodyAsString();
                heartbeatId = heartbeatId == null ? null : heartbeatId.trim();

                localIdProperties.setProperty(PROPERTY_HEARTBEAT_ID, heartbeatId);

                saveLocalIdProperties();
            }
        } else if (
        //supported types of redirect
        statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                || statusCode == HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header header = post.getResponseHeader("location");
            if (header != null) {
                if (log.isDebugEnabled())
                    log.debug("Heartbeat listener redirected.");

                httpCall(header.getValue(), contributor);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Heartbeat listener redirected to unknown destination.");
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Connecting to heartbeat listener URL failed. Status code: " + statusCode);
        }
    } catch (IOException e) {
        if (log.isDebugEnabled())
            log.debug("Connecting to heartbeat listener URL failed.", e);
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();

        clearCache();
    }
}

From source file:davmail.caldav.TestCaldav.java

public void testWellKnown() throws IOException, DavException {
    DavPropertyNameSet davPropertyNameSet = new DavPropertyNameSet();
    davPropertyNameSet.add(DavPropertyName.create("current-user-principal", Namespace.getNamespace("DAV:")));
    davPropertyNameSet.add(DavPropertyName.create("principal-URL", Namespace.getNamespace("DAV:")));
    davPropertyNameSet.add(DavPropertyName.create("resourcetype", Namespace.getNamespace("DAV:")));
    PropFindMethod method = new PropFindMethod("/.well-known/caldav", davPropertyNameSet, 0);
    httpClient.executeMethod(method);/*from   w  w  w.j  a v a2 s.co  m*/
    assertEquals(HttpStatus.SC_MOVED_PERMANENTLY, method.getStatusCode());
}

From source file:com.twinsoft.convertigo.eclipse.editors.connector.HtmlConnectorDesignComposite.java

public void modelChanged(HttpProxyEvent event) {
    if (!checkProxySource(event)) {
        return;/*from  w ww  .  ja  v a2  s. c o  m*/
    }

    String requestString = event.getRequest();
    String responseString = event.getResponse();
    boolean https = event.isHttps();
    int status = Integer.parseInt(event.getStatus());

    // do not record client redirection
    if ((status == HttpStatus.SC_MOVED_TEMPORARILY) || (status == HttpStatus.SC_MOVED_PERMANENTLY)
            || (status == HttpStatus.SC_SEE_OTHER) || (status == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        return;
    }

    /*if (requestString.indexOf(getServer()) == -1) {
       return;
    }*/

    Map<String, String> headers = parseResponseString(responseString);
    String contentType = headers.get(HeaderName.ContentType.value().toLowerCase());

    // record only text/html or null Content-Type ...
    if (contentType == null) {
        return;
    }

    if (MimeType.Html.is(contentType) && MimeType.Plain.is(contentType)) {
        return;
    }

    ConvertigoPlugin.logDebug2("(HtmlConnectorDesignComposite) Learning statement...");

    try {
        String url, method, handlerName, transactionName, statementName, scHandlerName;
        String normalizedScreenClassName, screenClassName;
        HtmlTransaction htmlTransaction = null;
        HTTPStatement httpStatement = null;
        HtmlScreenClass htmlScreenClass = null;
        HandlerStatement handlerStatement = null;
        ScHandlerStatement scHandlerStatement = null;
        //Document dom = null;
        //Log log = null;
        int size, index1;
        boolean bContinue;

        index1 = 0;
        bContinue = true;
        normalizedScreenClassName = "Unknown";

        htmlTransaction = (HtmlTransaction) htmlConnector.getLearningTransaction();

        synchronized (htmlConnector) {
            //dom = htmlConnector.getCurrentXmlDocument();
            htmlScreenClass = htmlConnector.getCurrentScreenClass();
        }

        screenClassName = htmlScreenClass.getName();
        normalizedScreenClassName = StringUtils.normalize(htmlScreenClass.getName());
        ConvertigoPlugin
                .logDebug2("(HtmlConnectorDesignComposite) current screen class is '" + screenClassName + "'");

        if (htmlTransaction != null) {
            transactionName = htmlTransaction.getName();

            ConvertigoPlugin.logDebug2("(HtmlConnectorDesignComposite) creating new HTTPStatement");
            ConvertigoPlugin.logDebug2(requestString);

            httpStatement = parseRequestString(requestString);
            httpStatement.setHttps(https);
            httpStatement.setPort(https ? 443 : 80);
            method = httpStatement.getMethod().toLowerCase();
            //size = httpStatement.getVariablesDefinitionSize();
            size = httpStatement.numberOfVariables();
            url = httpStatement.getUrl(htmlConnector.isHttps(), htmlConnector.getServer(),
                    htmlConnector.getPort());

            while (bContinue) {
                statementName = method + ((index1 == 0) ? " " : " " + index1) + " (" + url + " - " + size + ")";
                statementName = StringUtils.normalize(statementName);
                httpStatement.setName(statementName);
                httpStatement.hasChanged = true;
                httpStatement.bNew = true;

                if (htmlScreenClass == null) {
                    try {
                        httpStatement.priority = 0;
                        htmlTransaction.addStatement(httpStatement);
                        ConvertigoPlugin.logDebug2(
                                "(HtmlConnectorDesignComposite) added new HTTPStatement to default transaction '"
                                        + transactionName + "'");
                        fireObjectChanged(new CompositeEvent(htmlTransaction));
                        Engine.theApp.fireObjectDetected(new EngineEvent(httpStatement));

                        bContinue = false;
                    } catch (ObjectWithSameNameException owsne) {
                        index1++;
                    }
                } else {
                    if (htmlConnector.isAccumulating())
                        handlerName = "on" + normalizedScreenClassName + "Exit";
                    else
                        handlerName = "on" + normalizedScreenClassName + "Entry";

                    handlerStatement = htmlTransaction.getHandlerStatement(handlerName);
                    if (handlerStatement != null) {
                        try {
                            handlerStatement.addStatement(httpStatement);
                            ConvertigoPlugin.logDebug2(
                                    "(HtmlConnectorDesignComposite) added new HTTPStatement to handler '"
                                            + handlerName + "' of transaction '" + transactionName + "'");
                            fireObjectChanged(new CompositeEvent(handlerStatement));
                            Engine.theApp.fireObjectDetected(new EngineEvent(httpStatement));

                            bContinue = false;
                        } catch (ObjectWithSameNameException owsne) {
                            index1++;
                        }
                    } else {
                        try {
                            if (htmlConnector.isAccumulating())
                                scHandlerStatement = new ScExitHandlerStatement(normalizedScreenClassName);
                            else
                                scHandlerStatement = new ScEntryHandlerStatement(normalizedScreenClassName);
                            scHandlerName = scHandlerStatement.getName();
                            scHandlerStatement.setName(scHandlerName);
                            scHandlerStatement.hasChanged = true;
                            scHandlerStatement.bNew = true;

                            scHandlerStatement.priority = 0;
                            htmlTransaction.addStatement(scHandlerStatement);
                            ConvertigoPlugin.logDebug2(
                                    "(HtmlConnectorDesignComposite) added new ScExitHandlerStatement '"
                                            + handlerName + "' of transaction '" + transactionName + "'");

                            try {
                                scHandlerStatement.addStatement(httpStatement);
                                ConvertigoPlugin
                                        .logDebug2("(HtmlConnectorDesignComposite) added new HTTPStatement '"
                                                + statementName + "' to ScExitHandlerStatement '" + handlerName
                                                + "'");
                                fireObjectChanged(new CompositeEvent(htmlTransaction));
                                Engine.theApp.fireObjectDetected(new EngineEvent(httpStatement));

                                bContinue = false;
                            } catch (ObjectWithSameNameException owsne) {
                                index1++;
                            }
                        }
                        // Should not append
                        catch (ObjectWithSameNameException owsne) {
                            throw new EngineException(owsne.getMessage());
                        }
                    }
                }
            }
        } else {
            throw new EngineException("Found none learning transaction");
        }

    } catch (EngineException e) {
        ConvertigoPlugin.logException(e, "An exception occured while learning");
    }

}

From source file:davmail.caldav.CaldavConnection.java

/**
 * Send caldav response for /.well-known/ request.
 *
 * @throws IOException on error/*from  ww w .  ja v a 2s  .  c  o  m*/
 */
public void sendWellKnown() throws IOException {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Location", "/");
    sendHttpResponse(HttpStatus.SC_MOVED_PERMANENTLY, headers);
}

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. ja va2s.  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;
}

From source file:org.alfresco.httpclient.AbstractHttpClient.java

private boolean isRedirect(HttpMethod method) {
    switch (method.getStatusCode()) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        if (method.getFollowRedirects()) {
            return true;
        } else {/*from  www  .  j a v a 2  s . com*/
            return false;
        }
    default:
        return false;
    }
}

From source file:org.alfresco.repo.search.impl.solr.SolrAdminHTTPClient.java

public JSONObject execute(String relativeHandlerPath, HashMap<String, String> args) {
    ParameterCheck.mandatory("relativeHandlerPath", relativeHandlerPath);
    ParameterCheck.mandatory("args", args);

    String path = getPath(relativeHandlerPath);
    try {/*  w w w.jav a  2  s  .  c  o m*/
        URLCodec encoder = new URLCodec();
        StringBuilder url = new StringBuilder();

        for (String key : args.keySet()) {
            String value = args.get(key);
            if (url.length() == 0) {
                url.append(path);
                url.append("?");
                url.append(encoder.encode(key, "UTF-8"));
                url.append("=");
                url.append(encoder.encode(value, "UTF-8"));
            } else {
                url.append("&");
                url.append(encoder.encode(key, "UTF-8"));
                url.append("=");
                url.append(encoder.encode(value, "UTF-8"));
            }

        }

        // PostMethod post = new PostMethod(url.toString());
        GetMethod get = new GetMethod(url.toString());

        try {
            httpClient.executeMethod(get);

            if (get.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                    || get.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                Header locationHeader = get.getResponseHeader("location");
                if (locationHeader != null) {
                    String redirectLocation = locationHeader.getValue();
                    get.setURI(new URI(redirectLocation, true));
                    httpClient.executeMethod(get);
                }
            }

            if (get.getStatusCode() != HttpServletResponse.SC_OK) {
                throw new LuceneQueryParserException(
                        "Request failed " + get.getStatusCode() + " " + url.toString());
            }

            Reader reader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
            // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
            JSONObject json = new JSONObject(new JSONTokener(reader));
            return json;
        } finally {
            get.releaseConnection();
        }
    } catch (UnsupportedEncodingException e) {
        throw new LuceneQueryParserException("", e);
    } catch (HttpException e) {
        throw new LuceneQueryParserException("", e);
    } catch (IOException e) {
        throw new LuceneQueryParserException("", e);
    } catch (JSONException e) {
        throw new LuceneQueryParserException("", e);
    }
}