Example usage for org.apache.http.client ClientProtocolException getMessage

List of usage examples for org.apache.http.client ClientProtocolException getMessage

Introduction

In this page you can find the example usage for org.apache.http.client ClientProtocolException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.wso2.carbon.apimgt.impl.AMDefaultKeyManagerImpl.java

@Override
public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest)
        throws APIManagementException {

    String newAccessToken;/*from   ww  w . ja v  a2s  .c om*/
    long validityPeriod;
    AccessTokenInfo tokenInfo = null;

    if (tokenRequest == null) {
        log.warn("No information available to generate Token.");
        return null;
    }

    String tokenEndpoint = configuration.getParameter(APIConstants.TOKEN_URL);
    //To revoke tokens we should call revoke API deployed in API gateway.
    String revokeEndpoint = configuration.getParameter(APIConstants.REVOKE_URL);
    URL keyMgtURL = new URL(tokenEndpoint);
    int keyMgtPort = keyMgtURL.getPort();
    String keyMgtProtocol = keyMgtURL.getProtocol();

    // Call the /revoke only if there's a token to be revoked.
    try {
        if (tokenRequest.getTokenToRevoke() != null && !"".equals(tokenRequest.getTokenToRevoke())) {
            URL revokeEndpointURL = new URL(revokeEndpoint);
            String revokeEndpointProtocol = revokeEndpointURL.getProtocol();
            int revokeEndpointPort = revokeEndpointURL.getPort();

            HttpClient revokeEPClient = APIUtil.getHttpClient(revokeEndpointPort, revokeEndpointProtocol);

            HttpPost httpRevokePost = new HttpPost(revokeEndpoint);

            // Request parameters.
            List<NameValuePair> revokeParams = new ArrayList<NameValuePair>(3);
            revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, tokenRequest.getClientId()));
            revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, tokenRequest.getClientSecret()));
            revokeParams.add(new BasicNameValuePair("token", tokenRequest.getTokenToRevoke()));

            //Revoke the Old Access Token
            httpRevokePost.setEntity(new UrlEncodedFormEntity(revokeParams, "UTF-8"));
            int statusCode;
            try {
                HttpResponse revokeResponse = revokeEPClient.execute(httpRevokePost);
                statusCode = revokeResponse.getStatusLine().getStatusCode();
            } finally {
                httpRevokePost.reset();
            }

            if (statusCode != 200) {
                throw new RuntimeException("Token revoke failed : HTTP error code : " + statusCode);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Successfully submitted revoke request for old application token. HTTP status : 200");
                }
            }
        }
        //get default application access token name from config.

        String applicationTokenScope = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
                .getAPIManagerConfiguration().getFirstProperty(APIConstants.APPLICATION_TOKEN_SCOPE);

        // When validity time set to a negative value, a token is considered never to expire.
        if (tokenRequest.getValidityPeriod() == OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) {
            // Setting a different -ve value if the set value is -1 (-1 will be ignored by TokenValidator)
            tokenRequest.setValidityPeriod(-2);
        }

        //Generate New Access Token
        HttpClient tokenEPClient = APIUtil.getHttpClient(keyMgtPort, keyMgtProtocol);
        HttpPost httpTokpost = new HttpPost(tokenEndpoint);
        List<NameValuePair> tokParams = new ArrayList<NameValuePair>(3);
        tokParams.add(new BasicNameValuePair(OAuth.OAUTH_GRANT_TYPE, GRANT_TYPE_VALUE));
        tokParams.add(new BasicNameValuePair(GRANT_TYPE_PARAM_VALIDITY,
                Long.toString(tokenRequest.getValidityPeriod())));
        tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, tokenRequest.getClientId()));
        tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, tokenRequest.getClientSecret()));
        StringBuilder builder = new StringBuilder();
        builder.append(applicationTokenScope);

        for (String scope : tokenRequest.getScope()) {
            builder.append(' ').append(scope);
        }

        tokParams.add(new BasicNameValuePair("scope", builder.toString()));

        httpTokpost.setEntity(new UrlEncodedFormEntity(tokParams, "UTF-8"));
        try {
            HttpResponse tokResponse = tokenEPClient.execute(httpTokpost);
            HttpEntity tokEntity = tokResponse.getEntity();

            if (tokResponse.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("Error occurred while calling token endpoint: HTTP error code : "
                        + tokResponse.getStatusLine().getStatusCode());
            } else {
                tokenInfo = new AccessTokenInfo();
                String responseStr = EntityUtils.toString(tokEntity);
                JSONObject obj = new JSONObject(responseStr);
                newAccessToken = obj.get(OAUTH_RESPONSE_ACCESSTOKEN).toString();
                validityPeriod = Long.parseLong(obj.get(OAUTH_RESPONSE_EXPIRY_TIME).toString());
                if (obj.has("scope")) {
                    tokenInfo.setScope(((String) obj.get("scope")).split(" "));
                }
                tokenInfo.setAccessToken(newAccessToken);
                tokenInfo.setValidityPeriod(validityPeriod);
            }
        } finally {
            httpTokpost.reset();
        }
    } catch (ClientProtocolException e) {
        handleException("Error while creating token - Invalid protocol used", e);
    } catch (UnsupportedEncodingException e) {
        handleException("Error while preparing request for token/revoke APIs", e);
    } catch (IOException e) {
        handleException("Error while creating tokens - " + e.getMessage(), e);
    } catch (JSONException e) {
        handleException("Error while parsing response from token api", e);
    }

    return tokenInfo;
}

From source file:org.commonjava.aprox.autoprox.data.AutoProxDataManagerDecorator.java

/**
 * Validates the remote connection, produced from rule-set for given name, 
 * for a remote repo or group containing a remote. If:
 * /*  www. j  av a  2  s .  c o  m*/
 * <ul>
 *   <li>rule.isValidationEnabled() == false, return true</li>
 *   <li>rule.getValidationRemote() == null, return true</li>
 *   <li>
 *     rule.getRemoteValidationPath() != null, validate remote.getUrl() + validationPath
 *     <ul>
 *       <li>if response code is 200 OK, then return true</li>
 *       <li>otherwise, return false</li>
 *     </ul>
 *   </li>
 * </ul>
 * @throws AproxDataException if the selected rule encounters an error while creating the new group/repository instance(s).
 */
private boolean checkValidity(final String name) throws AproxDataException {
    if (catalog.isValidationEnabled(name)) {
        try {
            final RemoteRepository validationRepo = catalog.createValidationRemote(name);
            if (validationRepo == null) {
                return true;
            }

            String url = catalog.getRemoteValidationUrl(name);
            if (url == null) {
                url = validationRepo.getUrl();
            } else {
                url = normalize(validationRepo.getUrl(), url);
            }

            logger.debug("\n\n\n\n\n[AutoProx] Checking URL: {}", url);
            final HttpHead head = new HttpHead(url);

            http.bindRepositoryCredentialsTo(validationRepo, head);

            boolean result = false;
            try {
                final HttpResponse response = http.getClient().execute(head);
                final StatusLine statusLine = response.getStatusLine();
                final int status = statusLine.getStatusCode();
                logger.debug("[AutoProx] HTTP Status: {}", statusLine);
                result = status == HttpStatus.SC_OK;

                if (!result) {
                    logger.warn("Invalid repository URL: {}", validationRepo.getUrl());
                }
            } catch (final ClientProtocolException e) {
                logger.warn("[AutoProx] Cannot connect to target repository: '{}'.", url);
            } catch (final IOException e) {
                logger.warn("[AutoProx] Cannot connect to target repository: '{}'.", url);
            } finally {
                head.reset();

                http.clearRepositoryCredentials();
                http.closeConnection();
            }

            return result;
        } catch (final AutoProxRuleException e) {
            throw new AproxDataException(
                    "[AUTOPROX] Failed to create new group from factory matching: '%s'. Reason: %s", e, name,
                    e.getMessage());
        }
    }

    return true;
}

From source file:com.naryx.tagfusion.cfm.http.cfHttpConnection.java

@Override
public void connect() throws cfmRunTimeException {

    // Collect up the request
    addHeaders();//from  w  w w  .ja  va 2s. c o m
    addCookies();
    addURLData();
    addFormData();
    addFiles();
    setBody();
    setDefaultProxy();

    // if we are building up a multipart then we should add this to the message
    if (multipartEntityBuilder != null) {
        HttpEntity reqEntity = multipartEntityBuilder.build();
        ((HttpPost) message).setEntity(reqEntity);
    }

    // Execute the method.
    int statusCode = -1;
    int redirectLimit = 5;
    HttpResponse response;
    try {
        client.getParams().setParameter("http.protocol.max-redirects", redirectLimit);

        response = client.execute(message);
        statusCode = response.getStatusLine().getStatusCode();

    } catch (ConnectTimeoutException ce) {
        if (!throwOnError) {
            handleError("Connect Exception: Connection timed out.", "Connection Failed");
        } else {
            throw newRunTimeException("Connect Exception: Connection timed out.");
        }
        return;
    } catch (ClientProtocolException e) {
        if (!throwOnError) {
            handleError("Connect Exception: " + e.getMessage(), "Connection Failed");
        } else {
            throw newRunTimeException("Failed due to invalid Protocol: " + e.getMessage());
        }
        return;
    } catch (IOException e) {
        if (!throwOnError) {
            handleError("Connect Exception: " + e.getMessage(), "Connection Failed");
        } else {
            throw newRunTimeException("Connect Exception: " + e.getMessage());
        }
        return;
    }

    // if status code is -1
    if (statusCode != -1)
        handleResponse(response, statusCode);

}

From source file:org.openbaton.marketplace.core.VNFPackageManagement.java

public void dispatch(VNFPackageMetadata vnfPackageMetadata) throws FailedToUploadException {

    RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(60000)
            .build();/*from   w ww. j  a va  2s  . com*/
    CloseableHttpResponse response = null;
    HttpPost httpPost = null;
    String url = "https://" + fitEagleIp + ":" + fitEaglePort + "/OpenBaton/upload/v2";
    try {
        log.debug("Executing post on " + url);
        httpPost = new HttpPost(url);
        //      httpPost.setHeader(new BasicHeader("Accept", "multipart/form-data"));
        //      httpPost.setHeader(new BasicHeader("Content-type", "multipart/form-data"));
        httpPost.setHeader(new BasicHeader("username", userManagement.getCurrentUser()));
        httpPost.setHeader(new BasicHeader("filename", vnfPackageMetadata.getVnfPackageFileName()));

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addBinaryBody("file", vnfPackageMetadata.getVnfPackageFile());
        httpPost.setEntity(multipartEntityBuilder.build());

        CloseableHttpClient client = getHttpClientForSsl(config);

        response = client.execute(httpPost);
    } catch (ClientProtocolException e) {
        httpPost.releaseConnection();
        e.printStackTrace();
        log.error("NotAble to upload VNFPackage");
        throw new FailedToUploadException(
                "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage());
    } catch (IOException e) {
        httpPost.releaseConnection();
        e.printStackTrace();
        httpPost.releaseConnection();
        log.error("NotAble to upload VNFPackage");
        throw new FailedToUploadException(
                "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage());
    }

    // check response status
    String result = "";
    if (response != null && response.getEntity() != null) {
        try {
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
            httpPost.releaseConnection();
            throw new FailedToUploadException(
                    "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage());
        }
    }

    if (response != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
        log.debug("Uploaded the VNFPackage");
        log.debug("received: " + result);
        if (vnfPackageMetadata.getRequirements() == null) {
            vnfPackageMetadata.setRequirements(new HashMap<String, String>());
        }
        vnfPackageMetadata.getRequirements().put("fiteagle-id", result);
    } else
        throw new FailedToUploadException(
                "Not Able to upload VNFPackage to Fiteagle because: Fiteagle answered "
                        + response.getStatusLine().getStatusCode());
    httpPost.releaseConnection();
}

From source file:com.lehman.ic9.net.httpClient.java

/**
 * Performs the actual HTTP request. This method is called from the GET and POST 
 * methods. //from  w w w  . j  a v a2s.  co m
 * @param getString is a boolean flag with true for string and false for binary.
 * @param post is a boolean flag with true for post and false for get.
 * @return A Javascript object with the results of the request.
 * @throws ic9exception Exception
 * @throws NoSuchMethodException Exception
 * @throws ScriptException Exception
 */
private Map<String, Object> performRequest(boolean getString, httpReqType reqType)
        throws ic9exception, NoSuchMethodException, ScriptException {
    Map<String, Object> ret = this.eng.newObj(null);

    HttpRequestBase httpReq = null;
    if (reqType == httpReqType.GET)
        httpReq = new HttpGet(this.u.toString());
    else if (reqType == httpReqType.POST)
        httpReq = new HttpPost(this.u.toString());
    else if (reqType == httpReqType.PUT)
        httpReq = new HttpPut(this.u.toString());
    else if (reqType == httpReqType.DELETE)
        httpReq = new HttpDelete(this.u.toString());

    // Set cookies from JS object.
    this.cs.clear();
    Object[] jscookies = (Object[]) this.eng.getJavaArray(this.jsobj.get("cookies"));
    for (Object tobj : jscookies) {
        @SuppressWarnings("unchecked")
        Map<String, Object> cobj = (Map<String, Object>) tobj;
        this.cs.addCookie(this.setApacheCookie(cobj));
    }

    HttpClientContext ctx = HttpClientContext.create();
    ctx.setCookieStore(this.cs);
    ctx.setCredentialsProvider(this.cp);
    ctx.setRequestConfig(this.rcb.build());

    // Set headers.
    @SuppressWarnings("unchecked")
    Map<String, Object> headers = (Map<String, Object>) this.jsobj.get("headers");
    for (String key : headers.keySet()) {
        String val = (String) headers.get(key);
        httpReq.addHeader(key, val);
    }

    CloseableHttpResponse resp = null;
    try {
        if (this.cli == null) {
            this.buildClient(httpReq);
        }
        if (reqType == httpReqType.POST && this.respEnt != null)
            ((HttpPost) httpReq).setEntity(this.respEnt);
        else if (reqType == httpReqType.PUT && this.respEnt != null)
            ((HttpPut) httpReq).setEntity(this.respEnt);
        resp = this.cli.execute(httpReq, ctx);

        HttpEntity ent = resp.getEntity();

        this.getResponseInfo(ret, resp);

        if (ent != null) {
            if (getString)
                ret.put("content", this.getContentString(ent.getContent()));
            else {
                Map<String, Object> obj = this.eng.newObj("Buffer");
                obj.put("data", this.getContentBinary(ent.getContent()));
                ret.put("content", obj);
            }

            EntityUtils.consume(ent);
        }
    } catch (ClientProtocolException e) {
        throw new ic9exception("httpClient.performRequest(): Client protocol exception. " + e.getMessage());
    } catch (IOException e) {
        throw new ic9exception("httpClient.performRequest(): IO exception. " + e.getMessage());
    } catch (KeyManagementException e) {
        throw new ic9exception("httpClient.performRequest(): Key management exception. " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new ic9exception("httpClient.performRequest(): No such algorithm exception. " + e.getMessage());
    } catch (KeyStoreException e) {
        throw new ic9exception("httpClient.performRequest(): Key store exception. " + e.getMessage());
    } catch (AuthenticationException e) {
        throw new ic9exception("httpClient.performRequest(): Authentication exception. " + e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        throw new ic9exception("httpClient.performRequest(): Unhandled exception. " + e.getMessage());
    } finally {
        // Reset credentials
        if (this.creds != null) {
            this.creds = null;
            this.atype = authType.NONE;
        }
        if (resp != null) {
            try {
                resp.close();
            } catch (IOException e) {
            }
        }
        if (reqType == httpReqType.POST || reqType == httpReqType.PUT)
            this.respEnt = null;
    }

    // Release the connection.
    httpReq.releaseConnection();

    return ret;
}

From source file:zsk.YTDownloadThread.java

boolean downloadone(String sURL) {
    boolean rc = false;
    boolean rc204 = false;
    boolean rc302 = false;

    this.iRecursionCount++;

    // stop recursion
    try {/* ww w .j a v  a2s.co  m*/
        if (sURL.equals(""))
            return (false);
    } catch (NullPointerException npe) {
        return (false);
    }
    if (JFCMainClient.getbQuitrequested())
        return (false); // try to get information about application shutdown

    debugoutput("start.");

    // TODO GUI option for proxy?
    // http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube
    // using local squid to save download time for tests

    try {
        // determine http_proxy environment variable
        if (!this.getProxy().equals("")) {

            String sproxy = JFCMainClient.sproxy.toLowerCase().replaceFirst("http://", "");
            this.proxy = new HttpHost(sproxy.replaceFirst(":(.*)", ""),
                    Integer.parseInt(sproxy.replaceFirst("(.*):", "")), "http");

            SchemeRegistry supportedSchemes = new SchemeRegistry();
            supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
            supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUseExpectContinue(params, true);

            ClientConnectionManager ccm = new PoolingClientConnectionManager(supportedSchemes);

            // with proxy
            this.httpclient = new DefaultHttpClient(ccm, params);
            this.httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, this.proxy);
            this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
        } else {
            // without proxy
            this.httpclient = new DefaultHttpClient();
            this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
        }
        this.httpget = new HttpGet(getURI(sURL));
        if (sURL.toLowerCase().startsWith("https"))
            this.target = new HttpHost(getHost(sURL), 443, "https");
        else
            this.target = new HttpHost(getHost(sURL), 80, "http");
    } catch (Exception e) {
        debugoutput(e.getMessage());
    }

    debugoutput("executing request: ".concat(this.httpget.getRequestLine().toString()));
    debugoutput("uri: ".concat(this.httpget.getURI().toString()));
    debugoutput("host: ".concat(this.target.getHostName()));
    debugoutput("using proxy: ".concat(this.getProxy()));

    // we dont need cookies at all because the download runs even without it (like my wget does) - in fact it blocks downloading videos from different webpages, because we do not handle the bcs for every URL (downloading of one video with different resolutions does work)
    /*
    this.localContext = new BasicHttpContext();
    if (this.bcs == null) this.bcs = new BasicCookieStore(); // make cookies persistent, otherwise they would be stored in a HttpContext but get lost after calling org.apache.http.impl.client.AbstractHttpClient.execute(HttpHost target, HttpRequest request, HttpContext context)
    ((DefaultHttpClient) httpclient).setCookieStore(this.bcs); // cast to AbstractHttpclient would be best match because DefaultHttpClass is a subclass of AbstractHttpClient
    */

    // TODO maybe we save the video IDs+res that were downloaded to avoid downloading the same video again?

    try {
        this.response = this.httpclient.execute(this.target, this.httpget, this.localContext);
    } catch (ClientProtocolException cpe) {
        debugoutput(cpe.getMessage());
    } catch (UnknownHostException uhe) {
        output((JFCMainClient.isgerman() ? "Fehler bei der Verbindung zu: " : "error connecting to: ")
                .concat(uhe.getMessage()));
        debugoutput(uhe.getMessage());
    } catch (IOException ioe) {
        debugoutput(ioe.getMessage());
    } catch (IllegalStateException ise) {
        debugoutput(ise.getMessage());
    }

    /*
    CookieOrigin cookieOrigin = (CookieOrigin) localContext.getAttribute( ClientContext.COOKIE_ORIGIN);
    CookieSpec cookieSpec = (CookieSpec) localContext.getAttribute( ClientContext.COOKIE_SPEC);
    CookieStore cookieStore = (CookieStore) localContext.getAttribute( ClientContext.COOKIE_STORE) ;
    try { debugoutput("HTTP Cookie store: ".concat( cookieStore.getCookies().toString( )));
    } catch (NullPointerException npe) {} // useless if we don't set our own CookieStore before calling httpclient.execute
    try {
       debugoutput("HTTP Cookie origin: ".concat(cookieOrigin.toString()));
       debugoutput("HTTP Cookie spec used: ".concat(cookieSpec.toString()));
       debugoutput("HTTP Cookie store (persistent): ".concat(this.bcs.getCookies().toString()));
    } catch (NullPointerException npe) {
    }
    */

    try {
        debugoutput("HTTP response status line:".concat(this.response.getStatusLine().toString()));
        //for (int i = 0; i < response.getAllHeaders().length; i++) {
        //   debugoutput(response.getAllHeaders()[i].getName().concat("=").concat(response.getAllHeaders()[i].getValue()));
        //}

        // abort if HTTP response code is != 200, != 302 and !=204 - wrong URL?
        if (!(rc = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)200(.*)"))
                & !(rc204 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)204(.*)"))
                & !(rc302 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)302(.*)"))) {
            debugoutput(this.response.getStatusLine().toString().concat(" ").concat(sURL));
            output(this.response.getStatusLine().toString().concat(" \"").concat(this.sTitle).concat("\""));
            return (rc & rc204 & rc302);
        }
        if (rc204) {
            debugoutput("last response code==204 - download: ".concat(this.vNextVideoURL.get(0).getsYTID()));
            rc = downloadone(this.vNextVideoURL.get(0).getsURL());
            return (rc);
        }
        if (rc302)
            debugoutput(
                    "location from HTTP Header: ".concat(this.response.getFirstHeader("Location").toString()));

    } catch (NullPointerException npe) {
        // if an IllegalStateException was catched while calling httpclient.execute(httpget) a NPE is caught here because
        // response.getStatusLine() == null
        this.sVideoURL = null;
    }

    HttpEntity entity = null;
    try {
        entity = this.response.getEntity();
    } catch (NullPointerException npe) {
    }

    // try to read HTTP response body
    if (entity != null) {
        try {
            if (this.response.getFirstHeader("Content-Type").getValue().toLowerCase().matches("^text/html(.*)"))
                this.textreader = new BufferedReader(new InputStreamReader(entity.getContent()));
            else
                this.binaryreader = new BufferedInputStream(entity.getContent());
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            // test if we got a webpage
            this.sContentType = this.response.getFirstHeader("Content-Type").getValue().toLowerCase();
            if (this.sContentType.matches("^text/html(.*)")) {
                rc = savetextdata();
                // test if we got the binary content
            } else if (this.sContentType.matches("video/(.)*")) {
                if (JFCMainClient.getbNODOWNLOAD())
                    reportheaderinfo();
                else
                    savebinarydata();
            } else { // content-type is not video/
                rc = false;
                this.sVideoURL = null;
            }
        } catch (IOException ex) {
            try {
                throw ex;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (RuntimeException ex) {
            try {
                throw ex;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } //if (entity != null)

    this.httpclient.getConnectionManager().shutdown();

    debugoutput("done: ".concat(sURL));
    if (this.sVideoURL == null)
        this.sVideoURL = ""; // to prevent NPE

    if (!this.sVideoURL.matches(JFCMainClient.szURLREGEX)) {
        // no more recursion - html source hase been read
        // test !rc than video could not downloaded because of some error (like wrong protocol or restriction)
        if (!rc) {
            debugoutput("cannot download video - URL does not seem to be valid or could not be found: "
                    .concat(this.sURL));
            output(JFCMainClient.isgerman()
                    ? "es gab ein Problem die Video URL zu finden! evt. wegen Landesinschrnkung?!"
                    : "there was a problem getting the video URL! perhaps not allowed in your country?!");
            output((JFCMainClient.isgerman() ? "erwge die URL dem Autor mitzuteilen!"
                    : "consider reporting the URL to author! - ").concat(this.sURL));
            this.sVideoURL = null;
        }
    } else {
        // enter recursion - download video resource
        debugoutput("try to download video from URL: ".concat(this.sVideoURL));
        rc = downloadone(this.sVideoURL);
    }
    this.sVideoURL = null;

    return (rc);

}

From source file:com.pennassurancesoftware.tutum.client.TutumClient.java

private String executeHttpRequest(HttpRequestBase request) throws TutumException, RequestUnsuccessfulException {
    String response = "";
    try {/*  www.  j a  v a2s  .co m*/
        final HttpResponse httpResponse = httpClient.execute(request);
        LOG.debug("HTTP Response Object:: " + httpResponse);
        response = evaluateResponse(request, httpResponse);
        LOG.debug("Parsed Response:: " + response);
    } catch (ClientProtocolException cpe) {
        throw new RequestUnsuccessfulException(cpe.getMessage(), cpe);
    } catch (IOException ioe) {
        throw new RequestUnsuccessfulException(ioe.getMessage(), ioe);
    } finally {
        request.releaseConnection();
    }
    return response;
}

From source file:nl.esciencecenter.ptk.web.WebClient.java

protected int executeDelete(HttpDelete delMethod, StringHolder responseTextHolder,
        StringHolder contentTypeHolder) throws WebException {
    logger.debugPrintf("executeDelete():'%s'\n", delMethod.getRequestLine());

    try {/* w w w.j av  a  2 s. c  o  m*/
        HttpResponse response;
        response = httpClient.execute(delMethod);

        logger.debugPrintf("--------------- HttpDelete Response -------------------------\n");
        logger.debugPrintf("%s\n", response.getStatusLine());

        int status = handleStringResponse("HttpDelete:" + delMethod.getRequestLine(), response,
                responseTextHolder, contentTypeHolder);
        this.lastHttpStatus = status;
        return status;

    } catch (ClientProtocolException e) {
        throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, e.getMessage(), e);
    } catch (IOException e) {
        throw new WebException(WebException.Reason.IOEXCEPTION, e.getMessage(), e);
    } finally {
        delMethod.releaseConnection();
    }
}

From source file:nl.esciencecenter.ptk.web.WebClient.java

/**
 * Execute Get Method and handle the String response. Returns actual HTTP
 * Status. Does not do any HTTP status handling.
 * /*  w w  w. j  a  v  a 2s. c o  m*/
 * @param getMethod
 *            - HttpGet method to execute
 * @param responseTextHolder
 *            - Optional StringHolder for the Response
 * @param contentTypeHolder
 *            - Optional StringHolder for the contentType.
 * @return - actual HTTP Status as returned by server.
 * @throws WebException
 *             if a communication error occurred.
 */
protected int executeGet(HttpGet getMethod, StringHolder responseTextHolder, StringHolder contentTypeHolder)
        throws WebException {
    logger.debugPrintf("executeGet():'%s'\n", getMethod.getRequestLine());

    if (this.httpClient == null) {
        throw new NullPointerException("HTTP Client not properly initialized: httpClient==null");
    }

    try {
        HttpResponse response;
        response = httpClient.execute(getMethod);

        logger.debugPrintf("--------------- HttpGet Response -------------------------\n");
        logger.debugPrintf("%s\n", response.getStatusLine());

        int status = handleStringResponse("HttpGet:" + getMethod.getRequestLine(), response, responseTextHolder,
                contentTypeHolder);

        this.lastHttpStatus = status;
        return status;

    } catch (ClientProtocolException e) {
        throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, e.getMessage(), e);
    } catch (IOException e) {
        throw new WebException(WebException.Reason.IOEXCEPTION, e.getMessage(), e);
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.ymkm.lib.http.HttpRequester.java

private static HttpResponseHolder request(HttpRequestHolder loadReq) {
    HttpClient client = null;//from w  w w  . j  a v a2s.  co m

    ExecutableRequest req = loadReq.http;
    HttpRequestListener listener = loadReq.listener;
    HttpParams params = req.getParams();

    if (null == params) {
        params = new BasicHttpParams();
    }
    if (null != listener) {
        listener.setRequestParams(params);
    }

    // Use Android specific client if available
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
        client = android.net.http.AndroidHttpClient.newInstance(android_user_agent);
    } else {
        // Sets up the http part of the service.
        final SchemeRegistry supportedSchemes = new SchemeRegistry();
        // Register the "http" protocol scheme, it is required
        // by the default operator to look up socket factories.
        final SocketFactory sf = PlainSocketFactory.getSocketFactory();
        supportedSchemes.register(new Scheme("http", sf, 80));
        supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);
        client = new DefaultHttpClient(ccm, params);
    }
    req.setParams(params);

    if (null != listener) {
        listener.setHttpClient(client);
    }

    HttpResponse resp = null;
    HttpResponseHolder holder = new HttpResponseHolder();
    holder.uri = Uri.parse(req.getURI().toString());

    try {
        resp = client.execute(req);
        holder.returnCode = resp.getStatusLine().getStatusCode();
        Header[] hdrs = resp.getAllHeaders();
        if (hdrs.length > 0) {
            for (Header h : hdrs) {
                holder.headers.put(h.getName(), h.getValue());
            }
        }

        if ("application/octet-stream".equals(resp.getFirstHeader("Content-Type").getValue())) {
            int len = 0;
            byte[] buffer = new byte[1024];
            InputStream is = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            try {
                is = resp.getEntity().getContent();

                while (0 < (len = is.read(buffer))) {
                    baos.write(buffer, 0, len);
                }
                holder.responseBytes = baos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (null != baos) {
                    try {
                        baos.close();
                    } catch (IOException e) {
                    }
                }
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        } else {
            Reader r = null;
            int length = 1024;
            if (null != resp.getFirstHeader("Content-Length")) {
                length = Integer.parseInt(resp.getFirstHeader("Content-Length").getValue());
            }
            // Set initial size for StringBuilder buffer to be content length + some extra
            StringBuilder sb = new StringBuilder(length + 10);
            try {
                r = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
                String s = null;
                while ((s = ((BufferedReader) r).readLine()) != null) {
                    sb.append(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (null != r) {
                    try {
                        r.close();
                    } catch (IOException e) {
                    }
                }
            }
            holder.responseBody = sb.toString();
        }
        return holder;
    } catch (HttpResponseException hre) {
        holder.responseBody = hre.getMessage();
        holder.returnCode = hre.getStatusCode();
        return holder;
    } catch (ClientProtocolException cpe) {
        cpe.printStackTrace();
        holder.responseBody = cpe.getMessage();
        holder.returnCode = 500;
        return holder;
    } catch (Exception exc) {
        exc.printStackTrace();
        holder.responseBody = exc.getMessage();
        holder.returnCode = 500;
        return holder;
    } finally {
        // Use Android specific client if available
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
            ((android.net.http.AndroidHttpClient) client).close();
        }
    }
}