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:edu.unc.lib.dl.fedora.FedoraAccessControlService.java

public boolean hasAccess(PID pid, AccessGroupSet groups, Permission permission) {
    GetMethod method = new GetMethod(this.aclEndpointUrl + pid.getPid() + "/hasAccess/" + permission.name());
    try {/* w  ww.j a va 2s.  co  m*/
        method.setQueryString(
                new NameValuePair[] { new NameValuePair("groups", groups.joinAccessGroups(";")) });
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            String response = method.getResponseBodyAsString();
            Boolean hasAccess = Boolean.parseBoolean(response);
            return hasAccess != null && hasAccess;
        }
    } catch (HttpException e) {
        log.error("Failed to check hasAccess for " + pid, e);
    } catch (IOException e) {
        log.error("Failed to check hasAccess for " + pid, e);
    } finally {
        method.releaseConnection();
    }

    return false;
}

From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java

public void testSingleFileImport() {
    // create client and configure it
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    // instantiating a new method and configuring it
    PostMethod method = new PostMethod(restCommandUrlPrefix + "import");
    // Provide custom retry handler is necessary (?)
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] params = new NameValuePair[] { new NameValuePair("path", "/app:company_home"),
            new NameValuePair("ticket", ticket) };
    method.setQueryString(params);/*from  w  ww.j  a v a 2 s.c  om*/

    try {
        //method.setRequestBody(new NameValuePair[] {
        //      new NameValuePair("path", "/app:company_home") });
        FileInputStream acpXmlIs = new FileInputStream(SAMPLE_SINGLE_FILE_PATH);
        InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs);
        //InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs, "text/xml; charset=ISO-8859-1");
        method.setRequestEntity(entity);
    } catch (IOException ioex) {
        fail("ACP XML file not found " + ioex.getMessage());
    }

    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();
        System.out.println(new String(responseBody)); // TODO rm

        HashSet<String> defaultElementSet = new HashSet<String>(
                Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE,
                        RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE }));
        HashMap<String, String> elementValueMap = new HashMap<String, String>(6);

        try {
            XMLEventReader xmlReader = XmlHelper.getXMLInputFactory()
                    .createXMLEventReader(new ByteArrayInputStream(responseBody));
            StringBuffer singleLevelTextBuf = null;
            while (xmlReader.hasNext()) {
                XMLEvent event = xmlReader.nextEvent();
                switch (event.getEventType()) {
                case XMLEvent.CHARACTERS:
                case XMLEvent.CDATA:
                    if (singleLevelTextBuf != null) {
                        singleLevelTextBuf.append(event.asCharacters().getData());
                    } // else element not meaningful
                    break;
                case XMLEvent.START_ELEMENT:
                    StartElement startElement = event.asStartElement();
                    String elementName = startElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)
                            // TODO another command specific level
                            || "ticket".equals(elementName)) {
                        // reinit buffer at start of meaningful elements
                        singleLevelTextBuf = new StringBuffer();
                    } else {
                        singleLevelTextBuf = null; // not useful
                    }
                    break;
                case XMLEvent.END_ELEMENT:
                    if (singleLevelTextBuf == null) {
                        break; // element not meaningful
                    }

                    // TODO or merely put it in the map since the element has been tested at start
                    EndElement endElement = event.asEndElement();
                    elementName = endElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)) {
                        String value = singleLevelTextBuf.toString();
                        elementValueMap.put(elementName, value);
                        // TODO test if it is code and it is not OK, break to error handling
                    }
                    // TODO another command specific level
                    else if ("ticket".equals(elementName)) {
                        ticket = singleLevelTextBuf.toString();
                    }
                    // singleLevelTextBuf = new StringBuffer(); // no ! in start
                    break;
                }
            }
        } catch (XMLStreamException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Throwable t) {
            // TODO Auto-generated catch block
            t.printStackTrace();
            //throw t;
        }

        String code = elementValueMap.get(RestConstants.TAG_CODE);
        assertTrue(RestConstants.CODE_OK.equals(code));
        System.out.println("got ticket " + ticket);

    } catch (HttpException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:it.geosolutions.geonetwork.util.HTTPUtils.java

/**
 * Performs an HTTP GET on the given URL.
 *
 * @param url       The URL where to connect to.
 * @return          The HTTP response as a String if the HTTP response code was 200 (OK).
 * @throws MalformedURLException/*from  w  ww  .ja v a2  s  .c o m*/
 */
public String get(String url) throws MalformedURLException {

    GetMethod httpMethod = null;
    try {
        setAuth(client, url, username, pw);
        httpMethod = new GetMethod(url);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        lastHttpStatus = client.executeMethod(httpMethod);
        if (lastHttpStatus == HttpStatus.SC_OK) {
            InputStream is = httpMethod.getResponseBodyAsStream();
            String response = IOUtils.toString(is);
            if (response.trim().length() == 0) { // sometime gs rest fails
                LOGGER.warn("ResponseBody is empty");
                return null;
            } else {
                return response;
            }
        } else {
            LOGGER.info("(" + lastHttpStatus + ") " + HttpStatus.getStatusText(lastHttpStatus) + " -- " + url);
        }
    } catch (ConnectException e) {
        LOGGER.info("Couldn't connect to [" + url + "]");
    } catch (IOException e) {
        LOGGER.info("Error talking to [" + url + "]", e);
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
    }

    return null;
}

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

/**
 * Test Logout./*from w w  w. j a v a2  s.c o  m*/
 */
@Test
public void ifLoggedInThenLogout() {
    // given
    final String requestUrl = RestApiTest.URL_ROOT + "/security/logout";
    final UserAccount loggedInUser = this.doLogin(SecurityApiIT.VALID_EMAIL, SecurityApiIT.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 String json = given().headers(headers).expect().statusCode(HttpStatus.SC_OK).when().post(requestUrl)
            .asString();

    assertNotNull(json);
    assertEquals("true", json);
}

From source file:com.comcast.cats.jenkins.service.AbstractService.java

/**
 * Sends Http request to Jenkins server and read the respose.
 * /*from  w  w w . j a  va2 s  . co m*/
 * @param mapperClass
 * @param domainObject
 * @param client
 * @param request
 * @return
 * @throws NumberFormatException
 * @throws IOException
 * @throws HttpException
 * @throws URIException
 */
private Object sendRequestToJenkins(Class<?> mapperClass, Object domainObject, HttpClient client,
        HttpMethodBase request, String apiToken)
        throws NumberFormatException, IOException, HttpException, URIException {
    String passwdord = apiToken;
    if (apiToken.isEmpty()) {
        // Set jenkins password if no API token is present
        passwdord = jenkinsClientProperties.getJenkinsPassword();
    }
    client.getState().setCredentials(
            new AuthScope(jenkinsClientProperties.getJenkinsHost(),
                    new Integer(jenkinsClientProperties.getJenkinsPort()), AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(jenkinsClientProperties.getJenkinsUsername(), passwdord));
    if (!apiToken.isEmpty()) {
        client.getParams().setAuthenticationPreemptive(true);
    }

    int responseCode = client.executeMethod(request);

    LOGGER.info("[REQUEST][" + request.getURI().toString() + "]");
    LOGGER.info("[STATUS][" + request.getStatusLine().toString() + "]");

    if (HttpStatus.SC_OK == responseCode) {
        try {
            Serializer serializer = new Persister();
            domainObject = serializer.read(mapperClass, request.getResponseBodyAsStream(), false);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }
    return domainObject;
}

From source file:com.eviware.soapui.impl.support.AbstractMockResponse.java

public AbstractMockResponse(MockResponseConfigType config, MockOperation operation, String icon) {
    super(config, operation, icon);
    scriptEnginePool = new ScriptEnginePool(this);
    scriptEnginePool.setScript(getScript());
    propertyHolder = new MapTestPropertyHolder(this);
    propertyHolder.addProperty("Request");

    if (!config.isSetHttpResponseStatus()) {
        config.setHttpResponseStatus("" + HttpStatus.SC_OK);
    }//from www.j av a  2 s .c  om

}

From source file:cuanto.api.CuantoConnector.java

/**
 * Gets the TestRun from the Cuanto server.
 *
 * @param testRunId The TestRun to retrieve.
 * @return The retrieved TestRun.//from   w  ww  .  java  2  s .c  o  m
 */
public TestRun getTestRun(Long testRunId) {
    GetMethod get = (GetMethod) getHttpMethod(HTTP_GET,
            getCuantoUrl() + "/api/getTestRun/" + testRunId.toString());

    try {
        int httpStatus = getHttpClient().executeMethod(get);
        if (httpStatus == HttpStatus.SC_OK) {
            return TestRun.fromJSON(getResponseBodyAsString(get));
        } else {
            throw new RuntimeException("Getting the TestRun failed with HTTP status code " + httpStatus + ":\n"
                    + getResponseBodyAsString(get));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ParseException e) {
        throw new RuntimeException("Unable to parse JSON response", e);
    }
}

From source file:com.epam.wilma.service.http.WilmaHttpClient.java

/**
 * Posting the given file to the given URL via HTTP POST method and returns
 * {@code true} if the request was successful.
 *
 * @param url the given URL//w  w w.  ja  v  a 2  s .co m
 * @param file the given file
 * @return {@code true} if the request is successful, otherwise return {@code false}
 */
public boolean uploadFile(String url, File file) {
    boolean requestSuccessful = false;

    PostMethod method = new PostMethod(url);

    try {
        Part[] parts = { new FilePart("file", file) };
        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

        int statusCode = httpclient.executeMethod(method);
        if (HttpStatus.SC_OK == statusCode) {
            requestSuccessful = true;
        }
    } catch (HttpException e) {
        LOG.error("Protocol exception occurred when called: " + url, e);
    } catch (IOException e) {
        LOG.error("I/O (transport) error occurred when called: " + url, e);
    } finally {
        method.releaseConnection();
    }

    return requestSuccessful;
}

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

private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException {
    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("Error Collecting certificate. Message: " + httpMethod.getStatusLine());
    }/*from   w w  w .j  a va  2 s .  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);
    }

    LineNumberReader lineReader = new LineNumberReader(new StringReader(response));

    String statusParameter = lineReader.readLine();

    errorCode = CustomClientStatusCode.fromCode(statusParameter);

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

        errorMessage = lineReader.readLine();
    } else {
        error = false;

        if (errorCode == CustomClientStatusCode.CERTIFICATES_ATTACHED) {
            /*
             * The certificate is base64 encoded between -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----
             */

            StrBuilder base64 = new StrBuilder(4096);

            /* 
             * Skip -----BEGIN CERTIFICATE-----
             */
            String line = lineReader.readLine();

            if (!"-----BEGIN CERTIFICATE-----".equalsIgnoreCase(line)) {
                throw new IOException("-----BEGIN CERTIFICATE----- expected but got: " + line);
            }

            do {
                line = lineReader.readLine();

                if ("-----END CERTIFICATE-----".equalsIgnoreCase(line)) {
                    break;
                }

                if (line != null) {
                    base64.append(line);
                }
            } while (line != null);

            try {
                byte[] decoded = Base64.decodeBase64(MiscStringUtils.toAsciiBytes(base64.toString()));

                Collection<X509Certificate> certificates = CertificateUtils
                        .readX509Certificates(new ByteArrayInputStream(decoded));

                if (certificates != null && certificates.size() > 0) {
                    certificate = certificates.iterator().next();
                }
            } catch (CertificateException e) {
                throw new IOException(e);
            } catch (NoSuchProviderException e) {
                throw new IOException(e);
            }
        }
    }
}

From source file:com.nokia.helium.diamonds.DiamondsSessionSocket.java

/**
 * Internal method to send data to diamonds.
 * If ignore result is true, then the method will return null, else the message return by the query
 * will be returned./* ww  w .j av a 2  s .c om*/
 * @param message
 * @param ignoreResult
 * @return
 * @throws DiamondsException is thrown in case of message retrieval error, connection error. 
 */
protected synchronized String sendInternal(Message message, boolean ignoreResult) throws DiamondsException {
    URL destURL = url;
    if (buildId != null) {
        try {
            destURL = new URL(url.getProtocol(), url.getHost(), url.getPort(), buildId);
        } catch (MalformedURLException e) {
            throw new DiamondsException("Error generating the url to send the message: " + e.getMessage(), e);
        }
    }
    PostMethod post = new PostMethod(destURL.toExternalForm());
    try {
        File tempFile = streamToTempFile(message.getInputStream());
        tempFile.deleteOnExit();
        messages.add(tempFile);
        post.setRequestEntity(new FileRequestEntity(tempFile, "text/xml"));
    } catch (MessageCreationException e) {
        throw new DiamondsException("Error retrieving the message: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new DiamondsException("Error serializing the message into a temporary file: " + e.getMessage(),
                e);
    }
    try {
        int result = httpClient.executeMethod(post);
        if (result != HttpStatus.SC_OK && result != HttpStatus.SC_ACCEPTED) {
            throw new DiamondsException("Error sending the message: " + post.getStatusLine() + "("
                    + post.getResponseBodyAsString() + ")");
        }
        if (!ignoreResult) {
            return post.getResponseBodyAsString();
        }
    } catch (HttpException e) {
        throw new DiamondsException("Error sending the message: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new DiamondsException("Error sending the message: " + e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
    return null;
}