Example usage for org.apache.commons.httpclient HttpException printStackTrace

List of usage examples for org.apache.commons.httpclient HttpException printStackTrace

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Print this HttpException and its stack trace to the standard error stream.

Usage

From source file:org.archive.wayback.liveweb.URLCacher.java

protected ExtendedGetMethod urlToFile(String urlString, File file)
        throws LiveDocumentNotAvailableException, URIException, IOException {

    HttpClient http = getHttpClient();//from w w w.  j a v a2  s.  co m
    OutputStream os = new FileOutputStream(file);
    ExtendedGetMethod method = new ExtendedGetMethod(os);
    LaxURI lURI = new LaxURI(urlString, true);
    method.setURI(lURI);
    try {
        int code = http.executeMethod(method);
        os.close();
        // TODO: Constant 200
        if (code != 200) {
            throw new LiveDocumentNotAvailableException(urlString);
        }
    } catch (HttpException e) {
        e.printStackTrace();
        throw new LiveDocumentNotAvailableException(urlString);
    } catch (UnknownHostException e) {
        LOGGER.info("Unknown host for URL " + urlString);
        throw new LiveDocumentNotAvailableException(urlString);
    } catch (ConnectTimeoutException e) {
        LOGGER.info("Connection Timeout for URL " + urlString);
        throw new LiveDocumentNotAvailableException(urlString);
    } catch (NoRouteToHostException e) {
        LOGGER.info("No route to host for URL " + urlString);
        throw new LiveDocumentNotAvailableException(urlString);
    } catch (ConnectException e) {
        LOGGER.info("ConnectException URL " + urlString);
        throw new LiveDocumentNotAvailableException(urlString);
    }
    LOGGER.info("Stored " + urlString + " in " + file.getAbsolutePath());
    return method;
}

From source file:org.bbaw.pdr.ae.view.identifiers.internal.ConcurrenceSearchController.java

private String requestWebService(URL url) throws URISyntaxException, UnsupportedEncodingException {
    String result = null;// www .  j  a va 2 s.  c o m
    if (url != null) {
        HttpClient client = new HttpClient();

        // System.out.println("url " + url.toString());
        // PostMethod method = null;
        HttpClient httpclient = null;
        httpclient = new HttpClient();

        String urlString = new String(url.toString());
        if (urlString.contains(" ")) {
            // System.out.println("containts ws");
            urlString.replace(" ", "%20");
        }
        Pattern p = Pattern.compile("\\s");
        Matcher m = p.matcher(urlString);
        // while (m.find())
        // {
        // // System.out.println("\\s");
        // }
        urlString = m.replaceAll("%20");
        // while (m.find())
        // {
        // System.out.println("2.\\s");
        // }
        // urlString = URLEncoder.encode(urlString, "UTF-8");
        // urlString.replace("\\s+", "%20");
        GetMethod get = new GetMethod(urlString);
        HostConfiguration hf = new HostConfiguration();
        hf.setHost(urlString, url.getPort());
        httpclient.setHostConfiguration(hf);
        // get = new PostMethod(theURL);
        // LogHelper.logMessage("Before sending SMS Message: "+message);
        int respCode;
        try {
            respCode = httpclient.executeMethod(get);
            log = new Status(IStatus.INFO, Activator.PLUGIN_ID, "Response code: " + respCode);
            iLogger.log(log);
            // successful.

            /* send request */
            final int status = client.executeMethod(get);
            // LOG.debug("http status #execute: " +
            // Integer.toString(status));
            switch (status) {
            case HttpStatus.SC_NOT_IMPLEMENTED:
                get.releaseConnection();
                // throw new IOException("Solr Query #GET (" +
                // get.getURI().toString() + ") returned 501");
            default:
                result = get.getResponseBodyAsString();
                get.releaseConnection();
            }
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return result;
}

From source file:org.bigbluebutton.api.ParamsProcessorUtil.java

private String getConfig(String url) {
    HttpClient client = new HttpClient();
    GetMethod get = new GetMethod(url);
    String configXML = "";
    try {//from ww  w .ja  v  a 2s. com
        client.executeMethod(get);
        configXML = get.getResponseBodyAsString();
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return configXML;
}

From source file:org.camera.service.CAMERARESTService.java

/**
 * File & regular parameters are passed as two separate lists and they are treated
 * little differently. If flPairList is not null or empty then this method uses Part
 * Object else no./*from   w  w  w .  j av  a 2s .co m*/
 * @param pmPairList List of the name and value parameters that user has provided
 * @param flPairList List of the name and value (full file path)of file parameters.
 *          It is essentially a list of files that user wishes to attach.
 * @return  the results after executing the Post service.
 */
public String executePostMethod(List<NameValuePair> pmPairList, List<NameValuePair> flPairList,
        String serSiteURL) throws IllegalActionException {

    if (_debugging) {
        _debug("I AM IN POST METHOD");
    }

    log.debug("I AM IN POST METHOD");
    String postAddress = serSiteURL;

    HttpClient client = new HttpClient();
    MultipartPostMethod method = new MultipartPostMethod(postAddress);
    List<NameValuePair> fullNameValueList = pmPairList;
    if (flPairList != null && flPairList.size() > 0) {
        fullNameValueList.addAll(flPairList);
        int totalSize = fullNameValueList.size();
        Part[] parts = new Part[totalSize];

        try {

            for (int i = 0; i < parts.length; i++) {

                String nm = fullNameValueList.get(i).getName();
                String vl = fullNameValueList.get(i).getValue();

                if (i > totalSize - flPairList.size() - 1) {
                    System.out.println("FILE NAME: " + nm);
                    File file = getFileObject(vl);
                    System.out.println("FILE NAME: " + file.getName());
                    parts[i] = new FilePart(nm, file);
                    method.addPart(parts[i]);
                    System.out.println("PARTS: " + i + " " + parts[i].getName());
                    System.out.println("file Name: " + vl);

                } else {

                    System.out.println("PARAMETER NAME: " + nm);
                    System.out.println("PARAMETER Value: " + vl);
                    parts[i] = new StringPart(nm, vl);
                    method.addPart(parts[i]);

                }
                if (_debugging) {
                    _debug("Value of i: " + i);
                }

            }

        } catch (FileNotFoundException fnfe) {
            if (_debugging) {
                _debug("File Not Found Exception: " + fnfe.getMessage());
            }
            fnfe.printStackTrace();
            throw new IllegalActionException("File Not Found: " + fnfe.getMessage());
        }
    } else {
        for (NameValuePair nmPair : fullNameValueList) {
            method.addParameter(nmPair.getName(), nmPair.getValue());
            System.out.println("Name: " + nmPair.getName() + "  Value:" + nmPair.getValue());
        }
    }

    InputStream rstream = null;
    StringBuilder results = new StringBuilder();
    try {

        messageBldr = new StringBuilder();
        messageBldr.append("In excutePostMethod, communicating with service: ").append(serSiteURL)
                .append("   STATUS Code: ");

        int statusCode = client.executeMethod(method);
        messageBldr.append(statusCode);

        log.debug("DEBUG: " + messageBldr.toString());
        System.out.println(messageBldr.toString());

        rstream = method.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));

        log.debug("BEFORE WHILE LOOP");
        String s;
        while ((s = br.readLine()) != null) {
            results.append(s).append(ServiceUtils.LINESEP);
        }

    } catch (HttpException httpe) {
        if (_debugging) {
            _debug("Fatal protocol violation: " + httpe.getMessage());
        }
        httpe.printStackTrace();
        //            return "Protocol Violation";
        throw new IllegalActionException("Fatal protocol violation: " + httpe.getMessage());
    } catch (ConnectException conExp) {
        if (_debugging) {
            _debug("Perhaps service not reachable: " + conExp.getMessage());
        }

        conExp.printStackTrace();
        throw new IllegalActionException("Perhaps service not reachable: " + conExp.getMessage());
        //         return "Perhaps service not reachable";
    } catch (IOException ioe) {
        if (_debugging) {
            _debug("Fatal transport error: " + ioe.getMessage());
        }

        ioe.printStackTrace();
        //            return "IOException: Perhaps could not connect to the service.";
        throw new IllegalActionException("Fatal transport error: " + ioe.getMessage());
    } catch (Exception e) {
        if (_debugging) {
            _debug("Unknown error: " + e.getMessage());
        }
        e.printStackTrace();
        //            return "Exception: Unknown type error";
        throw new IllegalActionException("Error: " + e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return results.toString();
}

From source file:org.camera.service.CAMERARESTService.java

/**
 *  /*from   ww w .ja v  a2 s .  c om*/
 * @param pmPairList List of the name and value parameters that user has provided
 * through paramInputPort. However in  method this list is combined with
 * the user configured ports and the combined list name value pair parameters are
 * added to the service URL separated by ampersand.
 * @param nvPairList List of the name and value parameters that user has provided
 * @return the results after executing the Get service.
 */
public String executeGetMethod(List<NameValuePair> nvPairList, String serSiteURL)
        throws IllegalActionException {

    if (_debugging) {
        _debug("I AM IN GET METHOD");
    }

    HttpClient client = new HttpClient();

    StringBuilder results = new StringBuilder();
    results.append(serSiteURL);
    //Files cannot be attached with GET
    List<NameValuePair> fullPairList = nvPairList;// getCombinedPairList(nvPairList);

    if (fullPairList.size() > 0) {

        results.append("?");

        int pairListSize = fullPairList.size();
        for (int j = 0; j < pairListSize; j++) {
            NameValuePair nvPair = fullPairList.get(j);
            results.append(nvPair.getName()).append(ServiceUtils.EQUALDELIMITER).append(nvPair.getValue());
            if (j < pairListSize - 1) {
                results.append("&");
            }

        }
    }
    if (_debugging) {
        _debug("RESULTS :" + results.toString());
    }

    // Create a method instance.
    GetMethod method = new GetMethod(results.toString());
    InputStream rstream = null;
    StringBuilder resultsForDisplay = new StringBuilder();

    try {

        messageBldr = new StringBuilder();
        messageBldr.append("In excutePostMethod, communicating with service: ").append(serSiteURL)
                .append("   STATUS Code: ");

        int statusCode = client.executeMethod(method);
        messageBldr.append(statusCode);

        log.debug("DEBUG: " + messageBldr.toString());
        System.out.println(messageBldr.toString());

        rstream = method.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));

        String s;
        while ((s = br.readLine()) != null) {
            resultsForDisplay.append(s).append(ServiceUtils.LINESEP);
        }

    } catch (HttpException httpe) {
        if (_debugging) {
            _debug("Fatal protocol violation: " + httpe.getMessage());
        }
        httpe.printStackTrace();
        //            return "Protocol Violation";
        throw new IllegalActionException("Fatal protocol violation: " + httpe.getMessage());
    } catch (ConnectException conExp) {
        if (_debugging) {
            _debug("Perhaps service not reachable: " + conExp.getMessage());
        }
        conExp.printStackTrace();
        throw new IllegalActionException("Perhaps service not reachable: " + conExp.getMessage());
    } catch (IOException ioe) {
        if (_debugging) {
            _debug("Fatal transport error: " + ioe.getMessage());
        }
        ioe.printStackTrace();
        //            return "IOException: fatal transport error";
        throw new IllegalActionException("Fatal transport error: " + ioe.getMessage());
    } catch (Exception e) {
        if (_debugging) {
            _debug("Unknown error: " + e.getMessage());
        }
        e.printStackTrace();
        //            return "Exception: Unknown type error";
        throw new IllegalActionException("Error: " + e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return resultsForDisplay.toString();

}

From source file:org.dbpedia.spotlight.web.client.RestApiTests.java

private static String http_client(String text, String url, String disambiguator) {
    System.out.println("*** HTTP Client");
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
    method.setRequestHeader("Accept", "application/json");
    method.addParameter("disambiguator", disambiguator);
    method.addParameter("confidence", "-1");
    method.addParameter("support", "-1");
    method.addParameter("text", text);

    // Send POST request
    StringBuffer jsonString = new StringBuffer();
    int statusCode;
    try {/*  ww  w.  j  a v  a2s.co  m*/
        statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        InputStream rstream = null;
        rstream = method.getResponseBodyAsStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
        String line;

        while ((line = br.readLine()) != null) {
            jsonString.append(line);
            jsonString.append("\n");
        }
        System.out.println(jsonString);
        br.close();
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jsonString.toString();
}

From source file:org.deegree.enterprise.servlet.ProxyServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    String url = req.getParameter("URL");
    try {//w w  w.  j  a  v  a2 s.co m
        HttpMethod result = HttpUtils.performHttpPost(url, req.getInputStream(), 0, null, null,
                req.getContentType(), req.getCharacterEncoding(), null);
        InputStream in = result.getResponseBodyAsStream();
        IOUtils.getInstance().copyStreams(in, resp.getOutputStream());
        in.close();
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.deri.pipes.endpoints.SindiceProxy.java

public String readHTTP(String url) {
    HttpClient client = new HttpClient();

    GetMethod method = new GetMethod(url);

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

    //TODO:set Accept : "Accept: application/json"

    try {//from  w w w . ja v  a 2s. co  m

        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
            return null;
        }

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

From source file:org.easyframework.core.crawl.GetSample.java

public static Map<String, String> get(String url) {
    Map<String, String> result = new HashMap<String, String>();
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    try {/*from  ww  w  .ja va 2 s  . c  o  m*/
        int statusCode = client.executeMethod(method);
        String charset = method.getResponseCharSet();
        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }
        byte[] responseBody = method.getResponseBody();
        result.put(GetSample.RESPONSE_TEXT, new String(responseBody, charset));
        result.put(GetSample.CHARSET, charset);
    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        method.releaseConnection();
        return result;
    }

}

From source file:org.eclipse.e4.opensocial.container.internal.browserHandlers.core.MakeXmlHttpRequestHandler.java

@Override
public Object handle(final Browser browser, final Object[] arguments) {
    /*/*from   w ww.  jav  a  2 s .  co m*/
     * function('makeXmlHttpRequest', url, callback, method, contentType,
     * headers, postData)
     */
    try {
        // Retrieve arguments
        String url = (String) arguments[1];
        String callback = (String) arguments[2];
        String method = (String) arguments[3];
        String contentType = (String) arguments[4];
        // headers format :
        // headerName#headerValue\nheader2Name#header2Value
        String headers = (String) arguments[5];
        String postData = (String) arguments[6];

        HttpClient httpClient = new HttpClient();
        // Create GET or POST http method
        HttpMethod httpMethod = createMethod(url, method);

        // Add needed headers
        if (!"".equals(headers))
            addHeaders(httpMethod, headers);

        // Handle PostData if needed
        if (postData != null) {
            ((PostMethod) httpMethod).setRequestEntity(new StringRequestEntity(postData, "text/xml", "utf-8"));
        }

        int status = httpClient.executeMethod(httpMethod);

        String responseBodyAsString = retrieveResponseBody(httpMethod);

        // FIXME: at the moment, remove single quotes causing js
        // problems.
        responseBodyAsString = responseBodyAsString.replaceAll("'", " ");

        String responseScript = "\n";
        // Create and fill response object
        responseScript += "var response = new Object();\n";
        responseScript += "response.rc=" + status + ";\n";
        responseScript += "response.text='" + responseBodyAsString + "';\n";

        // Create the response's data property
        if ("DOM".equals(contentType)) {
            responseScript = createDOMResponseData(responseScript);
        } else if ("JSON".equals(contentType)) {
            responseScript = createJSONResponseData(responseBodyAsString, responseScript);
        } else if ("TEXT".equals(contentType)) {
            responseScript = createTEXTReponseData(responseScript);
        } else if ("FEED".equals(contentType)) {
            // FIXME : Not implemented for the moment.
            responseScript = createFEEDResponseData(responseScript);
        }

        // Instanciate and call callback
        responseScript += "(" + callback + ")(response);\n";

        final String script = responseScript;
        Display.getDefault().asyncExec(new Runnable() {
            public void run() {
                browser.execute(script);
            }
        });
        return status;
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return HttpStatus.SC_INTERNAL_SERVER_ERROR;
}