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

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

Introduction

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

Prototype

int SC_MOVED_TEMPORARILY

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

Click Source Link

Document

<tt>302 Moved Temporarily</tt> (Sometimes <tt>Found</tt>) (HTTP/1.0 - RFC 1945)

Usage

From source file:org.svenk.redmine.core.client.AbstractRedmineClient.java

public int createTicket(String project, Map<String, String> postValues, IProgressMonitor monitor)
        throws RedmineException {
    PostMethod method = new PostMethod(String.format(REDMINE_URL_TICKET_NEW, project));

    List<NameValuePair> values = this.ticket2HttpData(postValues);
    method.addParameters(values.toArray(new NameValuePair[values.size()]));

    String errorMsg = executeMethod(method, submitErrorParser, monitor, HttpStatus.SC_OK,
            HttpStatus.SC_MOVED_TEMPORARILY);
    if (errorMsg == null) {
        //TODO PRFEN !!!
        Header respHeader = method.getResponseHeader(HEADER_REDIRECT);
        if (respHeader != null) {
            String location = respHeader.getValue();

            Matcher m = Pattern.compile("(\\d+)$").matcher(location); //$NON-NLS-1$
            if (m.find()) {
                try {
                    return Integer.parseInt(m.group(1));
                } catch (NumberFormatException e) {
                    throw new RedmineException(Messages.AbstractRedmineClient_INVALID_TASK_ID);
                }// ww w.  jav  a2 s.com
            } else {
                throw new RedmineException(Messages.AbstractRedmineClient_MISSING_TASK_ID_IN_RESPONSE);
            }
        }
    } else {
        throw new RedmineStatusException(IStatus.INFO, errorMsg);
    }

    throw new RedmineException(Messages.AbstractRedmineClient_UNHANDLED_SUBMIT_ERROR);
}

From source file:org.svenk.redmine.core.client.AbstractRedmineClient.java

public void updateTicket(int ticketId, Map<String, String> postValues, String comment, IProgressMonitor monitor)
        throws RedmineException {
    PostMethod method = new PostMethod(REDMINE_URL_TICKET_EDIT + ticketId);

    List<NameValuePair> values = this.ticket2HttpData(postValues);
    values.add(new NameValuePair(CLIENT_FIELD_NOTES, comment));

    method.addParameters(values.toArray(new NameValuePair[values.size()]));

    String errorMsg = executeMethod(method, submitErrorParser, monitor, HttpStatus.SC_OK,
            HttpStatus.SC_MOVED_TEMPORARILY);
    if (errorMsg != null) {
        throw new RedmineStatusException(IStatus.INFO, errorMsg);
    }/*from  w  ww  .  j a v a 2s .c o m*/
}

From source file:org.vamdc.taverna.vamdc_taverna_suite.common.UWSCaller.java

/**
 * @param filename/*from w  ww.j  a v a 2 s  . com*/
 * @param strURL
 * @param append
 * @return
 * @throws Exception
 */
private static String getDetails(File input, String strURL, String append) throws Exception {
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // Request content will be retrieved directly
    // from the input stream
    // Per default, the request content needs to be buffered
    // in order to determine its length.
    // Request body buffering can be avoided when
    // content length is explicitly specified

    post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
    post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");

    post.setFollowRedirects(false);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();

    try {
        //httpclient.
        int result = httpclient.executeMethod(post);
        int statuscode = post.getStatusCode();

        if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                || (statuscode == HttpStatus.SC_SEE_OTHER)
                || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

            Header header = post.getResponseHeader("location");
            System.out.println("   :  Header  :  " + header);
            if (header != null) {
                String newuri = header.getValue();
                if ((newuri == null) || (newuri.equals("")))
                    newuri = "/";
                return newuri;
            } else {
                return null;
            }
        } else {
            System.out.println(post.getResponseBodyAsString());
        }
    } finally {
        // Release current connection to the connection pool 
        // once you are done
        post.releaseConnection();
    }
    return null;
}

From source file:org.wso2.am.integration.tests.application.GrantTypeTokenGenerateTestCase.java

@Test(groups = {
        "wso2.am" }, description = "Test authorization_code token generation", dependsOnMethods = "testApplicationCreation")
public void testAuthCode() throws Exception {

    //Sending first request to approve grant authorization to app
    headers.put("Content-Type", APPLICATION_CONTENT_TYPE);
    String url = authorizeURL + "?response_type=code&" + "client_id=" + consumerKey
            + "&scope=PRODUCTION&redirect_uri=" + CALLBACK_URL;
    HttpResponse res = HTTPSClientUtils.doGet(url, headers);
    Assert.assertEquals(res.getResponseCode(), HttpStatus.SC_MOVED_TEMPORARILY,
            "Response code is not as expected");
    String locationHeader = res.getHeaders().get(LOCATION_HEADER);
    Assert.assertNotNull(locationHeader, "Couldn't found Location Header");
    String sessionDataKey = getURLParameter(locationHeader, "sessionDataKey");
    Assert.assertNotNull(sessionDataKey, "Couldn't found sessionDataKey from the Location Header");

    //Login to the Identity with user/pass
    headers.clear();// www  . jav  a2 s.  c  om
    headers.put("Content-Type", APPLICATION_CONTENT_TYPE);
    urlParameters.add(new BasicNameValuePair("username", user.getUserName()));
    urlParameters.add(new BasicNameValuePair("password", user.getPassword()));
    urlParameters.add(new BasicNameValuePair("tocommonauth", "true"));
    urlParameters.add(new BasicNameValuePair("sessionDataKey", sessionDataKey));

    res = HTTPSClientUtils.doPost(identityLoginURL, headers, urlParameters);
    Assert.assertEquals(res.getResponseCode(), HttpStatus.SC_MOVED_TEMPORARILY,
            "Response code is not as expected");
    locationHeader = res.getHeaders().get(LOCATION_HEADER);
    Assert.assertNotNull(locationHeader, "Couldn't found Location Header");
    String sessionDataKeyConsent = getURLParameter(locationHeader, "sessionDataKeyConsent");
    Assert.assertNotNull(sessionDataKey, "Couldn't found sessionDataKeyConsent from the Location Header");

    //approve the application by logged user
    headers.clear();
    urlParameters.clear();
    headers.put("Content-Type", APPLICATION_CONTENT_TYPE);
    urlParameters.add(new BasicNameValuePair("consent", "approve"));
    urlParameters.add(new BasicNameValuePair("hasApprovedAlways", "false"));
    urlParameters.add(new BasicNameValuePair("sessionDataKeyConsent", sessionDataKeyConsent));

    res = HTTPSClientUtils.doPost(identityLoginURL, headers, urlParameters);
    Assert.assertEquals(res.getResponseCode(), HttpStatus.SC_MOVED_TEMPORARILY,
            "Response code is not as expected");
    locationHeader = res.getHeaders().get(LOCATION_HEADER);
    Assert.assertNotNull(locationHeader, "Couldn't found Location Header");
    String tempCode = getURLParameter(locationHeader, "code");
    Assert.assertNotNull(tempCode, "Couldn't found auth code from the Location Header");

    //get accessToken
    headers.clear();
    urlParameters.clear();
    urlParameters.add(new BasicNameValuePair("grant_type", AUTHORIZATION_CODE_GRANT_TYPE));
    urlParameters.add(new BasicNameValuePair("code", tempCode));
    urlParameters.add(new BasicNameValuePair("redirect_uri", CALLBACK_URL));
    urlParameters.add(new BasicNameValuePair("client_secret", consumerSecret));
    urlParameters.add(new BasicNameValuePair("client_id", consumerKey));

    res = HTTPSClientUtils.doPost(tokenURL, headers, urlParameters);
    Assert.assertEquals(res.getResponseCode(), HttpStatus.SC_OK, "Response code is not as expected");
    JSONObject response = new JSONObject(res.getData());
    String accessToken = response.getString("access_token");
    Assert.assertNotNull(accessToken, "Couldn't found accessToken");

    //invoke the api with generate token
    requestHeaders.clear();
    requestHeaders.put(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Bearer " + accessToken);
    String invokeURL = getAPIInvocationURLHttp(API_CONTEXT, API_VERSION);
    res = HTTPSClientUtils.doGet(invokeURL + "/add?x=1&y=1", requestHeaders);
    Assert.assertEquals(res.getResponseCode(), HttpStatus.SC_OK, "Response code is not as expected");
}

From source file:org.wso2.am.integration.tests.application.GrantTypeTokenGenerateTestCase.java

@Test(groups = { "wso2.am" }, description = "Test implicit token generation", dependsOnMethods = "testAuthCode")
public void testImplicit() throws Exception {
    headers.clear();/*from www  .  j  a  v a2  s .c o  m*/
    urlParameters.clear();
    //Sending first request to approve grant authorization to app
    headers.put("Content-Type", APPLICATION_CONTENT_TYPE);
    String url = authorizeURL + "?response_type=token&" + "client_id=" + consumerKey
            + "&scope=PRODUCTION&redirect_uri=" + CALLBACK_URL;
    HttpResponse res = HTTPSClientUtils.doGet(url, headers);
    Assert.assertEquals(res.getResponseCode(), HttpStatus.SC_MOVED_TEMPORARILY,
            "Response code is not as expected");
    String locationHeader = res.getHeaders().get(LOCATION_HEADER);
    Assert.assertNotNull(locationHeader, "Couldn't found Location Header");
    String sessionDataKey = getURLParameter(locationHeader, "sessionDataKey");
    Assert.assertNotNull(sessionDataKey, "Couldn't found sessionDataKey from the Location Header");

    //Login to the Identity with user/pass
    headers.clear();
    headers.put("Content-Type", APPLICATION_CONTENT_TYPE);
    urlParameters.add(new BasicNameValuePair("username", user.getUserName()));
    urlParameters.add(new BasicNameValuePair("password", user.getPassword()));
    urlParameters.add(new BasicNameValuePair("tocommonauth", "true"));
    urlParameters.add(new BasicNameValuePair("sessionDataKey", sessionDataKey));

    res = HTTPSClientUtils.doPost(identityLoginURL, headers, urlParameters);
    Assert.assertEquals(res.getResponseCode(), HttpStatus.SC_MOVED_TEMPORARILY,
            "Response code is not as expected");
    locationHeader = res.getHeaders().get(LOCATION_HEADER);
    Assert.assertNotNull(locationHeader, "Couldn't found Location Header");
    String sessionDataKeyConsent = getURLParameter(locationHeader, "sessionDataKeyConsent");
    Assert.assertNotNull(sessionDataKey, "Couldn't found sessionDataKeyConsent from the Location Header");

    //approve the application by logged user
    headers.clear();
    urlParameters.clear();
    headers.put("Content-Type", APPLICATION_CONTENT_TYPE);
    urlParameters.add(new BasicNameValuePair("consent", "approve"));
    urlParameters.add(new BasicNameValuePair("hasApprovedAlways", "false"));
    urlParameters.add(new BasicNameValuePair("sessionDataKeyConsent", sessionDataKeyConsent));

    res = HTTPSClientUtils.doPost(identityLoginURL, headers, urlParameters);
    Assert.assertEquals(res.getResponseCode(), HttpStatus.SC_MOVED_TEMPORARILY,
            "Response code is not as expected");
    locationHeader = res.getHeaders().get(LOCATION_HEADER);
    Assert.assertNotNull(locationHeader, "Couldn't found Location Header");
    String accessToken = getURLParameter(locationHeader, "access_token");
    Assert.assertNotNull(accessToken, "Couldn't found auth code from the Location Header");

    //invoke the api with generate token
    requestHeaders.clear();
    requestHeaders.put(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Bearer " + accessToken);
    String invokeURL = getAPIInvocationURLHttp(API_CONTEXT, API_VERSION);
    res = HTTPSClientUtils.doGet(invokeURL + "/add?x=1&y=1", requestHeaders);
    Assert.assertEquals(res.getResponseCode(), HttpStatus.SC_OK, "Response code is not as expected");
}

From source file:org.wso2.am.integration.tests.application.GrantTypeTokenGenerateTestCase.java

@Test(groups = {
        "wso2.am" }, description = "Test authorization_code token generation", dependsOnMethods = "testApplicationCreationWithoutCallBackURL")
public void testAuthRequestWithoutCallbackURL() throws Exception {
    headers.clear();//w  w w . j a v a  2  s  .com
    //Sending first request to approve grant authorization to app
    headers.put("Content-Type", APPLICATION_CONTENT_TYPE);
    String url = authorizeURL + "?response_type=code&" + "client_id=" + consumerKey
            + "&scope=PRODUCTION&redirect_uri=";
    HttpResponse res = HTTPSClientUtils.doGet(url, headers);
    Assert.assertEquals(res.getResponseCode(), HttpStatus.SC_MOVED_TEMPORARILY,
            "Response code is not as expected");
    String locationHeader = res.getHeaders().get(LOCATION_HEADER);
    Assert.assertNotNull(locationHeader, "Couldn't found Location Header");
    Assert.assertTrue(locationHeader.contains("oauthErrorCode"), "Redirection page should be a error page");
}

From source file:org.wso2.appfactory.dynamicslave.JenkinsClient.java

public String post(String path) {
    PostMethod postMethod = createPost(path, null, null, null);
    int statusCode = 0;
    String response = null;/*ww w .  j a  v  a2s .co m*/
    try {
        statusCode = httpClient.executeMethod(postMethod);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Error while calling the backed for " + postMethod.getPath(), e);
        return null;
    }
    try {
        if (statusCode != HttpStatus.SC_MOVED_TEMPORARILY
                && (statusCode < HttpStatus.SC_OK || statusCode >= HttpStatus.SC_MULTIPLE_CHOICES)) {
            LOGGER.info("Invocation returned " + statusCode + " for " + postMethod.getPath());
            return null;
        } else {

            response = postMethod.getResponseBodyAsString();
            LOGGER.info("Sent post successfully " + postMethod.getPath());
        }

    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Error while getting the response for " + postMethod.getPath(), e);
        return null;
    } finally {
        postMethod.releaseConnection();
    }
    return response;
}

From source file:org.wso2.appfactory.dynamicslave.JenkinsClient.java

public String post_xml(String path, String xml, Map<String, String> params) {
    PostMethod postMethod = null;/*from w w w  .j ava 2s .  c om*/
    int statusCode = 0;
    String response = null;
    NameValuePair[] nameValuePairs = getNameValuePairFromMap(params);
    StringRequestEntity stringRequestEntity = null;
    try {
        stringRequestEntity = xml != null ? new StringRequestEntity(xml, "text/xml", "utf-8") : null;
    } catch (UnsupportedEncodingException e) {
        LOGGER.log(Level.SEVERE, "Error while getting the request parameters for " + postMethod.getPath(), e);
        return null;
    }

    postMethod = createPost(path, nameValuePairs, stringRequestEntity, null);

    try {
        statusCode = httpClient.executeMethod(postMethod);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Error while calling the backed for " + postMethod.getPath(), e);
        return null;
    }
    try {
        if (statusCode != HttpStatus.SC_MOVED_TEMPORARILY
                && (statusCode < HttpStatus.SC_OK || statusCode >= HttpStatus.SC_MULTIPLE_CHOICES)) {
            LOGGER.info("Invocation returned " + statusCode + " for " + postMethod.getPath());
            return null;
        } else {

            response = postMethod.getResponseBodyAsString();
            LOGGER.info("Sent post successfully " + postMethod.getPath());
        }
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Error while getting the response for " + postMethod.getPath(), e);
        return null;
    } finally {
        postMethod.releaseConnection();
    }
    return response;
}

From source file:org.wso2.appfactory.integration.test.utils.external.HttpHandler.java

/**
 * This method is used to retrieve the redirection location from response header
 * as the request will results in either 301 or 302 status code.
 * @param url//w w w  .  j a  va  2s . c  om
 * @return
 * @throws IOException
 */
public static String getRedirectionUrl(String url) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    HttpResponse response = httpclient.execute(httpPost);
    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
        return response.getFirstHeader(HTTPConstants.HEADER_LOCATION).getValue();
    }
    return null;
}

From source file:org.wso2.as.platform.tests.sample.WebAppDepSyncTestCase.java

@Test(groups = "wso2.as", description = "Validating undeployment on all worker nodes", dependsOnMethods = "org.wso2.as.platform.tests.sample.WebAppDepSyncTestCase.testWebApplicationUndeploymentOnManager", timeOut = 120000)
public void testWebApplicationUndeploymentOnWorkers() throws Exception {

    // Requests are sent directly to worker nodes after undeploying web app in manager node
    log.info(" ----- Validating web application undeployment via worker node-1 : " + webAppURLLocalWorker1);

    HttpResponse worker1Response = HttpRequestUtil.sendGetRequest(webAppURLLocalWorker1, null);

    long currentTime = System.currentTimeMillis();

    while (((System.currentTimeMillis() - currentTime) < DEP_SYNC_TIME_OUT)) {

        if (worker1Response.getResponseCode() == HttpStatus.SC_NOT_FOUND
                || worker1Response.getResponseCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            break;
        }/*ww w  . j a v  a2s. c  o  m*/

        try {
            Thread.sleep(DEP_SYNC_RETRY_PERIOD);
        } catch (InterruptedException e) {
            //ignored the exception here since it will exit the execution
        }
        worker1Response = HttpRequestUtil.sendGetRequest(webAppURLLocalWorker1, null);
    }

    log.info(" ----- ResponseCode received worker node-1 : " + worker1Response.getResponseCode());

    // Validate dep sync undeployment on worker node within DEP_SYNC_TIME_OUT
    // After undeployment, HTTP response should be either HTTP 404 or HTTP 302
    assertTrue(
            worker1Response.getResponseCode() == HttpStatus.SC_NOT_FOUND
                    || worker1Response.getResponseCode() == HttpStatus.SC_MOVED_TEMPORARILY,
            "Undeploying web app from all nodes failed");

    log.info(" ----- Validating web application undeployment via worker node-2 : " + webAppURLLocalWorker2);

    HttpResponse worker2Response = HttpRequestUtil.sendGetRequest(webAppURLLocalWorker2, null);

    // Reset currentTime for worker node 2
    currentTime = System.currentTimeMillis();

    while (((System.currentTimeMillis() - currentTime) < DEP_SYNC_TIME_OUT)) {

        if (worker2Response.getResponseCode() == HttpStatus.SC_NOT_FOUND
                || worker2Response.getResponseCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            break;
        }

        try {
            Thread.sleep(DEP_SYNC_RETRY_PERIOD);
        } catch (InterruptedException e) {
            //ignored the exception here since it will exit the execution
        }
        worker2Response = HttpRequestUtil.sendGetRequest(webAppURLLocalWorker2, null);
    }

    log.info(" ----- ResponseCode received worker node-2 : " + worker2Response.getResponseCode());

    // Validate dep sync undeployment on worker node within DEP_SYNC_TIME_OUT
    // After undeployment, HTTP response should be either HTTP 404 or HTTP 302
    assertTrue(
            worker2Response.getResponseCode() == HttpStatus.SC_NOT_FOUND
                    || worker2Response.getResponseCode() == HttpStatus.SC_MOVED_TEMPORARILY,
            "Undeploying web app from all nodes failed");

}