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:es.mityc.firmaJava.ts.TSCliente.java

/**
 * Este mtodo genera el Sello de Tiempo/*from w w  w .  ja  v  a 2s .c om*/
 * @param binarioaSellar fichero binario que se va a sellar
 * @return TimeStampToken en formato binario
 * @throws TSClienteError
 */
public byte[] generarSelloTiempo(byte[] binarioaSellar) throws TSClienteError {

    if (binarioaSellar == null) {
        log.error(MENSAJE_NO_DATOS_SELLO_TIEMPO);
        throw new TSClienteError(I18n.getResource(LIBRERIA_TSA_ERROR_1));
    } else {
        log.info(MENSAJE_GENERANDO_SELLO_TIEMPO);
        TimeStampRequestGenerator generadorPeticion = new TimeStampRequestGenerator();
        TimeStampRequest peticion = null;
        TimeStampResponse respuesta = null;

        try {
            MessageDigest resumen = MessageDigest.getInstance(algoritmoHash);
            resumen.update(binarioaSellar);
            peticion = generadorPeticion.generate(TSPAlgoritmos.getOID(algoritmoHash), resumen.digest());
            log.info(MENSAJE_PETICION_TSA_GENERADA);
        } catch (Exception e) {
            log.error(MENSAJE_ERROR_PETICION_TSA);
            throw new TSClienteError(I18n.getResource(LIBRERIA_TSA_ERROR_10));
        }

        cliente.getParams().setParameter(HttpClientParams.SO_TIMEOUT, INT5000);

        // Comprueba si hay configurado un proxy
        String servidorProxy = System.getProperty("http.proxyHost");
        if (servidorProxy != null && !servidorProxy.trim().equals(CADENA_VACIA)) {
            int puertoProxy = 80;
            try {
                puertoProxy = Integer.parseInt(System.getProperty("http.proxyPort"));
            } catch (NumberFormatException ex) {
            }
            cliente.getHostConfiguration().setProxy(servidorProxy, puertoProxy);

            Credentials defaultcreds = new AuthenticatorProxyCredentials(servidorProxy, CADENA_VACIA);
            cliente.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
        }

        PostMethod metodo = new PostMethod(servidorTSA);
        metodo.addRequestHeader(CONTENT_TYPE, APPLICATION_TIMESTAMP_QUERY);
        ByteArrayInputStream datos = null;
        try {
            datos = new ByteArrayInputStream(peticion.getEncoded());
        } catch (IOException e) {
            log.error(MENSAJE_ERROR_PETICION + e.getMessage());
            throw new TSClienteError(
                    I18n.getResource(LIBRERIA_TSA_ERROR_11) + DOS_PUNTOS_ESPACIO + e.getMessage());
        }

        InputStreamRequestEntity rq = new InputStreamRequestEntity(datos);
        metodo.setRequestEntity(rq);

        metodo.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        byte[] cuerpoRespuesta = null;
        try {
            int estadoCodigo = cliente.executeMethod(metodo);
            log.info(MENSAJE_PETICION_TSA_ENVIADA);

            if (estadoCodigo != HttpStatus.SC_OK) {

                log.error(MENSAJE_FALLO_EJECUCION_METODO + metodo.getStatusLine());
                throw new TSClienteError(
                        I18n.getResource(LIBRERIA_TSA_ERROR_12) + DOS_PUNTOS_ESPACIO + metodo.getStatusLine());
            }

            cuerpoRespuesta = metodo.getResponseBody();
            log.info(MENSAJE_RESPUESTA_TSA_OBTENIDA);

            try {
                respuesta = new TimeStampResponse(cuerpoRespuesta);
                try {

                    respuesta.validate(peticion);

                    log.info(MENSAJE_RESPUESTA_TSA_VALIDADA_OK);
                    // Para solucionar bug en libreria bouncycastle
                    //return respuesta.getTimeStampToken().getEncoded();
                    //AppPerfect: Falso positivo
                    ASN1InputStream is = new ASN1InputStream(cuerpoRespuesta);
                    ASN1Sequence seq = ASN1Sequence.getInstance(is.readObject());
                    DEREncodable enc = seq.getObjectAt(1);
                    if (enc == null)
                        return null;
                    return enc.getDERObject().getEncoded();
                    //Fin Para solucionar bug en libreria bouncycastle
                } catch (TSPException e) {
                    log.error(MENSAJE_RESPUESTA_NO_VALIDA + e.getMessage());
                    throw new TSClienteError(
                            I18n.getResource(LIBRERIA_TSA_ERROR_9) + DOS_PUNTOS_ESPACIO + e.getMessage());
                }
            } catch (TSPException e) {
                log.error(MENSAJE_RESPUESTA_MAL_FORMADA + e.getMessage());
                throw new TSClienteError(
                        I18n.getResource(LIBRERIA_TSA_ERROR_8) + DOS_PUNTOS_ESPACIO + e.getMessage());
            } catch (IOException e) {

                log.error(MENSAJE_SECUENCIA_BYTES_MAL_CODIFICADA + e.getMessage());
                throw new TSClienteError(
                        I18n.getResource(LIBRERIA_TSA_ERROR_7) + DOS_PUNTOS_ESPACIO + e.getMessage());
            }
        } catch (HttpException e) {
            log.error(MENSAJE_VIOLACION_PROTOCOLO_HTTP + e.getMessage());
            throw new TSClienteError(
                    I18n.getResource(LIBRERIA_TSA_ERROR_6) + DOS_PUNTOS_ESPACIO + e.getMessage());
        } catch (IOException e) {
            String mensajeError = I18n.getResource(LIBRERIA_TSA_ERROR_4) + DOS_PUNTOS_ESPACIO + servidorTSA;
            log.error(MENSAJE_ERROR_CONEXION_SERVIDOR_OCSP + e.getMessage());

            throw new TSClienteError(mensajeError);
        } finally {
            // Termina la conexin
            metodo.releaseConnection();
        }
    }
}

From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java

/**
 * ()use httpState to create httpmethod.
 * /*from   ww w. j a v  a  2s  .co m*/
 * @param httpMethod
 *            the http method
 * @param httpClientConfig
 *            the http client config
 * @return the http method
 * @throws HttpClientException
 *             ?HttpClientUtilException?
 */
private static HttpMethod executeMethod(HttpMethod httpMethod, HttpClientConfig httpClientConfig)
        throws HttpClientException {
    HttpClient httpClient = new HttpClient();

    // ?
    setAuthentication(httpMethod, httpClientConfig, httpClient);

    // ?
    setProxy(httpClientConfig, httpClient);

    try {

        if (log.isDebugEnabled()) {
            // String[] excludes = new String[] { "defaults" };
            // HttpClientParams httpClientParams = httpClient.getParams();
            //
            // log.debug("[httpClient.getParams()]:{}", JsonUtil.format(httpClientParams, excludes));
            //
            // HttpMethodParams httpMethodParams = httpMethod.getParams();
            // log.debug("[httpMethod.getParams()]:{}", JsonUtil.format(httpMethodParams, excludes));

            Map<String, Object> map = getHttpMethodRequestAttributeMapForLog(httpMethod);
            String[] excludes = new String[] { "values", "elements"
                    // "rawAuthority",
                    // "rawCurrentHierPath",
                    // "rawPath",
                    // "rawPathQuery",
                    // "rawQuery",
                    // "rawScheme",
                    // "rawURI",
                    // "rawURIReference",
                    // "rawUserinfo",
                    // "rawFragment",
                    // "rawHost",
                    // "rawName",
                    // "protocol",
                    // "defaults",
                    // "class"
            };
            log.debug(JsonUtil.format(map, excludes));
        }

        // ????
        // ?????????
        // ?GetMethod?
        int statusCode = httpClient.executeMethod(httpMethod);
        if (statusCode != HttpStatus.SC_OK) {
            log.warn("statusCode is:[{}]", statusCode);
        }

    } catch (Exception e) {
        //SSL?
        //PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed
        Map<String, Object> map = getHttpMethodResponseAttributeMapForLog(httpMethod, httpClientConfig);
        log.error(e.getClass().getName() + " HttpMethodResponseAttributeMapForLog:" + JsonUtil.format(map), e);
        throw new HttpClientException(e);
    }
    return httpMethod;
}

From source file:com.serena.rlc.provider.jira.client.JiraClient.java

/**
 * Execute a put request//w w w.ja v  a  2s.c o  m
 *
 * @param url
 * @return Response body
 * @throws JiraClientException
 */
private String processPut(SessionData session, String restUrl, String url, String putData)
        throws JiraClientException {
    String uri = restUrl + url;

    logger.debug("Start executing JIRA PUT request to url=\"{}\" with payload={}", uri);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPut putRequest = new HttpPut(uri);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getJiraUsername(), getJiraPassword());
    putRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    putRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    putRequest.addHeader(HttpHeaders.ACCEPT, "application/json");
    String result = "";

    try {
        putRequest.setEntity(new StringEntity(putData));

        HttpResponse response = httpClient.execute(putRequest);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createHttpError(response);
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        StringBuilder sb = new StringBuilder(1024);
        String output;
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }

        logger.debug("End executing JIRA PUT request to url=\"{}\" and receive this result={}", uri, sb);

        return sb.toString();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new JiraClientException("Server not available", e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.isencia.passerelle.model.util.RESTFacade.java

private String invokeMethodForURL(HttpMethod method) {
    try {/*from  ww  w .  j  a v a  2 s.  co  m*/
        // Execute the method.
        int statusCode = httpClient.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Response status error : " + method.getStatusLine());
        }

        String response = method.getResponseBodyAsString();
        if (logger.isDebugEnabled()) {
            logger.debug("Received response\n" + response);
        }

        return response;
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: ", e);
        return null;
    } catch (IOException e) {
        logger.error("Fatal transport error: ", e);
        return null;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:de.lemo.apps.restws.client.InitialisationImpl.java

public Boolean defaultConnectionCheck() throws RestServiceCommunicationException {

    try {//from   ww w  .ja v a 2 s. c  om
        // not a proxy object because we want to get the http status
        ClientRequest request = new ClientRequest(InitialisationImpl.SERVICE_STARTTIME_URL, clientExecutor);
        ClientResponse<ServiceStartTime> response = request.get(ServiceStartTime.class);

        if (response.getStatus() != HttpStatus.SC_OK) {
            throw new ClientProtocolException(
                    "Default Connection Check: Failed : HTTP error code : " + response.getStatus());
        }
        response.releaseConnection();
        return true;
    } catch (final Exception e) {
        throw new RestServiceCommunicationException(this.toString() + " " + e.getLocalizedMessage());
    }

}

From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java

private static int executeHttpMethod(HttpMethod method) throws Exception {
    HttpClient client = new HttpClient();
    int statusCode;
    try {/*from   w  w w  .  j av a2s .c o m*/
        statusCode = client.executeMethod(method);
    } catch (Exception e) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
        e.printStackTrace();
        throw e;
    }
    if (statusCode != HttpStatus.SC_OK) {
        // QQQ For now, we are indeed assuming we get back JSON errors.
        // In future this may be changed depending on the requested
        // output format sent to the servlet.
        String errorBody = method.getResponseBodyAsString();
        JSONObject result = new JSONObject(errorBody);
        String[] errors = { result.getJSONArray("error-code").getString(0), result.getString("summary"),
                result.getString("stacktrace") };
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, errors[2]);
        throw new Exception("HTTP operation failed: " + errors[0] + "\nSTATUS LINE: " + method.getStatusLine()
                + "\nSUMMARY: " + errors[1] + "\nSTACKTRACE: " + errors[2]);
    }
    return statusCode;
}

From source file:com.tops.hotelmanager.util.CommonHttpClient.java

private static String executePOSTRequestV1(String url, Map<String, Object> requestData,
        Map<String, String> headerMap, String contentType, int timeOut, int retry) {
    PostMethod post = new PostMethod(url);
    Gson gson = new Gson();
    String errorMsg = "error~Request Failed";
    try {/*  ww  w. j  a  v a2s  .c o m*/
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setSoTimeout(timeOut);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut);
        if (requestData == null || requestData.isEmpty()) {
            throw new CustomException("Request data is null");
        }
        if (contentType != null && contentType.equals(CommonHttpClient.CONTENT_TYPE_JSON)) {
            StringRequestEntity requestEntity = new StringRequestEntity(gson.toJson(requestData), contentType,
                    "UTF-8");
            post.setRequestEntity(requestEntity);
        } else {
            // SET REQUEST PARAMETER
            for (Map.Entry<String, Object> entry : requestData.entrySet()) {
                post.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        // SET REQUEST HEADER
        if (headerMap != null) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                post.addRequestHeader(entry.getKey(), entry.getValue());
            }
        }
        int status = client.executeMethod(post);
        // System.out.println("URL:" + url);
        // System.out.println("\n REQUEST HEADERS:");
        // Header[] requestHeaders = post.getRequestHeaders();
        // for (Header header : requestHeaders) {
        // System.out.println(header.getName() + "=" + header.getValue());
        // }
        // System.out.println("\n RESPONSE HEADERS:");
        // Header[] responseHeaders = post.getResponseHeaders();
        // for (Header header : responseHeaders) {
        // System.out.println(header.getName() + "=" + header.getValue());
        // }
        // System.out.println(post.getStatusText());
        // System.out.println(post.getStatusLine().getReasonPhrase());
        // System.out.println(post.getResponseBodyAsString());
        if (status == HttpStatus.SC_OK) {
            return post.getResponseBodyAsString();
        } else if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header header = post.getResponseHeader("Location");
            if (retry != 1) {
                errorMsg = executePOSTRequestV1(header.getValue(), requestData, headerMap, contentType, timeOut,
                        retry++);
            }
        } else {
            errorMsg += ",HttpStatus:" + status;
        }
    } catch (Exception ex) {
        logger.error("executePOSTRequestV1 url: " + url + ", Parameters: " + requestData, ex);
        errorMsg = errorMsg + ":" + ex.getMessage();
    } finally {
        post.releaseConnection();
    }
    return errorMsg;
}

From source file:com.benfante.jslideshare.SlideShareConnectorImpl.java

public InputStream sendMultiPartMessage(String url, Map<String, String> parameters, Map<String, File> files)
        throws IOException, SlideShareErrorException {
    HttpClient client = createHttpClient();
    PostMethod method = new PostMethod(url);
    List<Part> partList = new ArrayList();
    partList.add(createStringPart("api_key", this.apiKey));
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    partList.add(createStringPart("ts", ts));
    partList.add(createStringPart("hash", hash));
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        partList.add(createStringPart(entry.getKey(), entry.getValue()));
    }/*from w  w w  .j a va2  s  .  c o  m*/
    Iterator<Map.Entry<String, File>> entryFileIt = files.entrySet().iterator();
    while (entryFileIt.hasNext()) {
        Map.Entry<String, File> entry = entryFileIt.next();
        partList.add(createFilePart(entry.getKey(), entry.getValue()));
    }
    MultipartRequestEntity requestEntity = new MultipartRequestEntity(
            partList.toArray(new Part[partList.size()]), method.getParams());
    method.setRequestEntity(requestEntity);
    logger.debug("Sending multipart POST message to " + method.getURI().getURI() + " with parts " + partList);
    int statusCode = client.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.debug("Server replied with a " + statusCode + " HTTP status code ("
                + HttpStatus.getStatusText(statusCode) + ")");
        throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(method.getResponseBodyAsString());
    }
    InputStream result = new ByteArrayInputStream(method.getResponseBody());
    method.releaseConnection();
    return result;
}

From source file:com.zimbra.cs.mailbox.MailboxTestUtil.java

public static void cleanupIndexStore(Mailbox mbox) {
    IndexStore index = mbox.index.getIndexStore();
    if (index instanceof ElasticSearchIndex) {
        String key = mbox.getAccountId();
        String indexUrl = String.format("%s%s/", LC.zimbra_index_elasticsearch_url_base.value(), key);
        HttpMethod method = new DeleteMethod(indexUrl);
        try {//  w  ww.  j av  a 2 s .  co  m
            ElasticSearchConnector connector = new ElasticSearchConnector();
            int statusCode = connector.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                boolean ok = connector.getBooleanAtJsonPath(new String[] { "ok" }, false);
                boolean acknowledged = connector.getBooleanAtJsonPath(new String[] { "acknowledged" }, false);
                if (!ok || !acknowledged) {
                    ZimbraLog.index.debug("Delete index status ok=%b acknowledged=%b", ok, acknowledged);
                }
            } else {
                String error = connector.getStringAtJsonPath(new String[] { "error" });
                if (error != null && error.startsWith("IndexMissingException")) {
                    ZimbraLog.index.debug("Unable to delete index for key=%s.  Index is missing", key);
                } else {
                    ZimbraLog.index.error("Problem deleting index for key=%s error=%s", key, error);
                }
            }
        } catch (HttpException e) {
            ZimbraLog.index.error("Problem Deleting index with key=" + key, e);
        } catch (IOException e) {
            ZimbraLog.index.error("Problem Deleting index with key=" + key, e);
        }
    }
}