Example usage for org.apache.commons.httpclient HttpMethod getStatusText

List of usage examples for org.apache.commons.httpclient HttpMethod getStatusText

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getStatusText.

Prototype

public abstract String getStatusText();

Source Link

Usage

From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

private HTTPResponse convertResponse(HttpMethod method) {
    Headers headers = new Headers();
    for (Header header : method.getResponseHeaders()) {
        headers = headers.add(header.getName(), header.getValue());
    }//from w  w w.  j  a v a  2  s.  c om
    InputStream stream = null;
    HTTPResponse response;
    try {
        stream = getInputStream(method);
        StatusLine line = new StatusLine(HTTPVersion.get(method.getStatusLine().getHttpVersion()),
                Status.valueOf(method.getStatusCode()), method.getStatusText());
        response = responseCreator.createResponse(line, headers, stream);
    } finally {
        if (stream == null) {
            method.releaseConnection();
        }
    }
    return response;
}

From source file:com.panoramagl.downloaders.PLHTTPFileDownloader.java

/**download methods*/

@Override//from  w  w  w  .j ava 2 s.c  om
protected byte[] downloadFile() {
    this.setRunning(true);
    byte[] result = null;
    InputStream is = null;
    ByteArrayOutputStream bas = null;
    String url = this.getURL();
    PLFileDownloaderListener listener = this.getListener();
    boolean hasListener = (listener != null);
    int responseCode = -1;
    long startTime = System.currentTimeMillis();
    // HttpClient instance
    HttpClient client = new HttpClient();
    // Method instance
    HttpMethod method = new GetMethod(url);
    // Method parameters
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.USER_AGENT, "PanoramaGL Android");
    methodParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(this.getMaxAttempts(), false));
    try {
        // Execute the method
        responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK)
            throw new IOException(method.getStatusText());
        // Get content length
        Header header = method.getRequestHeader("Content-Length");
        long contentLength = (header != null ? Long.parseLong(header.getValue()) : 1);
        if (this.isRunning()) {
            if (hasListener)
                listener.didBeginDownload(url, startTime);
        } else
            throw new PLRequestInvalidatedException(url);
        // Get response body as stream
        is = method.getResponseBodyAsStream();
        bas = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int length = 0, total = 0;
        // Read stream
        while ((length = is.read(buffer)) != -1) {
            if (this.isRunning()) {
                bas.write(buffer, 0, length);
                total += length;
                if (hasListener)
                    listener.didProgressDownload(url, (int) (((float) total / (float) contentLength) * 100.0f));
            } else
                throw new PLRequestInvalidatedException(url);
        }
        if (total == 0)
            throw new IOException("Request data has invalid size (0)");
        // Get data
        if (this.isRunning()) {
            result = bas.toByteArray();
            if (hasListener)
                listener.didEndDownload(url, result, System.currentTimeMillis() - startTime);
        } else
            throw new PLRequestInvalidatedException(url);
    } catch (Throwable e) {
        if (this.isRunning()) {
            PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            if (hasListener)
                listener.didErrorDownload(url, e.toString(), responseCode, result);
        }
    } finally {
        if (bas != null) {
            try {
                bas.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        // Release the connection
        method.releaseConnection();
    }
    this.setRunning(false);
    return result;
}

From source file:com.delmar.station.service.impl.WFDetailServiceImpl.java

public String updateDcmsFcrDate(EDIResponseInfo edirInfo, String trustFileCode) {

    String resultMessage = "success";
    Date date = new Date();
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    String currentDate = sf.format(date);
    try {//from  www. j av  a  2s.co  m
        date = sf.parse(edirInfo.getInDate());
        currentDate = sf.format(date);
    } catch (ParseException e1) {
        e1.printStackTrace();
    }

    try {

        EDIResponseInfo resultEDIResponseInfo = ediResponseInfoService.getEDIRByTrustFileCode(trustFileCode);

        // Booking IDCargoProDcms????bookingID
        if (StringUtil.isNotEmpty(resultEDIResponseInfo.getCsReferenceNo())) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("id", resultEDIResponseInfo.getCsReferenceNo());
            params.put("fcrDate", currentDate);
            params.put("remark", edirInfo.getResponseDesc());
            HttpClient httpClient = null;
            httpClient.getParams().setAuthenticationPreemptive(true);

            // ?
            Credentials credentials = new UsernamePasswordCredentials("wsuserchina", "ws1sGreat");
            httpClient.getState().setCredentials(AuthScope.ANY, credentials);

            HttpMethod method = buildPostMethod(
                    "https://www.delmarcargo.com/cms/api/bookingservice/updateBookingFcrDate", params);
            int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                throw new HttpException(method.getStatusText());
            }
            String xmlResult = method.getResponseBodyAsString();
            method.releaseConnection();

            //   
            StringReader xmlReader = new StringReader(xmlResult);
            // ?SAX ? InputSource ?? XML   
            InputSource xmlSource = new InputSource(xmlReader);
            // SAXBuilder  
            SAXReader builder = new SAXReader();
            // ?SAXDocument
            Document doc = builder.read(xmlSource);
            // 
            Element root = doc.getRootElement();
            // BODY 
            Element resultStatusCode = root.element("ServiceResponse").element("statusCode");

            // ????
            if ("200".equals(resultStatusCode.getText())) {
                // add
                edirInfo.setEdiType("DCMS_FCRDATE");
                edirInfo.setEdiStatus("1");
                edirInfo.setCsReferenceNo(resultEDIResponseInfo.getCsReferenceNo());// set Booking Id
                edirInfo.setEdiAction("NEW");
                edirInfo.setEdiStatus("1");
                edirInfo.setBatchNo("0");
                edirInfo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setBeUse(0);
                ediResponseInfoService.saveOrUpdate(edirInfo);

                ediResponseInfoService.updateTrustFileInfoFCRDate(currentDate, edirInfo.getTrustFileCode());
            } else if ("405".equals(resultStatusCode.getText())) {
                Element resultText = root.element("ServiceResponse").element("description");
                resultMessage = resultText.getText();

                // add
                edirInfo.setEdiType("DCMS_FCRDATE");
                edirInfo.setEdiStatus("11");
                edirInfo.setCsReferenceNo(resultEDIResponseInfo.getCsReferenceNo());// set Booking Id
                edirInfo.setEdiAction("NEW");
                edirInfo.setEdiStatus("1");
                edirInfo.setBatchNo("0");
                edirInfo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setBeUse(0);
                ediResponseInfoService.saveOrUpdate(edirInfo);
            } else {
                Element resultText = root.element("ServiceResponse").element("description");
                resultMessage = resultText.getText();
            }
        } else {
            resultMessage = "Booking IDCargoProDcms?";
        }
    } catch (Exception e) {
        e.printStackTrace();
        resultMessage = "Modify Dcms Fcr Date have Exception";
        return resultMessage;
    }

    return resultMessage;
}

From source file:com.cloud.test.longrun.User.java

public void retrievePublicIp(long zoneId) throws IOException {

    String encodedApiKey = URLEncoder.encode(this.apiKey, "UTF-8");
    String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8");
    String requestToSign = "apiKey=" + encodedApiKey + "&command=associateIpAddress" + "&zoneId="
            + encodedZoneId;/*  ww  w .  j a  va  2 s. c  o  m*/
    requestToSign = requestToSign.toLowerCase();
    String signature = TestClientWithAPI.signRequest(requestToSign, this.secretKey);
    String encodedSignature = URLEncoder.encode(signature, "UTF-8");

    String url = this.developerServer + "?command=associateIpAddress" + "&apiKey=" + encodedApiKey + "&zoneId="
            + encodedZoneId + "&signature=" + encodedSignature;

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> values = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "ipaddress" });
        this.getPublicIp().add(values.get("ipaddress"));
        s_logger.info("Ip address is " + values.get("ipaddress"));
    } else if (responseCode == 500) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is,
                new String[] { "errorcode", "description" });
        s_logger.error("associate ip test failed with errorCode: " + errorInfo.get("errorCode")
                + " and description: " + errorInfo.get("description"));
    } else {
        s_logger.error("internal error processing request: " + method.getStatusText());
    }

}

From source file:com.sa.npopa.samples.hbase.rest.client.Client.java

/**
 * Execute a transaction method given a complete URI.
 * @param method the transaction method//from w  ww  . jav a 2  s.  c o  m
 * @param headers HTTP header values to send
 * @param uri a properly urlencoded URI
 * @return the HTTP response code
 * @throws IOException
 */
public int executeURI(HttpMethod method, Header[] headers, String uri) throws IOException {
    method.setURI(new URI(uri, true));
    for (Map.Entry<String, String> e : extraHeaders.entrySet()) {
        method.addRequestHeader(e.getKey(), e.getValue());
    }
    if (headers != null) {
        for (Header header : headers) {
            method.addRequestHeader(header);
        }
    }
    long startTime = System.currentTimeMillis();
    int code = httpClient.executeMethod(method);
    long endTime = System.currentTimeMillis();
    if (LOG.isDebugEnabled()) {
        LOG.debug(method.getName() + " " + uri + " " + code + " " + method.getStatusText() + " in "
                + (endTime - startTime) + " ms");
    }
    return code;
}

From source file:com.cloud.test.longrun.User.java

public void registerUser() throws HttpException, IOException {

    String encodedUsername = URLEncoder.encode(this.userName, "UTF-8");
    String encodedPassword = URLEncoder.encode(this.password, "UTF-8");
    String url = server + "?command=register&username=" + encodedUsername + "&domainid=1";
    s_logger.info("registering: " + this.userName + " with url " + url);
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> requestKeyValues = TestClientWithAPI.getSingleValueFromXML(is,
                new String[] { "apikey", "secretkey" });
        this.setApiKey(requestKeyValues.get("apikey"));
        this.setSecretKey(requestKeyValues.get("secretkey"));
    } else if (responseCode == 500) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is,
                new String[] { "errorcode", "description" });
        s_logger.error("registration failed with errorCode: " + errorInfo.get("errorCode")
                + " and description: " + errorInfo.get("description"));
    } else {/*from   w w w. ja va 2s  .  com*/
        s_logger.error("internal error processing request: " + method.getStatusText());
    }
}

From source file:com.cloud.test.longrun.VirtualMachine.java

public void deployVM(long zoneId, long serviceOfferingId, long templateId, String server, String apiKey,
        String secretKey) throws IOException {

    String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8");
    String encodedServiceOfferingId = URLEncoder.encode("" + serviceOfferingId, "UTF-8");
    String encodedTemplateId = URLEncoder.encode("" + templateId, "UTF-8");
    String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8");
    String requestToSign = "apiKey=" + encodedApiKey + "&command=deployVirtualMachine&serviceOfferingId="
            + encodedServiceOfferingId + "&templateId=" + encodedTemplateId + "&zoneId=" + encodedZoneId;

    requestToSign = requestToSign.toLowerCase();
    String signature = TestClientWithAPI.signRequest(requestToSign, secretKey);
    String encodedSignature = URLEncoder.encode(signature, "UTF-8");
    String url = server + "?command=deployVirtualMachine" + "&zoneId=" + encodedZoneId + "&serviceOfferingId="
            + encodedServiceOfferingId + "&templateId=" + encodedTemplateId + "&apiKey=" + encodedApiKey
            + "&signature=" + encodedSignature;

    s_logger.info("Sending this request to deploy a VM: " + url);
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    s_logger.info("deploy linux vm response code: " + responseCode);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> values = TestClientWithAPI.getSingleValueFromXML(is,
                new String[] { "id", "ipaddress" });
        long linuxVMId = Long.parseLong(values.get("id"));
        s_logger.info("got linux virtual machine id: " + linuxVMId);
        this.setPrivateIp(values.get("ipaddress"));

    } else if (responseCode == 500) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is,
                new String[] { "errorcode", "description" });
        s_logger.error("deploy linux vm test failed with errorCode: " + errorInfo.get("errorCode")
                + " and description: " + errorInfo.get("description"));
    } else {/* w  w  w .  ja v  a  2 s.c om*/
        s_logger.error("internal error processing request: " + method.getStatusText());
    }
}

From source file:com.jackbe.mapreduce.EMMLRestRunner.java

protected String executeRESTCall(String scriptName, String encodedValue) {

    // "http://localhost:8080/presto/edge/api/rest/StockQuoteMapper/runMashup?x-presto-resultFormat=xml&value=<encodedValue>"
    HttpMethod httpMethod = null;
    String result = null;/*from ww  w.  j  a  va 2s. c  om*/

    if (encodedValue != null) {
        httpMethod = new GetMethod(protocol + host + ":" + port + path + scriptName + "/" + operation + "?"
                + format + "&value=" + encodedValue);
        log.debug("Invoking REST service: " + protocol + host + ":" + port + path + scriptName + "/" + operation
                + "?" + format + "&value=" + encodedValue);
    } else {
        httpMethod = new GetMethod(
                protocol + host + ":" + port + path + scriptName + "/" + operation + "?" + format);
        log.debug("Invoking REST service: " + protocol + host + ":" + port + path + scriptName + "/" + operation
                + "?" + format);
    }

    try {
        client.executeMethod(httpMethod);

        if (httpMethod.getStatusCode() != HttpStatus.SC_OK) {
            log.error("HTTP Error status connecting to Presto: " + httpMethod.getStatusCode());
            log.error("HTTP Error message connecting to Presto: " + httpMethod.getStatusText());
            return null;
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Status code: " + httpMethod.getStatusCode());
                Header contentTypeHeader = httpMethod.getResponseHeader("content-type");
                log.debug("Mimetype: " + contentTypeHeader.getValue());
            }
        }

        result = httpMethod.getResponseBodyAsString();
        // log.debug(httpMethod.getStatusText());
        if (log.isDebugEnabled())
            log.debug("Response: " + result);
    } catch (Exception e) {
        log.error("Exception executing REST call: " + e, e);
    } finally {
        httpMethod.releaseConnection();
    }

    return result;

}

From source file:com.dtolabs.client.utils.HttpClientChannel.java

/**
 * Perform the HTTP request.  Can only be performed once.
 *//* www. jav a2s  .  c  o  m*/
public void makeRequest() throws IOException, HttpClientException {
    if (requestMade) {
        return;
    }

    requestMade = true;
    RequestEntity reqEntity = null;
    NameValuePair[] postBody = null;
    if (isPostMethod()) {
        setMethodType("POST");
    }
    HttpMethod method = initMethod();
    if (isPostMethod()) {
        reqEntity = getRequestEntity((PostMethod) method);
        if (null != reqEntity) {
            logger.debug("preparing to post request entity data: " + reqEntity.getContentType());

            ((PostMethod) method).setRequestEntity(reqEntity);
        } else {
            logger.debug("preparing to post form data");
            postBody = getRequestBody((PostMethod) method);
            ((PostMethod) method).setRequestBody(postBody);
        }
    }
    logger.debug("calling preMakeRequest");
    if (!preMakeRequest(method)) {
        return;
    }
    logger.debug("calling doAuthentication...");
    if (!doAuthentication(method)) {
        return;
    }
    int bytesread = 0;
    try {
        if (!isPostMethod()) {
            method.setFollowRedirects(true);
        }
        logger.debug("make request...");
        resultCode = httpc.executeMethod(method);
        reasonCode = method.getStatusText();
        if (isPostMethod()) {
            //check redirect after post
            method = checkFollowRedirect(method, resultCode);
        }
        logger.debug("check needs reauth...");

        if (needsReAuthentication(resultCode, method)) {
            logger.debug("re-authentication needed, performing...");
            method.releaseConnection();
            method.abort();
            //need to re-authenticate.
            method = initMethod();
            if (isPostMethod() && null != reqEntity) {
                ((PostMethod) method).setRequestEntity(reqEntity);
            } else if (isPostMethod() && null != postBody) {
                ((PostMethod) method).setRequestBody(postBody);
            }
            if (!doAuthentication(method)) {
                //user login failed
                return;
            }
            //user login has succeeded
            logger.debug("remaking original request...");
            resultCode = httpc.executeMethod(method);
            reasonCode = method.getStatusText();
            if (needsReAuthentication(resultCode, method)) {
                //user request was unauthorized
                throw new HttpClientException("Unauthorized Action: "
                        + (null != method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER)
                                ? method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER)
                                        .getValue()
                                : reasonCode));
            }
        }

        logger.debug("finish...");
        if (null != method.getResponseHeader("Content-Type")) {
            resultType = method.getResponseHeader("Content-Type").getValue();
        }
        String type = resultType;
        if (type != null && type.indexOf(";") > 0) {
            type = type.substring(0, type.indexOf(";")).trim();
        }
        if (null == expectedContentType || expectedContentType.equals(type)) {
            if (null != destinationStream && resultCode >= 200 && resultCode < 300) {
                //read the input stream and write it to the destination
                contentLengthRetrieved = Streams.copyStreamCount(method.getResponseBodyAsStream(),
                        destinationStream);
            } else {
                final ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(1024 * 50);
                Streams.copyStream(method.getResponseBodyAsStream(), outputBytes);
                resultStream = new ByteArrayInputStream(outputBytes.toByteArray());
            }
        }
        reqMadeMethod = method;
    } catch (HttpException e) {
        logger.error("HTTP error: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }

    logger.debug("Response received");
    postMakeRequest();
}

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method,
        HttpState state) throws IOException, ServiceException {
    // create an HTTP client with the same cookies
    javax.servlet.http.Cookie cookies[] = req.getCookies();
    String hostname = method.getURI().getHost();
    boolean hasZMAuth = hasZimbraAuthCookie(state);
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(ZimbraCookie.COOKIE_ZM_AUTH_TOKEN) && hasZMAuth)
                continue;
            state.addCookie(/*from ww  w.ja  va  2  s .  c o m*/
                    new Cookie(hostname, cookies[i].getName(), cookies[i].getValue(), "/", null, false));
        }
    }
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    if (state != null)
        client.setState(state);

    int hopcount = 0;
    for (Enumeration<?> enm = req.getHeaderNames(); enm.hasMoreElements();) {
        String hname = (String) enm.nextElement(), hlc = hname.toLowerCase();
        if (hlc.equals("x-zimbra-hopcount"))
            try {
                hopcount = Math.max(Integer.parseInt(req.getHeader(hname)), 0);
            } catch (NumberFormatException e) {
            }
        else if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.equals("authorization"))
            method.addRequestHeader(hname, req.getHeader(hname));
    }
    if (hopcount >= MAX_PROXY_HOPCOUNT)
        throw ServiceException.TOO_MANY_HOPS(HttpUtil.getFullRequestURL(req));
    method.addRequestHeader("X-Zimbra-Hopcount", Integer.toString(hopcount + 1));
    if (method.getRequestHeader("X-Zimbra-Orig-Url") == null)
        method.addRequestHeader("X-Zimbra-Orig-Url", req.getRequestURL().toString());
    String ua = req.getHeader("User-Agent");
    if (ua != null)
        method.setRequestHeader("User-Agent", ua);

    // dispatch the request and copy over the results
    int statusCode = -1;
    for (int retryCount = 3; statusCode == -1 && retryCount > 0; retryCount--) {
        statusCode = HttpClientUtil.executeMethod(client, method);
    }
    if (statusCode == -1) {
        resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "retry limit reached");
        return;
    } else if (statusCode >= 300) {
        resp.sendError(statusCode, method.getStatusText());
        return;
    }

    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        String hname = headers[i].getName(), hlc = hname.toLowerCase();
        if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.startsWith("www-"))
            resp.addHeader(hname, headers[i].getValue());
    }
    InputStream responseStream = method.getResponseBodyAsStream();
    if (responseStream == null || resp.getOutputStream() == null)
        return;
    ByteUtil.copy(method.getResponseBodyAsStream(), false, resp.getOutputStream(), false);
}