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:com.datatorrent.demos.yahoofinance.StockTickInput.java

@Override
public void emitTuples() {

    try {/*from w ww. j  a  va  2s  .c  o  m*/
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: " + method.getStatusLine());
        } else {
            InputStream istream = method.getResponseBodyAsStream();
            // Process response
            InputStreamReader isr = new InputStreamReader(istream);
            CSVReader reader = new CSVReader(isr);
            List<String[]> myEntries = reader.readAll();
            for (String[] stringArr : myEntries) {
                ArrayList<String> tuple = new ArrayList<String>(Arrays.asList(stringArr));
                if (tuple.size() != 4) {
                    return;
                }
                // input csv is <Symbol>,<Price>,<Volume>,<Time>
                String symbol = tuple.get(0);
                double currentPrice = Double.valueOf(tuple.get(1));
                long currentVolume = Long.valueOf(tuple.get(2));
                String timeStamp = tuple.get(3);
                long vol = currentVolume;
                // Sends total volume in first tick, and incremental volume afterwards.
                if (lastVolume.containsKey(symbol)) {
                    vol -= lastVolume.get(symbol);
                }

                if (vol > 0 || outputEvenIfZeroVolume) {
                    price.emit(new KeyValPair<String, Double>(symbol, currentPrice));
                    volume.emit(new KeyValPair<String, Long>(symbol, vol));
                    time.emit(new KeyValPair<String, String>(symbol, timeStamp));
                    lastVolume.put(symbol, currentVolume);
                }
            }
        }
        Thread.sleep(readIntervalMillis);
    } catch (InterruptedException ex) {
        logger.debug(ex.toString());
    } catch (IOException ex) {
        logger.debug(ex.toString());
    }
}

From source file:com.cerema.cloud2.lib.resources.files.ExistenceCheckRemoteOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    HeadMethod head = null;//from  www .java 2  s .  com
    boolean previousFollowRedirects = client.getFollowRedirects();
    try {
        head = new HeadMethod(client.getWebdavUri() + WebdavUtils.encodePath(mPath));
        client.setFollowRedirects(false);
        int status = client.executeMethod(head, TIMEOUT, TIMEOUT);
        if (previousFollowRedirects) {
            mRedirectionPath = client.followRedirection(head);
            status = mRedirectionPath.getLastStatus();
        }
        client.exhaustResponse(head.getResponseBodyAsStream());
        boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent)
                || (status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent);
        result = new RemoteOperationResult(success, status, head.getResponseHeaders());
        Log_OC.d(TAG,
                "Existence check for " + client.getWebdavUri() + WebdavUtils.encodePath(mPath)
                        + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ")
                        + "finished with HTTP status " + status + (!success ? "(FAIL)" : ""));

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG,
                "Existence check for " + client.getWebdavUri() + WebdavUtils.encodePath(mPath)
                        + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + ": "
                        + result.getLogMessage(),
                result.getException());

    } finally {
        if (head != null)
            head.releaseConnection();
        client.setFollowRedirects(previousFollowRedirects);
    }
    return result;
}

From source file:it.geosolutions.geostore.services.rest.security.WebServiceTokenAuthenticationFilter.java

@Override
protected Authentication checkToken(String token) {
    String webServiceUrl = url.replace("{token}", token);
    HttpClient client = getHttpClient();
    client.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, connectTimeout * 1000l);
    client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, readTimeout * 1000);
    HttpMethod method = null;/*  www .  ja  va2s. c o m*/
    try {
        LOGGER.debug("Issuing request to webservice: " + url);
        method = new GetMethod(webServiceUrl);
        int statusCode = client.executeMethod(method);

        if (statusCode == HttpStatus.SC_OK) {
            // get response content as a single string, without new lines
            // so that is simpler to apply an extraction regular expression
            String response = method.getResponseBodyAsString().replace("\r", "").replace("\n", "");
            if (response != null) {
                if (searchUserRegex == null) {
                    return createAuthenticationForUser(response, null, "");
                } else {
                    Matcher matcher = searchUserRegex.matcher(response);
                    if (matcher.find()) {
                        return createAuthenticationForUser(matcher.group(1), null, response);
                    } else {
                        LOGGER.warn(
                                "Error in getting username from webservice response cannot find userName in response");
                    }
                }
            } else {
                LOGGER.error("No response received from webservice: " + url);
            }
        }
    } catch (HttpException e) {
        LOGGER.error("Error contacting webservice: " + url, e);
    } catch (IOException e) {
        LOGGER.error("Error reading data from webservice: " + url, e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return null;

}

From source file:controllers.sparql.SparqlQueryExecuter.java

public String request(URL url) throws SparqlExecutionException {
    GetMethod method = new GetMethod(url.toString());
    String response = null;//from w w w  .ja  v  a  2 s. c  o m

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

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

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("SparqlQuery failed: " + method.getStatusLine());
            throw new SparqlExecutionException(String.format("%s (%s). %s", method.getStatusLine(),
                    method.getURI(), method.getResponseBodyAsString()));
        }

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

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        response = new String(responseBody);

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

}

From source file:com.cordys.coe.ac.httpconnector.execution.MethodExecutor.java

/**
 * Send the HTTP request to the web server and returns the response.
 * //from   w w w  . java  2  s.  c  o m
 * @param reqNode
 *            Request XML node.
 * @param serverConnection
 *            Server connection information.
 * @param methodInfo
 *            Method information information.
 * @param counters
 *            JMX performance counters
 * @return Response XML node.
 * @throws ConnectorException
 * @throws HandlerException
 */
public static int sendRequest(int reqNode, IServerConnection serverConnection, IMethodConfiguration methodInfo,
        PerformanceCounters counters) throws ConnectorException, HandlerException {
    boolean setJMXInfo = counters == null ? false : true;
    // Get request and response handlers for converting the data.
    IRequestHandler requestHandler = methodInfo.getRequestHandler();
    IResponseHandler responseHandler = methodInfo.getResponseHandler();

    // Create the connection
    HttpClient client = serverConnection.getHttpClient();

    client.getParams().setContentCharset("UTF-8");
    client.getParams().setCredentialCharset("UTF-8");
    client.getParams().setHttpElementCharset("UTF-8");

    HttpMethod httpMethod;
    int timeout = serverConnection.getTimeout();

    // Convert the SOAP request XML into an HTTP request.
    long startTime = 0;
    if (setJMXInfo) {
        startTime = counters.getStartTime();
    }
    httpMethod = requestHandler.process(reqNode, serverConnection, client);
    if (setJMXInfo) {
        counters.finishRequestTransformation(startTime);
    }

    // Set additional HTTP parameters.
    HttpMethodParams hmpMethodParams = httpMethod.getParams();

    if (hmpMethodParams != null) {
        // Set the authentication character set to UTF-8, if not set.
        String sCredCharset = hmpMethodParams.getCredentialCharset();

        if ((sCredCharset == null) || (sCredCharset.length() == 0)) {
            hmpMethodParams.setCredentialCharset("UTF-8");
        }

        if (timeout > 0) {
            hmpMethodParams.setSoTimeout(timeout);
        }
    }

    // Send the request and handle the response.
    try {
        if (setJMXInfo) {
            startTime = counters.getStartTime();
        }
        int statusCode = client.executeMethod(httpMethod);
        if (setJMXInfo) {
            counters.finishHTTP(startTime);
        }
        int validStatusCode = methodInfo.getValidResponseCode();

        if (statusCode != HttpStatus.SC_OK) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Received HTTP error code: " + statusCode);
            }
        }

        if (setJMXInfo) {
            startTime = counters.getStartTime();
        }
        // Convert the response into XML.
        int responseNode = responseHandler.convertResponseToXml(httpMethod, serverConnection,
                Node.getDocument(reqNode));
        if (setJMXInfo) {
            counters.finishResponseTransformation(startTime);
        }
        if ((validStatusCode >= 0) && (statusCode != validStatusCode)) {
            if (responseNode != 0) {
                Node.delete(responseNode);
                responseNode = 0;
            }

            throw new ConnectorException(ConnectorExceptionMessages.INVALID_STATUS_CODE_RECEIVED_0_EXPECTED_1,
                    statusCode, validStatusCode);
        }

        return responseNode;
    } catch (ConnectorException e) {
        throw e;
    } catch (HttpException e) {
        throw new ConnectorException(e, ConnectorExceptionMessages.HTTP_REQUEST_FAILED_0, e.getMessage());
    } catch (IOException e) {
        throw new ConnectorException(e, ConnectorExceptionMessages.HTTP_CONNECTION_FAILED_0, e.getMessage());
    } catch (XMLException e) {
        throw new ConnectorException((Throwable) e, ConnectorExceptionMessages.INVALID_RESPONSE_XML_RECEIVED);
    } finally {
        // Release the connection.
        httpMethod.releaseConnection();
    }
}

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

@Test
public void testFindSecurityProfile() throws NiciraNvpApiException, IOException {
    // Prepare/*www  .  j  ava 2  s. com*/
    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("fields", "*") };

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

    // Assert
    verify(method, times(1)).releaseConnection();
    verify(method, times(1)).setQueryString(queryString);
    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 URI for SecurityProfile creation REST service", NiciraNvpApi.GET_METHOD_TYPE, type);
}

From source file:com.google.api.ads.dfp.lib.AuthToken.java

/**
 * Retrieves an authentication token using the user's credentials.
 *
 * @return a {@code String} authentication token.
 * @throws AuthTokenException if the status from the Client Login server is
 *     anything but {@code HttpStatus.SC_OK = 200}
 *//*from  ww  w.  ja  v  a  2s .co m*/
public String getAuthToken() throws AuthTokenException {
    try {
        PostMethod postMethod = new PostMethod(CLIENT_LOGIN_URL);

        int statusCode = postToClientLogin(postMethod);
        Properties responseProperties = generatePropertiesFromResponse(postMethod.getResponseBodyAsStream());

        if (statusCode == HttpStatus.SC_OK) {
            if (responseProperties.containsKey(AUTH_TOKEN_KEY)) {
                return responseProperties.getProperty(AUTH_TOKEN_KEY).toString();
            } else {
                throw new IllegalStateException("Unable to get auth token from Client Login server");
            }
        } else {
            CaptchaInformation captchaInfo = null;
            String errorCode = null;

            if (responseProperties.containsKey(ERROR_KEY)) {
                errorCode = responseProperties.getProperty(ERROR_KEY);
                if (errorCode != null && errorCode.equals(CAPTCHA_REQUIRED_ERROR)) {
                    captchaInfo = extractCaptchaInfoFromProperties(responseProperties);
                }

                if (responseProperties.containsKey(INFO_KEY)) {
                    errorCode += ": " + responseProperties.getProperty(INFO_KEY);
                }
            }

            throw new AuthTokenException(statusCode, postMethod.getResponseBodyAsString(), errorCode,
                    captchaInfo, null);
        }
    } catch (IOException e) {
        throw new AuthTokenException(null, null, null, null, e);
    }
}

From source file:net.sf.jaceko.mock.resource.BasicSetupResource.java

@POST
@Path("/{operationId}/init")
public Response initMock(@PathParam("serviceName") String serviceName,
        @PathParam("operationId") String operationId) {
    mockSetupExecutor.initMock(serviceName, operationId);
    return Response.status(HttpStatus.SC_OK).build();
}

From source file:it.geosolutions.geonetwork.op.GNMetadataUpdate.java

/**
 * Insert a metadata in GN.<br/>//from  w w  w  .  j  av  a2 s. c o m
 * 
 * <ul>
 * <li>Url: <tt>http://<i>server</i>:<i>port</i>/geonetwork/srv/en/metadata.update</tt></li>
 * <li>Mime-type: <tt>application/xml</tt></li>
 * <li>Post request: <pre>{@code 
 * 
 * <?xml version="1.0" encoding="UTF-8"?>
 * <request>
 *    <id>2</id>
 *    <version>2</version>
 *    <data><![CDATA[
 *       <gmd:MD_Metadata xmlns:gmd="http://www.isotc211.org/2005/gmd"
 *                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 *       ...
 *          </gmd:DQ_DataQuality>
 *         </gmd:dataQualityInfo>
 *       </gmd:MD_Metadata>]]>
 *    </data>
 * </request> }</pre></li>
 * </ul>
 *      * 
 * @see <a href="http://geonetwork-opensource.org/latest/developers/xml_services/metadata_xml_services.html#insert-metadata-metadata-insert" >GeoNetwork documentation about inserting metadata</a>
 */
private static void gnUpdateMetadata(HTTPUtils connection, String baseURL, final Element gnRequest)
        throws GNLibException, GNServerException {

    String serviceURL = baseURL + "/srv/en/metadata.update.finish";
    connection.setIgnoreResponseContentOnSuccess(true);
    String res = gnPost(connection, serviceURL, gnRequest);
    if (connection.getLastHttpStatus() != HttpStatus.SC_OK)
        throw new GNServerException(
                "Error updating metadata in GeoNetwork (HTTP code " + connection.getLastHttpStatus() + ")");
}

From source file:com.bdaum.juploadr.uploadapi.smugrest.upload.SmugmugUpload.java

@Override
public boolean execute() throws ProtocolException, CommunicationException {
    HttpClient client = HttpClientFactory.getHttpClient(session.getAccount());
    this.monitor.uploadStarted(new UploadEvent(image, 0, true, false));
    SortedMap<String, String> params = getParams();
    String name = params.get(X_SMUG_FILE_NAME);
    PutMethod put = new PutMethod(URL + name);
    for (Map.Entry<String, String> entry : params.entrySet())
        put.addRequestHeader(entry.getKey(), entry.getValue());
    File file = new File(image.getImagePath());
    Asset asset = image.getAsset();/*from   www  .  j  a  v a  2s . co m*/
    FileRequestEntity entity = new FileRequestEntity(file, asset.getMimeType());
    put.setRequestEntity(entity);
    try {
        int status = client.executeMethod(put);
        if (status == HttpStatus.SC_OK) {
            // deal with the response
            try {
                String response = put.getResponseBodyAsString();
                put.releaseConnection();
                boolean success = parseResponse(response);
                if (success) {
                    image.setState(UploadImage.STATE_UPLOADED);
                    ImageUploadResponse resp = new ImageUploadResponse(handler.getPhotoID(), handler.getKey(),
                            handler.getUrl());
                    this.monitor.uploadFinished(new UploadCompleteEvent(resp, image));
                } else {
                    throw new UploadFailedException(Messages.getString("juploadr.ui.error.status")); //$NON-NLS-1$
                }

            } catch (IOException e) {
                // TODO: Is it safe to assume the upload failed here?
                this.fail(Messages.getString("juploadr.ui.error.response.unreadable") //$NON-NLS-1$
                        + e.getMessage(), e);
            }
        } else {
            this.fail(Messages.getString("juploadr.ui.error.bad.http.response", status), null); //$NON-NLS-1$
        }
    } catch (ConnectException ce) {
        this.fail(Messages.getString("juploadr.ui.error.unable.to.connect"), ce); //$NON-NLS-1$
    } catch (NoRouteToHostException route) {
        this.fail(Messages.getString("juploadr.ui.error.no.internet"), route); //$NON-NLS-1$
    } catch (UnknownHostException uhe) {
        this.fail(Messages.getString("juploadr.ui.error.unknown.host"), uhe); //$NON-NLS-1$

    } catch (HttpException e) {
        this.fail(Messages.getString("juploadr.ui.error.http.exception") + e, e); //$NON-NLS-1$
    } catch (IOException e) {
        this.fail(Messages.getString("juploadr.ui.error.simple.ioexception") + e.getMessage() + "" //$NON-NLS-1$ //$NON-NLS-2$
                + e, e);
    }
    return true;
}