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

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

Introduction

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

Prototype

int SC_SEE_OTHER

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

Click Source Link

Document

<tt>303 See Other</tt> (HTTP/1.1 - RFC 2616)

Usage

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

/**
 * Authenticate the client http state so that the colony requests can be made.
 *
 * @param baseURL URL requested for colony
 * @param client  HttpClient instance/* w w w. j  a v a2  s.  c  om*/
 *
 * @return true if authentication succeeded.
 *
 * @throws com.dtolabs.client.utils.HttpClientException
 *
 */
public boolean authenticate(final URL baseURL, final HttpClient client) throws HttpClientException {
    final HttpState state = client.getState();
    if (hasSessionCookie(baseURL, state, basePath)) {
        return true;
    }
    final byte[] buffer = new byte[1024];

    boolean doPostLogin = false;
    boolean isLoginFormContent = false;
    logger.debug("No session found, must login...");
    try {
        final URL newUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(),
                basePath + getInitialPath());

        //load welcome page, which should forward to form based logon page.
        final GetMethod get = new GetMethod(newUrl.toExternalForm());
        get.setDoAuthentication(false);
        get.setFollowRedirects(false);
        logger.debug("Requesting: " + newUrl);
        int res = client.executeMethod(get);
        logger.debug("Result is: " + res);

        /*
          Tomcat container auth behaves differently than Jetty.  Tomcat will respond 200 OK and include the login form
          when auth is required, as well as on auth failure, it will also require complete GET of original URL after
          successful auth.
          Jetty will redirect to login page when auth is required, and will redirect to error page on failure.
         */

        String body = get.getResponseBodyAsString();
        if (null != body && body.contains(J_SECURITY_CHECK) && body.contains(JAVA_USER_PARAM)
                && body.contains(JAVA_PASS_PARAM)) {
            isLoginFormContent = true;
        }
        get.releaseConnection();

        if ((res == HttpStatus.SC_UNAUTHORIZED)) {
            if (get.getResponseHeader("WWW-Authenticate") != null
                    && get.getResponseHeader("WWW-Authenticate").getValue().matches("^Basic.*")) {
                logger.warn("Form-based login received UNAUTHORIZED, trying to use Basic authentication");
                final BasicAuthenticator auth = new BasicAuthenticator(username, password);
                return auth.authenticate(baseURL, client);
            } else {
                throw new HttpClientException(
                        "Form-based login received UNAUTHORIZED, but didn't recognize it as Basic authentication: unable to get a session");
            }

        }
        //should now have the proper session cookie
        if (!hasSessionCookie(baseURL, state, basePath)) {
            throw new HttpClientException("Unable to get a session from URL : " + newUrl);
        }
        if (res == HttpStatus.SC_OK && isLoginFormContent) {
            doPostLogin = true;
        } else if ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY)
                || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT)) {
            Header locHeader = get.getResponseHeader("Location");
            if (locHeader == null) {
                throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl);
            }
            String location = locHeader.getValue();
            if (!isValidLoginRedirect(get)) {
                //unexpected response
                throw new HttpClientException("Unexpected redirection when getting session: " + location);
            }
            logger.debug("Follow redirect: " + res + ": " + location);

            final GetMethod redir = new GetMethod(location);
            redir.setFollowRedirects(true);
            res = client.executeMethod(redir);
            InputStream ins = redir.getResponseBodyAsStream();
            while (ins.available() > 0) {
                //read and discard response body
                ins.read(buffer);
            }
            redir.releaseConnection();

            if (res != HttpStatus.SC_OK) {
                throw new HttpClientException("Login page status was not OK: " + res);
            }
            logger.debug("Result: " + res);

            doPostLogin = true;
        } else if (res != HttpStatus.SC_OK) {
            //if request to welcome page was OK, we figure that the session is already set
            throw new HttpClientException("Request to welcome page returned error: " + res + ": " + get);
        }
        if (doPostLogin) {
            //now post login
            final URL loginUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(),
                    basePath + JAVA_AUTH_PATH);

            final PostMethod login = new PostMethod(loginUrl.toExternalForm());
            login.setRequestBody(new NameValuePair[] { new NameValuePair(JAVA_USER_PARAM, getUsername()),
                    new NameValuePair(JAVA_PASS_PARAM, getPassword()) });

            login.setFollowRedirects(false);
            logger.debug("Post login info to URL: " + loginUrl);

            res = client.executeMethod(login);

            final InputStream ins = login.getResponseBodyAsStream();
            while (ins.available() > 0) {
                //read and discard response body
                ins.read(buffer);
            }
            login.releaseConnection();

            Header locHeader = login.getResponseHeader("Location");
            String location = null != locHeader ? locHeader.getValue() : null;
            if (isLoginError(login)) {
                logger.error("Form-based auth failed");
                return false;
            } else if (null != location && !location.equals(newUrl.toExternalForm())) {

                logger.warn("Form-based auth succeeded, but last URL was unexpected");
            }
            if (isFollowLoginRedirect()
                    && ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY)
                            || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT))) {

                if (location == null) {
                    throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl);
                }
                final GetMethod get2 = new GetMethod(location);
                //                    logger.debug("Result: " + res + ": " + location + ", following redirect");
                res = client.executeMethod(get2);
            } else if (res != HttpStatus.SC_OK) {
                throw new HttpClientException(
                        "Login didn't seem to work: " + res + ": " + login.getResponseBodyAsString());
            }
            logger.debug("Result: " + res);
        }
    } catch (MalformedURLException e) {
        throw new HttpClientException("Bad URL", e);
    } catch (HttpException e) {
        throw new HttpClientException("HTTP Error: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new HttpClientException(
                "Error occurred while trying to authenticate to server: " + e.getMessage(), e);
    }

    return true;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Check if status is a redirect (various 30x values).
 *
 * @param status Http status/*w  ww .  j  a  va 2 s.  c o m*/
 * @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:com.cloud.network.bigswitch.BigSwitchBcfApi.java

private String checkResponse(final HttpMethodBase m, final String errorMessageBase)
        throws BigSwitchBcfApiException, IllegalArgumentException {
    String customErrorMsg = null;
    if (m.getStatusCode() == HttpStatus.SC_OK) {
        String hash = "";
        if (m.getResponseHeader(HASH_MATCH) != null) {
            hash = m.getResponseHeader(HASH_MATCH).getValue();
            set_hash(hash);//from   w  w w .  j av a 2 s.  co  m
        }
        return hash;
    }
    if (m.getStatusCode() == HttpStatus.SC_CONFLICT) {
        if (m instanceof GetMethod) {
            return HASH_CONFLICT;
        }
        throw new BigSwitchBcfApiException("BCF topology sync required", true);
    }
    if (m.getStatusCode() == HttpStatus.SC_SEE_OTHER) {
        isMaster = false;
        set_hash(HASH_IGNORE);
        return HASH_IGNORE;
    }
    if (m.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
        if (m instanceof DeleteMethod) {
            return "";
        }
    }
    if (m.getStatusCode() == HttpStatus.SC_BAD_REQUEST) {
        customErrorMsg = " Invalid data in BCF request";
        throw new IllegalArgumentException(customErrorMsg);
    }
    String errorMessage = responseToErrorMessage(m);
    m.releaseConnection();
    S_LOGGER.error(errorMessageBase + errorMessage);
    throw new BigSwitchBcfApiException(errorMessageBase + errorMessage + customErrorMsg);
}

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());
        }// w w  w.  j av a 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:edu.ucsb.eucalyptus.transport.Axis2InOutMessageReceiver.java

public void invokeBusinessLogic(MessageContext msgContext, MessageContext newMsgContext) throws AxisFault {
    String methodName = this.findOperation(msgContext);
    Class serviceMethodArgType = this.findArgumentClass(methodName);

    SOAPFactory factory = this.getSOAPFactory(msgContext);
    OMElement msgBodyOm = msgContext.getEnvelope().getBody().getFirstElement();

    String bindingName = this.findBindingName(msgBodyOm);
    EucalyptusMessage wrappedParam = this.bindMessage(methodName, serviceMethodArgType, msgBodyOm, bindingName);

    HttpRequest httprequest = (HttpRequest) msgContext.getProperty(GenericHttpDispatcher.HTTP_REQUEST);
    if (httprequest == null) {
        this.verifyUser(msgContext, wrappedParam);
    } else {//  w  w  w.j av  a2 s  . c  om
        bindingName = httprequest.getBindingName();
        Policy p = new Policy();
        newMsgContext.setProperty(RampartMessageData.KEY_RAMPART_POLICY, p);
        //:: fixes the handling of certain kinds of client brain damage :://
        if (httprequest.isPureClient()) {
            if (wrappedParam instanceof ModifyImageAttributeType) {
                ModifyImageAttributeType pure = ((ModifyImageAttributeType) wrappedParam);
                pure.setImageId(purifyImageIn(pure.getImageId()));
            } else if (wrappedParam instanceof DescribeImageAttributeType) {
                DescribeImageAttributeType pure = ((DescribeImageAttributeType) wrappedParam);
                pure.setImageId(purifyImageIn(pure.getImageId()));
            } else if (wrappedParam instanceof ResetImageAttributeType) {
                ResetImageAttributeType pure = ((ResetImageAttributeType) wrappedParam);
                pure.setImageId(purifyImageIn(pure.getImageId()));
            } else if (wrappedParam instanceof DescribeImagesType) {
                ArrayList<String> strs = Lists.newArrayList();
                for (String imgId : ((DescribeImagesType) wrappedParam).getImagesSet()) {
                    strs.add(purifyImageIn(imgId));
                }
                ((DescribeImagesType) wrappedParam).setImagesSet(strs);
            } else if (wrappedParam instanceof DeregisterImageType) {
                DeregisterImageType pure = ((DeregisterImageType) wrappedParam);
                pure.setImageId(purifyImageIn(pure.getImageId()));
            } else if (wrappedParam instanceof RunInstancesType) {
                RunInstancesType pure = ((RunInstancesType) wrappedParam);
                pure.setImageId(purifyImageIn(pure.getImageId()));
                pure.setKernelId(purifyImageIn(pure.getKernelId()));
                pure.setRamdiskId(purifyImageIn(pure.getRamdiskId()));
            }
        }

    }

    MuleMessage message = this.invokeService(methodName, wrappedParam);

    if (message == null)
        throw new AxisFault("Received a NULL response. This is a bug -- it should NEVER happen.");

    this.checkException(message);

    if (httprequest != null) {
        //:: fixes the handling of certain kinds of client brain damage :://
        if (httprequest.isPureClient()) {
            if (message.getPayload() instanceof DescribeImagesResponseType) {
                DescribeImagesResponseType purify = (DescribeImagesResponseType) message.getPayload();
                for (ImageDetails img : purify.getImagesSet()) {
                    img.setImageId(img.getImageId().replaceFirst("^e", "a").toLowerCase());
                    if (img.getKernelId() != null)
                        img.setKernelId(img.getKernelId().replaceFirst("^e", "a").toLowerCase());
                    if (img.getRamdiskId() != null)
                        img.setRamdiskId(img.getRamdiskId().replaceFirst("^e", "a").toLowerCase());
                }
            } else if (message.getPayload() instanceof DescribeInstancesResponseType) {
                DescribeInstancesResponseType purify = (DescribeInstancesResponseType) message.getPayload();
                for (ReservationInfoType rsvInfo : purify.getReservationSet()) {
                    for (RunningInstancesItemType r : rsvInfo.getInstancesSet()) {
                        r.setImageId(r.getImageId().replaceFirst("^e", "a").toLowerCase());
                        if (r.getKernel() != null)
                            r.setKernel(r.getKernel().replaceFirst("^e", "a").toLowerCase());
                        if (r.getRamdisk() != null)
                            r.setRamdisk(r.getRamdisk().replaceFirst("^e", "a").toLowerCase());
                    }
                }
            }

        }
    }

    if (newMsgContext != null) {
        SOAPEnvelope envelope = generateMessage(methodName, factory, bindingName, message.getPayload(),
                httprequest == null ? null : httprequest.getOriginalNamespace());
        newMsgContext.setEnvelope(envelope);
    }

    newMsgContext.setProperty(Axis2HttpWorker.REAL_HTTP_REQUEST,
            msgContext.getProperty(Axis2HttpWorker.REAL_HTTP_REQUEST));
    newMsgContext.setProperty(Axis2HttpWorker.REAL_HTTP_RESPONSE,
            msgContext.getProperty(Axis2HttpWorker.REAL_HTTP_RESPONSE));

    LOG.info("Returning reply: " + message.getPayload());

    if (message.getPayload() instanceof WalrusErrorMessageType) {
        WalrusErrorMessageType errorMessage = (WalrusErrorMessageType) message.getPayload();
        msgContext.setProperty(Axis2HttpWorker.HTTP_STATUS, errorMessage.getHttpCode());
        newMsgContext.setProperty(Axis2HttpWorker.HTTP_STATUS, errorMessage.getHttpCode());
        //This selects the data formatter
        newMsgContext.setProperty("messageType", "application/walrus");
        return;
    }

    Boolean putType = (Boolean) msgContext.getProperty(WalrusProperties.STREAMING_HTTP_PUT);
    Boolean getType = (Boolean) msgContext.getProperty(WalrusProperties.STREAMING_HTTP_GET);

    if (getType != null || putType != null) {
        WalrusDataResponseType reply = (WalrusDataResponseType) message.getPayload();
        AxisHttpResponse response = (AxisHttpResponse) msgContext
                .getProperty(Axis2HttpWorker.REAL_HTTP_RESPONSE);
        response.addHeader(new BasicHeader("Last-Modified", reply.getLastModified()));
        response.addHeader(new BasicHeader("ETag", '\"' + reply.getEtag() + '\"'));
        if (getType != null) {
            newMsgContext.setProperty(WalrusProperties.STREAMING_HTTP_GET, getType);
            WalrusDataRequestType request = (WalrusDataRequestType) wrappedParam;
            Boolean isCompressed = request.getIsCompressed();
            if (isCompressed == null)
                isCompressed = false;
            if (isCompressed) {
                newMsgContext.setProperty("GET_COMPRESSED", isCompressed);
            } else {
                Long contentLength = reply.getSize();
                response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, String.valueOf(contentLength)));
            }
            List<MetaDataEntry> metaData = reply.getMetaData();
            for (MetaDataEntry metaDataEntry : metaData) {
                response.addHeader(
                        new BasicHeader(WalrusProperties.AMZ_META_HEADER_PREFIX + metaDataEntry.getName(),
                                metaDataEntry.getValue()));
            }
            if (getType.equals(Boolean.TRUE)) {
                newMsgContext.setProperty("GET_KEY", request.getBucket() + "." + request.getKey());
                newMsgContext.setProperty("GET_RANDOM_KEY", request.getRandomKey());
            }
            //This selects the data formatter
            newMsgContext.setProperty("messageType", "application/walrus");
        } else if (putType != null) {
            if (reply instanceof PostObjectResponseType) {
                PostObjectResponseType postReply = (PostObjectResponseType) reply;
                String redirectUrl = postReply.getRedirectUrl();
                if (redirectUrl != null) {
                    response.addHeader(new BasicHeader("Location", redirectUrl));
                    msgContext.setProperty(Axis2HttpWorker.HTTP_STATUS, HttpStatus.SC_SEE_OTHER);
                    newMsgContext.setProperty(Axis2HttpWorker.HTTP_STATUS, HttpStatus.SC_SEE_OTHER);
                    newMsgContext.setProperty("messageType", "application/walrus");
                } else {
                    Integer successCode = postReply.getSuccessCode();
                    if (successCode != null) {
                        newMsgContext.setProperty(Axis2HttpWorker.HTTP_STATUS, successCode);
                        if (successCode == 201) {
                            return;
                        } else {
                            newMsgContext.setProperty("messageType", "application/walrus");
                            return;
                        }

                    }
                }
            }
            response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, String.valueOf(0)));
        }
    }

}

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   w ww.  j a v a  2  s .co 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:com.twinsoft.convertigo.eclipse.editors.connector.HtmlConnectorDesignComposite.java

public void modelChanged(HttpProxyEvent event) {
    if (!checkProxySource(event)) {
        return;/* w ww.  j  a  va  2 s. c om*/
    }

    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: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;//from   www .  j  av  a  2 s  . 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 {/*ww  w.  j  a  v  a  2  s.  co m*/
            return false;
        }
    default:
        return false;
    }
}

From source file:org.apache.commons.httpclient.demo.RedirectDemo.java

public static void main(String[] args) {
    HttpClient client = new HttpClient();
    //// ww  w. j av  a 2  s. c om
    //client.getHostConfiguration().setProxy("90.0.12.21", 808);
    //client.getHostConfiguration().setHost("www.imobile.com.cn", 80, "http");

    PostMethod post = new PostMethod("http://90.0.12.20:8088/NationWideAdmin/test/RedirectDemo.jsp");

    try {
        client.executeMethod(post);
    } catch (IOException ex) {
    }

    System.out.println(post.getStatusLine().toString());

    post.releaseConnection();

    //

    int statuscode = post.getStatusCode();
    /*
             
              HttpServletResponse
              
            
             301
              SC_MOVED_PERMANENTLY
              
            
             302
              SC_MOVED_TEMPORARILY
              
            
             303
              SC_SEE_OTHER
              URL
            
             307
              SC_TEMPORARY_REDIRECT
              SC_MOVED_TEMPORARILY
    */
    System.out.println("" + statuscode);
    System.out.println("HttpStatus.SC_MOVED_TEMPORARILY" + HttpStatus.SC_MOVED_TEMPORARILY);
    System.out.println("HttpStatus.SC_MOVED_PERMANENTLY" + HttpStatus.SC_MOVED_PERMANENTLY);
    System.out.println("HttpStatus.SC_SEE_OTHER" + HttpStatus.SC_SEE_OTHER);
    System.out.println("HttpStatus.SC_TEMPORARY_REDIRECT" + HttpStatus.SC_TEMPORARY_REDIRECT);
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        //URL
        Header header = post.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }

            GetMethod redirect = new GetMethod(newuri);

            try {
                client.executeMethod(redirect);
            } catch (IOException ex1) {
            }

            System.out.println("Redirect:" + redirect.getStatusLine().toString());

            redirect.releaseConnection();
        } else {
            System.out.println("Invalid redirect");
        }
    }
}