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:net.sf.sail.webapp.dao.sds.impl.HttpRestSdsWorkgroupDaoTest.java

/**
 * Test method for//from  w  ww. ja v a 2 s . co  m
 * {@link net.sf.sail.webapp.dao.sds.impl.HttpRestSdsWorkgroupDao#save(net.sf.sail.webapp.domain.sds.SdsWorkgroup)}.
 */
@SuppressWarnings("unchecked")
public void testSave_NewSdsWorkgroup_NoMembers() throws Exception {
    // create offering in SDS
    Long sdsOfferingId = this.createWholeOffering().getSdsObjectId();
    this.sdsOffering.setSdsObjectId(sdsOfferingId);

    this.sdsWorkgroup.setName(DEFAULT_NAME);
    this.sdsWorkgroup.setSdsOffering(this.sdsOffering);

    assertNull(this.sdsWorkgroup.getSdsObjectId());
    this.sdsWorkgroupDao.save(this.sdsWorkgroup);
    assertNotNull(this.sdsWorkgroup.getSdsObjectId());

    // retrieve newly created workgroup using httpunit and compare with
    // sdsWorkgroup saved via DAO
    WebResponse webResponse = makeHttpRestGetRequest("/workgroup/" + this.sdsWorkgroup.getSdsObjectId());
    assertEquals(HttpStatus.SC_OK, webResponse.getResponseCode());

    Document doc = createDocumentFromResponse(webResponse);

    Element rootElement = doc.getRootElement();
    assertEquals(this.sdsWorkgroup.getSdsObjectId(), new Long(rootElement.getChild("id").getValue()));
    assertEquals(this.sdsWorkgroup.getName(), rootElement.getChild("name").getValue());
    assertEquals(this.sdsWorkgroup.getSdsOffering().getSdsObjectId(),
            new Long(rootElement.getChild("offering-id").getValue()));

    // compare the members in the workgroup
    webResponse = makeHttpRestGetRequest("/workgroup/" + this.sdsWorkgroup.getSdsObjectId() + "/membership");
    assertEquals(HttpStatus.SC_OK, webResponse.getResponseCode());

    doc = createDocumentFromResponse(webResponse);

    Element rootMembershipElement = doc.getRootElement();
    assertEquals("workgroup-memberships", rootMembershipElement.getName());
    assertTrue(rootMembershipElement.getChildren().isEmpty());
}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public AuthenticationResponse authenticate(Long operatorId, String username, String password) {
    PostMethod method = new PostMethod(baseUrl + AUTHENTICATE);
    AuthenticationRequest request = new AuthenticationRequest();
    request.setOperatorId(operatorId);//from w  w  w  . j  a  va 2 s  .  c o m
    request.setUserName(username);
    request.setPassword(password);

    try {
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            AuthenticationResponse response = new AuthenticationResponse();
            response.setAuthenticated(false);
            return response;

        } else if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, AuthenticationResponse.class);

        } else {
            throw new RuntimeException("Failed to authenticate user, RESPONSE CODE: " + statusCode);
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.autentia.mvn.plugin.changes.HttpRequest.java

/**
 * Send a GET method request to the given link using the configured HttpClient, possibly following redirects, and returns
 * the response as String.//from w ww . j a v a2s . c o m
 * 
 * @param cl the HttpClient
 * @param link the URL
 * @throws HttpStatusException
 * @throws IOException
 */
public byte[] sendPostRequest(final HttpClient cl, final String link, final String parameters)
        throws HttpStatusException, IOException {
    try {
        final PostMethod pm = new PostMethod(link);

        if (parameters != null) {
            final String[] params = parameters.split("&");
            for (final String param : params) {
                final String[] pair = param.split("=");
                if (pair.length == 2) {
                    pm.addParameter(pair[0], pair[1]);
                }
            }
        }

        this.getLog().info("Downloading from Bugzilla at: " + link);

        cl.executeMethod(pm);

        final StatusLine sl = pm.getStatusLine();

        if (sl == null) {
            this.getLog().error("Unknown error validating link: " + link);

            throw new HttpStatusException("UNKNOWN STATUS");
        }

        // if we get a redirect, throws exception
        if (pm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            this.getLog().debug("Attempt to redirect ");
            throw new HttpStatusException("Attempt to redirect");
        }

        if (pm.getStatusCode() == HttpStatus.SC_OK) {
            final InputStream is = pm.getResponseBodyAsStream();
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final byte[] buff = new byte[256];
            int readed = is.read(buff);
            while (readed != -1) {
                baos.write(buff, 0, readed);
                readed = is.read(buff);
            }

            this.getLog().debug("Downloading from Bugzilla was successful");
            return baos.toByteArray();
        } else {
            this.getLog().warn("Downloading from Bugzilla failed. Received: [" + pm.getStatusCode() + "]");
            throw new HttpStatusException("WRONG STATUS");
        }
    } catch (final HttpException e) {
        if (this.getLog().isDebugEnabled()) {
            this.getLog().error("Error downloading issues from Bugzilla:", e);
        } else {
            this.getLog().error("Error downloading issues from Bugzilla url: " + e.getLocalizedMessage());

        }
        throw e;
    } catch (final IOException e) {
        if (this.getLog().isDebugEnabled()) {
            this.getLog().error("Error downloading issues from Bugzilla:", e);
        } else {
            this.getLog().error("Error downloading issues from Bugzilla. Cause is " + e.getLocalizedMessage());
        }
        throw e;
    }
}

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

/**
 * Test find by username with Valid Username.
 * //from w ww  .j  a  va 2s.  co  m
 * @throws Exception
 *             Thrown on Error
 */
@Test
@UsingDataSet("ThreeUserAccounts-Admin.yml")
public void ifMultipleCriteriaMatchesThenGetResults() 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.setState("SC");
    userAccount.setLastName("Saunders");

    // 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(2, list.size());
}

From source file:net.sf.dsig.verify.X509CRLHelper.java

/**
 * Retrieve the CRL//from www.ja  v a2 s . co  m
 * 
 * @param distributionPointUriAsString the distribution point URI
 * @return the {@link X509CRL} object
 * @throws NetworkAccessException when any network access issues occur
 * @throws VerificationException when an error occurs while parsing the CRL
 */
public X509CRL getX509CRL(String distributionPointUriAsString)
        throws NetworkAccessException, VerificationException {
    synchronized (mutex) {
        Date nextUpdate = (Date) uriNextUpdateMap.get(distributionPointUriAsString);
        if (nextUpdate != null && nextUpdate.after(new Date())) {
            logger.debug("Returning cached X509CRL" + "; distributionPoint=" + distributionPointUriAsString
                    + ", nextUpdate=" + nextUpdate);
            return (X509CRL) uriX509CrlMap.get(distributionPointUriAsString);
        }

        HostConfiguration config = getHostConfiguration();

        GetMethod get = new GetMethod(distributionPointUriAsString);
        try {
            getHttpClient().executeMethod(config, get);

            logger.debug("HTTP GET executed" + "; distributionPointUri=" + distributionPointUriAsString
                    + ", statusLine=" + get.getStatusLine());

            if (get.getStatusCode() != HttpStatus.SC_OK) {
                throw new NetworkAccessException("HTTP GET failed; statusLine=" + get.getStatusLine());
            }

            X509CRL crl = null;
            byte[] responseBodyBytes = get.getResponseBody();
            try {
                crl = (X509CRL) CertificateFactory.getInstance("X.509")
                        .generateCRL(new ByteArrayInputStream(responseBodyBytes));
            } catch (CertificateException e) {
                throw new ConfigurationException("X.509 certificate factory missing");
            }

            uriNextUpdateMap.put(distributionPointUriAsString, crl.getNextUpdate());
            uriX509CrlMap.put(distributionPointUriAsString, crl);

            return crl;
        } catch (IOException e) {
            throw new NetworkAccessException("I/O error occured", e);
        } catch (CRLException e) {
            throw new VerificationException("Error while following CRL protocol", e);
        } finally {
            get.releaseConnection();
        }
    }
}

From source file:com.sdm.core.resource.RestResource.java

@Override
public IBaseResponse getById(PK id) {
    DefaultResponse response = this.validateCache();
    // Cache validation
    if (response != null) {
        return response;
    }/*from ww w  .ja  v a2s .c o  m*/

    T data = this.checkData(id);

    response = new DefaultResponse<T>(HttpStatus.SC_OK, ResponseType.SUCCESS, data);
    response.setHeaders(this.buildCache());
    return response;
}

From source file:mitm.common.security.ca.handlers.comodo.Tier2PartnerDetails.java

private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException {
    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("Error Tier2 partner details. Message: " + httpMethod.getStatusLine());
    }/* ww  w .  j  a  v a2s  . c o  m*/

    InputStream input = httpMethod.getResponseBodyAsStream();

    if (input == null) {
        throw new IOException("Response body is null.");
    }

    /*
     * we want to set a max on the number of bytes to download. We do not want a rogue server to return 1GB.
     */
    InputStream limitInput = new SizeLimitedInputStream(input, MAX_HTTP_RESPONSE_SIZE);

    String response = IOUtils.toString(limitInput, CharEncoding.US_ASCII);

    if (logger.isDebugEnabled()) {
        logger.debug("Response:\r\n" + response);
    }

    Map<String, String[]> parameters = NetUtils.parseQuery(response);

    errorCode = CustomClientStatusCode.fromCode(getValue(parameters, "errorCode"));

    if (errorCode.getID() < CustomClientStatusCode.SUCCESSFUL.getID()) {
        error = true;

        errorMessage = getValue(parameters, "errorMessage");
    } else {
        error = false;

        verificationLevel = getValue(parameters, "verificationLevel");
        accountStatus = getValue(parameters, "accountStatus");
        resellerStatus = getValue(parameters, "resellerStatus");
        webHostResellerStatus = getValue(parameters, "webHostResellerStatus");
        epkiStatus = getValue(parameters, "epkiStatus");
        capLiveCCCs = getValue(parameters, "capLiveCCCs");
        peakLiveCCCs = getValue(parameters, "peakLiveCCCs");
        currentLiveCCCs = getValue(parameters, "currentLiveCCCs");
        authorizedDomains = getValue(parameters, "authorizedDomains");
    }
}

From source file:com.thoughtworks.twist.mingle.core.MingleClient.java

public TaskData getTaskData(String taskId) {
    HttpMethod method = getMethod(cardUrl(taskId));
    try {//from www .  j  ava  2 s.  co m
        switch (executeMethod(method)) {
        case HttpStatus.SC_OK:
            return (TaskData) parse(getResponse(method));
        case HttpStatus.SC_UNAUTHORIZED:
            throw new MingleAuthenticationException(
                    "Could not authenticate user. Check username and password.");
        default:
            throw new RuntimeException("Got an http response that I do not know how to handle");
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:edu.stanford.base.batch.RawCollectionsExample.java

/**
 * @param subcat//w w w.  j a  va 2  s . co m
 * @throws IOException
 * @throws HttpException
 * @throws JsonParseException
 * @throws URISyntaxException 
 */
public static void pullSearsProducts(String subcat)
        throws IOException, HttpException, JsonParseException, URISyntaxException {
    StringBuffer reponse = new StringBuffer();
    //http://api.developer.sears.com/v1/productsearch?apikey=09b9aeb25ff985a9c85d877f8a9c4dd9&store=Sears&verticalName=Appliances&categoryName=Refrigerators&searchType=category&productsOnly=1&contentType=json
    //String request = "http://api.developer.sears.com/v1/productsearch?apikey=09b9aeb25ff985a9c85d877f8a9c4dd9&store=Sears&verticalName=Appliances&categoryName=Refrigerators&subCategoryName=Side-by-Side+Refrigerators&searchType=subcategory&productsOnly=1&endIndex=1000&startIndex=1&contentType=json";
    String request = "http://api.developer.sears.com/v1/productsearch?apikey=09b9aeb25ff985a9c85d877f8a9c4dd9&store=Sears&verticalName=Appliances&categoryName=Refrigerators&subCategoryName="
            + subcat + "&searchType=subcategory&productsOnly=1&contentType=json&endIndex=1000&startIndex=1";

    URI uri = new URI(request);
    URL url = uri.toURL();
    //Compact+Refrigerators
    System.out.println(url);
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(request);

    // Send GET request
    int statusCode = client.executeMethod(method);

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

    // Get the response body
    rstream = method.getResponseBodyAsStream();

    // Process the response from Yahoo! Web Services
    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    String line;
    while ((line = br.readLine()) != null) {
        reponse.append(line);
        System.out.println(line);
    }
    br.close();
    Gson gson = new Gson();
    /*   // gson.registerTypeAdapter(Event.class, new MyInstanceCreator());
        Collection collection = new ArrayList();
        collection.add("hello");
        collection.add(5);
        collection.add(new Event("GREETINGS", "guest"));
        String json2 = gson.toJson(collection);
        System.out.println("Using Gson.toJson() on a raw collection: " + json2);*/
    JsonParser parser = new JsonParser();
    //JsonArray array = parser.parse(json1).getAsJsonArray();

    String products = StringUtils.remove(reponse.toString(),
            "{\"mercadoresult\":{\"products\":{\"product\":[true,");
    //System.out.println(products);
    String productsList = StringUtils.substring(products, 0, StringUtils.indexOf(products, "productcount") - 3);
    // System.out.println(productsList);
    productsList = "[" + StringUtils.replaceOnce(productsList, "}}]]", "}]]");
    //System.out.println(productsList);
    List<SearsProduct> prodList = new ArrayList<SearsProduct>();

    // Reader reader = new InputStreamReader(productsList);
    Gson gson1 = new GsonBuilder().create();
    JsonArray array1 = parser.parse(productsList).getAsJsonArray();

    JsonArray prodArray = (JsonArray) array1.get(0);

    // prodList= gson1.fromJson(array1.get(2), ArrayList.class);

    for (JsonElement jsonElement : prodArray) {

        prodList.add(gson.fromJson(jsonElement, SearsProduct.class));
        //System.out.println(gson.fromJson(jsonElement, SearsProduct.class));

    }

    PullSearsProductsDAO pullSearsProductsDAO = new PullSearsProductsDAO();

    try {
        pullSearsProductsDAO.pullAllProducts(prodList);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.cloud.network.nicira.NiciraNvpApiTest.java

@Test
public void testFindSecurityProfileByUuid() throws NiciraNvpApiException, IOException {
    // Prepare/*from   w w  w. ja  va 2s.  c  om*/
    method = mock(GetMethod.class);
    when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
    when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE);
    final NameValuePair[] queryString = new NameValuePair[] { new NameValuePair("uuid", UUID),
            new NameValuePair("fields", "*") };
    final List<NameValuePair> queryStringNvps = new ArrayList<>();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            final NameValuePair[] arguments = (NameValuePair[]) invocation.getArguments()[0];
            queryStringNvps.addAll(Arrays.asList(arguments));
            return null;
        }
    }).when(method).setQueryString(any(NameValuePair[].class));

    // Execute
    final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile(UUID);

    // Assert
    verify(method, times(1)).releaseConnection();
    assertTrue(queryStringNvps.containsAll(Arrays.asList(queryString)));
    assertEquals(queryString.length, queryStringNvps.size());
    assertEquals("Wrong Uuid in the newly created SecurityProfile", UUID,
            actualProfiles.getResults().get(0).getUuid());
    assertEquals("Wrong Uuid in the newly created SecurityProfile", HREF,
            actualProfiles.getResults().get(0).getHref());
    assertEquals("Wrong Schema in the newly created SecurityProfile", SCHEMA,
            actualProfiles.getResults().get(0).getSchema());
    assertEquals("Wrong Uuid in the newly created SecurityProfile", UUID2,
            actualProfiles.getResults().get(1).getUuid());
    assertEquals("Wrong Uuid in the newly created SecurityProfile", HREF2,
            actualProfiles.getResults().get(1).getHref());
    assertEquals("Wrong Schema in the newly created SecurityProfile", SCHEMA2,
            actualProfiles.getResults().get(1).getSchema());
    assertEquals("Wrong Schema in the newly created SecurityProfile", 2, actualProfiles.getResultCount());
    assertEquals("Wrong URI for SecurityProfile creation REST service", NiciraNvpApi.SEC_PROFILE_URI_PREFIX,
            uri);
    assertEquals("Wrong HTTP method for SecurityProfile creation REST service", NiciraNvpApi.GET_METHOD_TYPE,
            type);
}