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

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

Introduction

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

Prototype

public static String getStatusText(int statusCode) 

Source Link

Document

Get the reason phrase for a particular status code.

Usage

From source file:org.pmedv.core.util.UploadUtils.java

public static boolean uploadFile(File sourceFile, String targetURL, UploadMonitor monitor,
        String requestParams) {// www  .j  a  va 2 s  .c  om

    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("remoting.properties");
    Properties uploadProps = new Properties();

    try {
        uploadProps.load(is);
    } catch (IOException e) {
        log.info("Could not load upload.properties, is it in classpath?");
        return false;
    }

    log.info("uploading " + sourceFile + " to " + targetURL);

    PostMethod filePost = new PostMethod(targetURL + requestParams);

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

    try {

        Part[] parts = { new CustomizableFilePart(sourceFile.getName(), sourceFile, monitor) };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getState().setCredentials(new AuthScope(hostname, port, AuthScope.ANY_REALM), defaultcreds);

        int status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            log.info("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            log.info("Upload failed, response=" + HttpStatus.getStatusText(status));
            return false;
        }

    } catch (Exception ex) {
        log.error("An exception occured :");
        log.error(ResourceUtils.getStackTrace(ex));
        return false;
    } finally {
        filePost.releaseConnection();
    }

    return true;

}

From source file:org.soitoolkit.commons.mule.mime.MimeUtil.java

public static String sendFileAsMultipartHttpPost(String targetURL, File targetFile, String partName,
        boolean expectHeader, int timeoutMs) {

    logger.debug("Send file {} to url {}", targetFile.getAbsolutePath(), targetURL);

    String response = null;/* ww w .java  2  s .  c  om*/

    PostMethod filePost = new PostMethod(targetURL);

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, expectHeader);

    try {

        Part[] parts = { new FilePart(partName, targetFile) };

        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(timeoutMs);

        int status = client.executeMethod(filePost);

        logger.debug("Send done, http status: {}", status);

        if (status == HttpStatus.SC_OK) {
            response = filePost.getResponseBodyAsString();
            logger.debug("Send done, http response: {}", response);
        } else {
            String errorText = HttpStatus.getStatusText(status);
            throw new RuntimeException("HTTP Error Code: " + status + "HTTP Error Text: " + errorText);
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        filePost.releaseConnection();
    }

    return response;
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

@Override
public void storeItem(ProxyRepository repository, StorageItem item)
        throws UnsupportedStorageOperationException, RemoteStorageException {
    if (!(item instanceof StorageFileItem)) {
        throw new UnsupportedStorageOperationException("Storing of non-files remotely is not supported!");
    }//from w  w  w.  jav a 2 s .c  o  m

    StorageFileItem fItem = (StorageFileItem) item;

    ResourceStoreRequest request = new ResourceStoreRequest(item);

    URL remoteURL = getAbsoluteUrlFromBase(repository, request);

    PutMethod method = new PutMethod(remoteURL.toString());

    try {
        method.setRequestEntity(
                new InputStreamRequestEntity(fItem.getInputStream(), fItem.getLength(), fItem.getMimeType()));

        int response = executeMethod(repository, request, method, remoteURL);

        if (response != HttpStatus.SC_OK && response != HttpStatus.SC_CREATED
                && response != HttpStatus.SC_NO_CONTENT && response != HttpStatus.SC_ACCEPTED) {
            throw new RemoteStorageException("Unexpected response code while executing " + method.getName()
                    + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                    + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString()
                    + "\"]. Expected: \"any success (2xx)\". Received: " + response + " : "
                    + HttpStatus.getStatusText(response));
        }
    } catch (IOException e) {
        throw new RemoteStorageException(
                e.getMessage() + " [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                        + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]",
                e);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

@Override
public void deleteItem(ProxyRepository repository, ResourceStoreRequest request)
        throws ItemNotFoundException, UnsupportedStorageOperationException, RemoteStorageException {
    URL remoteURL = getAbsoluteUrlFromBase(repository, request);

    DeleteMethod method = new DeleteMethod(remoteURL.toString());

    try {/*w w  w .ja va 2s .  c om*/
        int response = executeMethod(repository, request, method, remoteURL);

        if (response != HttpStatus.SC_OK && response != HttpStatus.SC_NO_CONTENT
                && response != HttpStatus.SC_ACCEPTED) {
            throw new RemoteStorageException("The response to HTTP " + method.getName()
                    + " was unexpected HTTP Code " + response + " : " + HttpStatus.getStatusText(response)
                    + " [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath()
                    + "\", remoteUrl=\"" + remoteURL.toString() + "\"]");
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

/**
 * Execute method. In case of any exception thrown by HttpClient, it will release the connection. In other cases it
 * is the duty of caller to do it, or process the input stream.
 * /* w  w w . j  a v  a2  s .  c  o  m*/
 * @param method the method
 * @return the int
 */
protected int doExecuteMethod(ProxyRepository repository, ResourceStoreRequest request, HttpMethod method,
        URL remoteUrl) throws RemoteStorageException {
    URI methodURI = null;

    try {
        methodURI = method.getURI();
    } catch (URIException e) {
        getLogger().debug("Could not format debug log message", e);
    }

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Invoking HTTP " + method.getName() + " method against remote location " + methodURI);
    }

    RemoteStorageContext ctx = getRemoteStorageContext(repository);

    HttpClient httpClient = (HttpClient) ctx.getContextObject(CTX_KEY_CLIENT);

    HostConfiguration httpConfiguration = (HostConfiguration) ctx.getContextObject(CTX_KEY_HTTP_CONFIGURATION);

    method.setRequestHeader(new Header("user-agent", formatUserAgentString(ctx, repository)));
    method.setRequestHeader(new Header("accept", "*/*"));
    method.setRequestHeader(new Header("accept-language", "en-us"));
    method.setRequestHeader(new Header("accept-encoding", "gzip, identity"));
    method.setRequestHeader(new Header("cache-control", "no-cache"));

    // HTTP keep alive should not be used, except when NTLM is used
    Boolean isNtlmUsed = (Boolean) ctx.getContextObject(HttpClientProxyUtil.NTLM_IS_IN_USE_KEY);

    if (isNtlmUsed == null || !isNtlmUsed) {
        method.setRequestHeader(new Header("Connection", "close"));
        method.setRequestHeader(new Header("Proxy-Connection", "close"));
    }

    method.setFollowRedirects(true);

    if (StringUtils.isNotBlank(ctx.getRemoteConnectionSettings().getQueryString())) {
        method.setQueryString(ctx.getRemoteConnectionSettings().getQueryString());
    }

    int resultCode;

    try {
        resultCode = httpClient.executeMethod(httpConfiguration, method);

        final Header httpServerHeader = method.getResponseHeader("server");
        checkForRemotePeerAmazonS3Storage(repository,
                httpServerHeader == null ? null : httpServerHeader.getValue());

        Header proxyReturnedErrorHeader = method.getResponseHeader(NEXUS_MISSING_ARTIFACT_HEADER);
        boolean proxyReturnedError = proxyReturnedErrorHeader != null
                && Boolean.valueOf(proxyReturnedErrorHeader.getValue());

        if (resultCode == HttpStatus.SC_FORBIDDEN) {
            throw new RemoteAccessDeniedException(repository, remoteUrl,
                    HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN));
        } else if (resultCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new RemoteAuthenticationNeededException(repository,
                    HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED));
        } else if (resultCode == HttpStatus.SC_OK && proxyReturnedError) {
            throw new RemoteStorageException(
                    "Invalid artifact found, most likely a proxy redirected to an HTML error page.");
        }
    } catch (RemoteStorageException e) {
        method.releaseConnection();

        throw e;
    } catch (HttpException ex) {
        method.releaseConnection();

        throw new RemoteStorageException("Protocol error while executing " + method.getName()
                + " method. [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                + request.getRequestPath() + "\", remoteUrl=\"" + methodURI + "\"]", ex);
    } catch (IOException ex) {
        method.releaseConnection();

        throw new RemoteStorageException("Transport error while executing " + method.getName()
                + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                + request.getRequestPath() + "\", remoteUrl=\"" + methodURI + "\"]", ex);
    }

    return resultCode;
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

@Override
protected boolean checkRemoteAvailability(long newerThen, ProxyRepository repository,
        ResourceStoreRequest request, boolean isStrict) throws RemoteStorageException {
    URL remoteURL = getAbsoluteUrlFromBase(repository, request);

    HttpMethodBase method = new HeadMethod(remoteURL.toString());

    int response = HttpStatus.SC_BAD_REQUEST;

    // artifactory hack, it pukes on HEAD so we will try with GET if HEAD fails
    boolean doGet = false;

    try {//from  ww  w.ja va  2s.c om
        response = executeMethod(repository, request, method, remoteURL);
    } catch (RemoteStorageException e) {
        // If HEAD failed, attempt a GET. Some repos may not support HEAD method
        doGet = true;

        getLogger().debug("HEAD method failed, will attempt GET.  Exception: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();

        // HEAD returned error, but not exception, try GET before failing
        if (!doGet && response != HttpStatus.SC_OK) {
            doGet = true;

            getLogger().debug("HEAD method failed, will attempt GET.  Status: " + response);
        }
    }

    if (doGet) {
        // create a GET
        method = new GetMethod(remoteURL.toString());

        try {
            // execute it
            response = executeMethod(repository, request, method, remoteURL);
        } finally {
            // and release it immediately
            method.releaseConnection();
        }
    }

    // if we are not strict and remote is S3
    if (!isStrict && isRemotePeerAmazonS3Storage(repository)) {
        // if we are relaxed, we will accept any HTTP response code below 500. This means anyway the HTTP
        // transaction succeeded. This method was never really detecting that the remoteUrl really denotes a root of
        // repository (how could we do that?)
        // this "relaxed" check will help us to "pass" S3 remote storage.
        return response >= HttpStatus.SC_OK && response <= HttpStatus.SC_INTERNAL_SERVER_ERROR;
    } else {
        // non relaxed check is strict, and will select only the OK response
        if (response == HttpStatus.SC_OK) {
            // we have it
            // we have newer if this below is true
            return makeDateFromHeader(method.getResponseHeader("last-modified")) > newerThen;
        } else if ((response >= HttpStatus.SC_MULTIPLE_CHOICES && response < HttpStatus.SC_BAD_REQUEST)
                || response == HttpStatus.SC_NOT_FOUND) {
            return false;
        } else {
            throw new RemoteStorageException("Unexpected response code while executing " + method.getName()
                    + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                    + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString()
                    + "\"]. Expected: \"SUCCESS (200)\". Received: " + response + " : "
                    + HttpStatus.getStatusText(response));
        }
    }
}

From source file:org.tuleap.mylyn.task.core.internal.client.rest.RestOperation.java

/**
 * Throws a CoreException that encapsulates useful info about a server error.
 *
 * @param response//from   w w w  .j a v  a 2s  .com
 *            The error response received from the server.
 * @throws CoreException
 *             If the given response does not have a status OK (200).
 */
protected void checkServerError(ServerResponse response) throws CoreException {
    if (!response.isOk()) {
        String responseBody = response.getBody();
        TuleapErrorMessage message = gson.fromJson(responseBody, TuleapErrorMessage.class);
        TuleapErrorPart errorPart = null;
        TuleapDebugPart debugPart = null;
        if (message != null) {
            errorPart = message.getError();
            debugPart = message.getDebug();
        }
        String msg;
        int statusCode = response.getStatus();
        if (statusCode >= 1000) {
            // Communication error
            msg = TuleapCoreMessages.getString(TuleapCoreKeys.communicationError, Integer.toString(statusCode));
        } else {
            if (errorPart == null) {
                String arg = Integer.toString(statusCode) + ' ' + HttpStatus.getStatusText(statusCode);
                if (!responseBody.isEmpty()) {
                    arg += '/' + responseBody;
                }
                if (statusCode >= HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                    // Server error
                    msg = TuleapCoreMessages.getString(TuleapCoreKeys.internalServerError, fullUrl,
                            method.name(), arg);
                } else {
                    msg = TuleapCoreMessages.getString(TuleapCoreKeys.errorReturnedByServer, fullUrl,
                            method.name(), arg, TuleapCoreMessages.getString(TuleapCoreKeys.noMessage));
                }
            } else {
                if (debugPart != null) {
                    msg = TuleapCoreMessages.getString(TuleapCoreKeys.errorReturnedByServerWithDebug, fullUrl,
                            method.name(), Integer.valueOf(errorPart.getCode()), errorPart.getMessage(),
                            debugPart.getSource());
                } else {
                    msg = TuleapCoreMessages.getString(TuleapCoreKeys.errorReturnedByServer, fullUrl,
                            method.name(), Integer.valueOf(errorPart.getCode()), errorPart.getMessage());
                }
            }
        }
        throw new CoreException(new Status(IStatus.ERROR, TuleapCoreActivator.PLUGIN_ID, msg));
    }
}

From source file:org.wandora.application.tools.extractors.reddit.AbstractRedditExtractor.java

protected static String statusToPhrase(int status) {
    String phrase = HttpStatus.getStatusText(status);
    if (phrase == null && additionalPhrases.containsKey(status)) {
        phrase = additionalPhrases.get(status);
    }/*from  w  w  w  . ja  va2  s .com*/
    return phrase;
}

From source file:org.wso2.carbon.device.mgt.iot.sensebot.api.SensebotControllerService.java

private String sendCommand(String deviceIp, int deviceServerPort, String motionType) {

    if (deviceServerPort == 0) {
        deviceServerPort = 80;/*from   w  w  w.  j a v  a 2  s . co  m*/
    }

    String urlString = URL_PREFIX + deviceIp + ":" + deviceServerPort + motionType;
    if (log.isDebugEnabled())
        log.debug(urlString);

    String result = "";
    URL url = null;
    int responseCode = 200;

    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        log.error("Invalid URL: " + urlString);
    }
    try {
        if (url != null) {
            httpConn = (HttpURLConnection) url.openConnection();

            try {
                httpConn.setRequestMethod(HttpMethod.GET);
                httpConn.setRequestProperty("User-Agent", "WSO2 Carbon Server");
                responseCode = httpConn.getResponseCode();
                result = "" + responseCode + HttpStatus.getStatusText(responseCode) + "(No reply from Robot)";

                if (log.isDebugEnabled())
                    log.debug("\nSending 'GET' request to URL : " + urlString);
                if (log.isDebugEnabled())
                    log.debug("Response Code : " + responseCode);
            } catch (ProtocolException e) {
                log.error("Protocol mismatch exception occured whilst trying to 'GET' resource");
            } catch (IOException e) {
                log.error(
                        "Error occured whilst reading return code from server. This could be because the server did not return anything");
                result = "" + responseCode + " " + HttpStatus.getStatusText(responseCode)
                        + "(No reply from Robot)";
                return result;
            }
        }
    } catch (IOException e) {
        log.error("Error Connecting to HTTP Endpoint at: " + urlString);
    }

    return result;
}

From source file:org.wso2.carbon.device.mgt.iot.services.sensebot.SenseBotControllerService.java

private String sendCommand(String deviceIp, int deviceServerPort, String motionType) {

    if (deviceServerPort == 0) {
        deviceServerPort = 80;//from   w  w w .  j  a  v  a2  s . c  o  m
    }

    String urlString = URL_PREFIX + deviceIp + ":" + deviceServerPort + motionType;
    log.info(urlString);

    String result = null;
    URL url = null;
    int responseCode = 200;

    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        log.error("Invalid URL: " + urlString);
    }
    try {
        httpConn = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        log.error("Error Connecting to HTTP Endpoint at: " + urlString);
    }

    try {
        httpConn.setRequestMethod(HttpMethod.GET);
        httpConn.setRequestProperty("User-Agent", "WSO2 Carbon Server");
        responseCode = httpConn.getResponseCode();
        result = "" + responseCode + HttpStatus.getStatusText(responseCode) + "(No reply from Robot)";

        log.info("\nSending 'GET' request to URL : " + urlString);
        log.info("Response Code : " + responseCode);
    } catch (ProtocolException e) {
        log.error("Protocol mismatch exception occured whilst trying to 'GET' resource");
    } catch (IOException e) {
        log.error(
                "Error occured whilst reading return code from server. This could be because the server did not return anything");
        result = "" + responseCode + " " + HttpStatus.getStatusText(responseCode) + "(No reply from Robot)";
        return result;
    }

    return result;
}