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

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

Introduction

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

Prototype

int SC_OK

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

Click Source Link

Document

<tt>200 OK</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient_0_5_0.java

private String getEngineInfo(String infoType)
        throws EngineUnavailableException, ServiceInvocationFailedException {
    String version;// w  w  w  . jav  a  2  s. c om
    HttpClient client;
    PostMethod method;
    NameValuePair[] nameValuePairs;

    version = null;
    client = new HttpClient();
    method = new PostMethod(getServiceUrl(ENGINE_INFO_SERVICE));

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    nameValuePairs = new NameValuePair[] { new NameValuePair("infoType", infoType) }; //$NON-NLS-1$

    method.setRequestBody(nameValuePairs);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new ServiceInvocationFailedException(
                    Messages.getString("SpagoBITalendEngineClient_0_5_0.serviceExcFailed") //$NON-NLS-1$
                            + ENGINE_INFO_SERVICE,
                    method.getStatusLine().toString(),
                    method.getResponseBodyAsString());
        } else {
            version = method.getResponseBodyAsString();
        }

    } catch (HttpException e) {
        throw new EngineUnavailableException(
                Messages.getString("SpagoBITalendEngineClient_0_5_0.protocolViolation") + e.getMessage()); //$NON-NLS-1$
    } catch (IOException e) {
        throw new EngineUnavailableException(
                Messages.getString("SpagoBITalendEngineClient_0_5_0.transportError") + e.getMessage()); //$NON-NLS-1$
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return version;
}

From source file:net.bryansaunders.jee6divelog.service.rest.UserAccountApiIT.java

/**
 * Test find by username with Valid Username.
 * /*from   www  . j  a  v  a  2  s.  c  o m*/
 * @throws Exception
 *             Thrown on Error
 */
@Test
public void ifSingleCriteriaMatchesThenGetResults() throws Exception {
    // given
    final String requestUrl = RestApiTest.URL_ROOT + "/user/find/";
    final UserAccount loggedInUser = this.doLogin(UserAccountApiIT.VALID_EMAIL,
            UserAccountApiIT.VALID_PASSWORD);
    final String privateApiKey = loggedInUser.getPrivateApiKey();
    final String publicApiKey = loggedInUser.getPublicApiKey();

    final Map<String, String> headers = this.generateLoginHeaders(HttpMethod.POST, requestUrl, null,
            privateApiKey, publicApiKey);

    final UserAccount userAccount = new UserAccount();
    userAccount.setEmail(UserAccountApiIT.VALID_EMAIL);

    // when
    final String json = given().headers(headers).contentType(ContentType.JSON).body(userAccount).expect()
            .statusCode(HttpStatus.SC_OK).when().post(requestUrl).asString();

    // then
    assertNotNull(json);

    final ObjectMapper objMapper = new ObjectMapper();
    final List<UserAccount> list = objMapper.readValue(json, new TypeReference<List<UserAccount>>() {
    });
    assertNotNull(list);
    assertEquals(1, list.size());

    final UserAccount foundUser = list.get(0);
    assertNotNull(foundUser);
    assertEquals(UserAccountApiIT.VALID_EMAIL, foundUser.getEmail());
}

From source file:com.twinsoft.convertigo.engine.admin.services.mobiles.GetBuildStatus.java

@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    String project = Keys.project.value(request);

    MobileApplication mobileApplication = getMobileApplication(project);

    if (mobileApplication == null) {
        throw new ServiceException("no such mobile application");
    } else {/*from  ww  w . j a  v  a  2 s.c o m*/
        boolean bAdminRole = Engine.authenticatedSessionManager.hasRole(request.getSession(), Role.WEB_ADMIN);
        if (!bAdminRole && mobileApplication.getAccessibility() == Accessibility.Private) {
            throw new AuthenticationException("Authentication failure: user has not sufficient rights!");
        }
    }

    String platformName = Keys.platform.value(request);

    String mobileBuilderPlatformURL = EnginePropertiesManager
            .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL);

    URL url = new URL(mobileBuilderPlatformURL + "/getstatus");

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(url.getHost());
    HttpState httpState = new HttpState();
    Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

    PostMethod method = new PostMethod(url.toString());

    JSONObject jsonResult;
    try {
        HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value());
        method.setRequestBody(new NameValuePair[] {
                new NameValuePair("application", mobileApplication.getComputedApplicationName()),
                new NameValuePair("platformName", platformName),
                new NameValuePair("auth_token", mobileApplication.getComputedAuthenticationToken()),
                new NameValuePair("endpoint", mobileApplication.getComputedEndpoint(request)) });

        int methodStatusCode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);

        InputStream methodBodyContentInputStream = method.getResponseBodyAsStream();
        byte[] httpBytes = IOUtils.toByteArray(methodBodyContentInputStream);
        String sResult = new String(httpBytes, "UTF-8");

        if (methodStatusCode != HttpStatus.SC_OK) {
            throw new ServiceException(
                    "Unable to get building status for application '" + project + "' (final app name: '"
                            + mobileApplication.getComputedApplicationName() + "').\n" + sResult);
        }

        jsonResult = new JSONObject(sResult);
    } finally {
        method.releaseConnection();
    }

    Element statusElement = document.createElement("build");
    statusElement.setAttribute(Keys.project.name(), project);
    statusElement.setAttribute(Keys.platform.name(), platformName);

    if (jsonResult.has(platformName + "_status")) {
        statusElement.setAttribute("status", jsonResult.getString(platformName + "_status"));
    } else {
        statusElement.setAttribute("status", "none");
    }

    if (jsonResult.has(platformName + "_error")) {
        statusElement.setAttribute("error", jsonResult.getString(platformName + "_error"));
    }

    statusElement.setAttribute("version", jsonResult.has("version") ? jsonResult.getString("version") : "n/a");
    statusElement.setAttribute("phonegap_version",
            jsonResult.has("phonegap_version") ? jsonResult.getString("phonegap_version") : "n/a");

    statusElement.setAttribute("revision",
            jsonResult.has("revision") ? jsonResult.getString("revision") : "n/a");
    statusElement.setAttribute("endpoint",
            jsonResult.has("endpoint") ? jsonResult.getString("endpoint") : "n/a");

    document.getDocumentElement().appendChild(statusElement);
}

From source file:davmail.caldav.TestCaldav.java

public void testGetRoot() throws IOException {
    GetMethod method = new GetMethod("/");
    httpClient.executeMethod(method);/*  ww w.  jav  a2  s.c o m*/
    assertEquals(HttpStatus.SC_OK, method.getStatusCode());
}

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java

/**
 * Construct and select are sent across the wire in exactly the same way.
 *//*  w  w w . j  a  v  a2  s. c  o m*/
private String executeQuery(final String query, final QueryLanguage ql, final boolean includeInferred)
        throws Exception {

    GetMethod get = new GetMethod(servletURL);
    // just to be nice.
    get.addRequestHeader(new Header("Accept", "application/rdf+xml"));
    // and say what we want.
    get.addRequestHeader(new Header("Accept-Charset", "UTF-8"));

    try {

        // add the range and include inferred headers
        get.addRequestHeader(
                new Header(GraphRepositoryServlet.X_INCLUDE_INFERRED, String.valueOf(includeInferred)));
        if (query != null) {
            // add the range header
            String range = ql.toString().toLowerCase() + "[" + trim(query) + "]";
            get.addRequestHeader(new Header(GraphRepositoryServlet.HTTP_RANGE, range));
        }

        // Execute the method.
        int sc = getHttpClient().executeMethod(get);
        if (sc != HttpStatus.SC_OK && sc != HttpStatus.SC_PARTIAL_CONTENT) {
            throw new IOException("HTTP-GET failed: " + get.getStatusLine());
        }

        // Read the response body.
        String response = IOUtils.readString(get.getResponseBodyAsStream(), get.getResponseCharSet());
        return response;

    } finally {
        // Release the connection.
        get.releaseConnection();
    }

}

From source file:de.avanux.livetracker.sender.LocationSender.java

private String executeHttpMethod(HttpMethodBase method) {
    String response = null;/*from   w ww .jav a 2s .  com*/
    HttpClient client = new HttpClient();
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        response = new String(responseBody);

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;
}

From source file:com.rallydev.integration.build.rest.RallyRestServiceTest.java

public void testRallyRestServiceBuildSuccessWithProxy() throws Exception {
    String xml = readFile(BUILD_SUCCESS_FILE);
    httpClientMockControl.expectAndReturn(httpClientMock.getHostConfiguration(), hostConfigurationMock);
    hostConfigurationMock.setProxy("10.1.0.12", 3128);

    httpClientMockControl.expectAndReturn(httpClientMock.executeMethod(postMethodMock), HttpStatus.SC_OK);
    postMethodMockControl.expectAndReturn(postMethodMock.getResponseBodyAsStream(),
            readFileAsStream(BUILD_SUCCESS_RESPONSE_FILE));
    postMethodMock.releaseConnection();//from w  ww  . j av a 2s  .c o m
    httpClientMockControl.replay();
    postMethodMockControl.replay();
    hostConfigurationMockControl.replay();

    rallyRestService.setProxyInfo("10.1.0.12", 3128, null, null);
    String response = rallyRestService.doCreate(xml, httpClientMock, postMethodMock);
    assertEquals(readFile(BUILD_SUCCESS_RESPONSE_FILE), response);
    hostConfigurationMockControl.verify();
    verify();
}

From source file:com.thoughtworks.go.server.service.PipelinePauseServiceTest.java

@Test
public void shouldUnPausePipeline() throws Exception {

    setUpValidPipelineWithAuth();//www .j  a v a2  s .c  o m

    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();

    pipelinePauseService.unpause(VALID_PIPELINE, VALID_USER, result);
    verify(pipelineDao).unpause(VALID_PIPELINE);

    assertThat(result.isSuccessful(), is(true));
    assertThat(result.httpCode(), is(HttpStatus.SC_OK));
}

From source file:edu.northwestern.bioinformatics.studycalendar.security.plugin.websso.direct.DirectLoginHttpFacade.java

/**
 * Performs a mid-process post and updates the LT from the new response.
 *///from   www .j  a  v  a2 s. com
private String doIntermediatePost(PostMethod post) throws IOException {
    try {
        getHttpClient().executeMethod(post);
        if (post.getStatusCode() == HttpStatus.SC_OK) {
            String body = post.getResponseBodyAsString();
            this.lt = new LoginFormReader(body).getLoginTicket();
            return body;
        } else {
            throw new CasDirectException("Retrieving the login form %s failed: %s", getLoginUrl(),
                    post.getStatusLine());
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:com.zimbra.cs.service.admin.StatsImageServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    AuthToken authToken = getAdminAuthTokenFromCookie(req, resp);
    if (authToken == null)
        return;//w w w  .j ava 2 s  .  c  o  m

    String imgName = null;
    InputStream is = null;
    boolean imgAvailable = true;
    boolean localServer = false;
    boolean systemWide = false;

    String serverAddr = "";

    String noDefaultImg = req.getParameter("nodef");
    boolean noDefault = false;
    if (noDefaultImg != null && !noDefaultImg.equals("") && noDefaultImg.equals("1")) {
        noDefault = true;
    }
    String reqPath = req.getRequestURI();
    try {

        //check if this is the logger host, otherwise proxy the request to the logger host 
        String serviceHostname = Provisioning.getInstance().getLocalServer()
                .getAttr(Provisioning.A_zimbraServiceHostname);
        String logHost = Provisioning.getInstance().getConfig().getAttr(Provisioning.A_zimbraLogHostname);
        if (!serviceHostname.equalsIgnoreCase(logHost)) {
            StringBuffer url = new StringBuffer("https");
            url.append("://").append(logHost).append(':').append(LC.zimbra_admin_service_port.value());
            url.append(reqPath);
            String queryStr = req.getQueryString();
            if (queryStr != null)
                url.append('?').append(queryStr);

            // create an HTTP client with the same cookies
            HttpState state = new HttpState();
            try {
                state.addCookie(new org.apache.commons.httpclient.Cookie(logHost,
                        ZimbraCookie.COOKIE_ZM_ADMIN_AUTH_TOKEN, authToken.getEncoded(), "/", null, false));
            } catch (AuthTokenException ate) {
                throw ServiceException.PROXY_ERROR(ate, url.toString());
            }
            HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
            client.setState(state);
            GetMethod get = new GetMethod(url.toString());
            try {
                int statusCode = HttpClientUtil.executeMethod(client, get);
                if (statusCode != HttpStatus.SC_OK)
                    throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), null);

                resp.setContentType("image/gif");
                ByteUtil.copy(get.getResponseBodyAsStream(), true, resp.getOutputStream(), false);
                return;
            } catch (HttpException e) {
                throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e);
            } catch (IOException e) {
                throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e);
            } finally {
                get.releaseConnection();
            }
        }
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
        return;
    }
    try {

        if (reqPath == null || reqPath.length() == 0) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        if (mLog.isDebugEnabled())
            mLog.debug("received request to:(" + reqPath + ")");

        String reqParts[] = reqPath.split("/");

        String reqFilename = reqParts[3];
        imgName = LC.stats_img_folder.value() + File.separator + reqFilename;
        try {
            is = new FileInputStream(imgName);
        } catch (FileNotFoundException ex) {//unlikely case - only if the server's files are broken
            if (is != null)
                is.close();
            if (!noDefault) {
                imgName = LC.stats_img_folder.value() + File.separator + IMG_NOT_AVAIL;
                is = new FileInputStream(imgName);

            } else {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
                return;
            }
        }
    } catch (Exception ex) {
        if (is != null)
            is.close();

        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "FNF image File not found");
        return;
    }
    resp.setContentType("image/gif");
    ByteUtil.copy(is, true, resp.getOutputStream(), false);
}