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

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

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:edu.unc.lib.dl.admin.controller.RESTProxyController.java

@RequestMapping(value = { "/services/rest", "/services/rest/*", "/services/rest/**/*" })
public final void proxyAjaxCall(HttpServletRequest request, HttpServletResponse response) throws IOException {
    log.debug("Prepending service url " + this.servicesUrl + " to " + request.getRequestURI());
    String url = request.getRequestURI().replaceFirst(".*/services/rest/?", this.servicesUrl);
    if (request.getQueryString() != null)
        url = url + "?" + request.getQueryString();

    OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
    HttpClient client = new HttpClient();
    HttpMethod method = null;/*from   w ww. j a va2s.  c o  m*/
    try {
        log.debug("Proxying ajax request to services REST api via " + request.getMethod());
        // Split this according to the type of request
        if (request.getMethod().equals("GET")) {
            method = new GetMethod(url);
        } else if (request.getMethod().equals("POST")) {
            method = new PostMethod(url);
            // Set any eventual parameters that came with our original
            // request (POST params, for instance)
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                ((PostMethod) method).setParameter(paramName, request.getParameter(paramName));
            }
        } else {
            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

        // Forward the user's groups along with the request
        method.addRequestHeader(HttpClientUtil.SHIBBOLETH_GROUPS_HEADER, GroupsThreadStore.getGroupString());
        method.addRequestHeader("On-Behalf-Of", GroupsThreadStore.getUsername());

        // Execute the method
        client.executeMethod(method);

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {
            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }
        }
        try (InputStream responseStream = method.getResponseBodyAsStream()) {
            int b;
            while ((b = responseStream.read()) != -1) {
                response.getOutputStream().write(b);
            }
        }
        response.getOutputStream().flush();
    } catch (HttpException e) {
        writer.write(e.toString());
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        writer.write(e.toString());
        throw e;
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:edu.ku.brc.helpers.HTTPGetter.java

/**
 * Performs a "generic" HTTP request and fill member variable with results
 * use "getDigirResultsetStr" to get the results as a String
 *
 * @param url URL to be executed/* ww w  . j  av a  2  s .c  om*/
 * @param fileCache the file to place the results
 * @return returns an error code
 */
public byte[] doHTTPRequest(final String url, final File fileCache) {
    byte[] bytes = null;
    Exception excp = null;
    status = ErrorCode.NoError;

    // Create an HttpClient with the MultiThreadedHttpConnectionManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());

    GetMethod method = null;
    try {
        method = new GetMethod(url);

        //log.debug("getting " + method.getURI()); //$NON-NLS-1$
        httpClient.executeMethod(method);

        // get the response body as an array of bytes
        long bytesRead = 0;
        if (fileCache == null) {
            bytes = method.getResponseBody();
            bytesRead = bytes.length;

        } else {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileCache));
            bytes = new byte[4096];
            InputStream ins = method.getResponseBodyAsStream();
            BufferedInputStream bis = new BufferedInputStream(ins);
            while (bis.available() > 0) {
                int numBytes = bis.read(bytes);
                if (numBytes > 0) {
                    bos.write(bytes, 0, numBytes);
                    bytesRead += numBytes;
                }
            }

            bos.flush();
            bos.close();

            bytes = null;
        }

        log.debug(bytesRead + " bytes read"); //$NON-NLS-1$

    } catch (ConnectException ce) {
        excp = ce;
        log.error(String.format("Could not make HTTP connection. (%s)", ce.toString())); //$NON-NLS-1$
        status = ErrorCode.HttpError;

    } catch (HttpException he) {
        excp = he;
        log.error(String.format("Http problem making request.  (%s)", he.toString())); //$NON-NLS-1$
        status = ErrorCode.HttpError;

    } catch (IOException ioe) {
        excp = ioe;
        log.error(String.format("IO problem making request.  (%s)", ioe.toString())); //$NON-NLS-1$
        status = ErrorCode.IOError;

    } catch (java.lang.IllegalArgumentException ioe) {
        excp = ioe;
        log.error(String.format("IO problem making request.  (%s)", ioe.toString())); //$NON-NLS-1$
        status = ErrorCode.IOError;

    } catch (Exception e) {
        excp = e;
        log.error("Error: " + e); //$NON-NLS-1$
        status = ErrorCode.Error;

    } finally {
        // always release the connection after we're done
        if (isThrowingErrors && status != ErrorCode.NoError) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(HTTPGetter.class, excp);
        }

        if (method != null)
            method.releaseConnection();
        //log.debug("Connection released"); //$NON-NLS-1$
    }

    if (listener != null) {
        if (status == ErrorCode.NoError) {
            listener.completed(this);
        } else {
            listener.completedWithError(this, status);
        }
    }

    return bytes;
}

From source file:de.ingrid.portal.interfaces.impl.WMSInterfaceImpl.java

public String getWMCDocument(String sessionId) {
    String response = null;//from w  ww  .java  2  s. co  m

    try {
        String urlStr = config.getString("interface_url",
                "http://localhost/mapbender/php/mod_portalCommunication_gt.php");
        if (urlStr.indexOf("?") > 0) {
            urlStr = urlStr.concat("&PREQUEST=getWMC").concat("&PHPSESSID=" + sessionId);
        } else {
            urlStr = urlStr.concat("?PREQUEST=getWMC").concat("&PHPSESSID=" + sessionId);
        }

        if (log.isDebugEnabled()) {
            log.debug("MapBender Server Request: " + urlStr);
        }

        //          Create an instance of HttpClient.
        HttpClient client = new HttpClient();

        // Create a method instance.
        GetMethod method = new GetMethod(urlStr);

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(2, false));

        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                log.error("Requesting WMC faild for URL: " + urlStr);
            }

            // Read the response body.
            byte[] responseBody = method.getResponseBody();

            response = new String(responseBody);

        } catch (HttpException e) {
            log.error("Fatal protocol violation: " + e.getMessage(), e);
        } catch (IOException e) {
            log.error("Fatal transport error: " + e.getMessage(), e);
        } finally {
            // Release the connection.
            method.releaseConnection();
        }

        if (log.isDebugEnabled()) {
            log.debug("MapBender Server Response: " + response);
        }

        Document document = DocumentHelper.parseText(response);
        // check for valid server response
        String error = document.valueOf("//portal_communication/error");
        if (error != null && error.length() > 0) {
            throw new Exception("MapBender Server Error: " + error);
        }

        String sessionMapBender = document.valueOf("//portal_communication/session");
        if (sessionMapBender != null && !sessionMapBender.equals(sessionId)) {
            throw new Exception(
                    "MapBender Server Error: session Id (" + sessionId + ") from request and session Id ("
                            + sessionMapBender + ") from MapBender are not the same.");
        }

        String urlEncodedWmc = document.valueOf("//portal_communication/wmc");
        return urlEncodedWmc;

    } catch (Exception e) {
        log.error(e.toString());
    }
    return null;
}

From source file:org.eclipse.smarthome.binding.fsinternetradio.internal.radio.FrontierSiliconRadioConnection.java

/**
 * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for
 * future requests./*from w w w  .  j a  v a2 s  . com*/
 *
 * @return <code>true</code> if login was successful; <code>false</code> otherwise.
 * @throws IOException if communication with the radio failed, e.g. because the device is not reachable.
 */
public boolean doLogin() throws IOException {
    isLoggedIn = false; // reset login flag

    if (httpClient == null) {
        httpClient = new HttpClient();
    }

    final String url = "http://" + hostname + ":" + port + "/fsapi/CREATE_SESSION?pin=" + pin;

    logger.trace("opening URL:" + url);

    final HttpMethod method = new GetMethod(url);
    method.getParams().setSoTimeout(SOCKET_TIMEOUT);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        final int statusCode = httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.debug("Communication with radio failed: " + method.getStatusLine());
            if (method.getStatusCode() == 403) {
                throw new RuntimeException("Radio does not allow connection, maybe wrong pin?");
            }
            throw new IOException("Communication with radio failed, return code: " + statusCode);
        }

        final String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.trace("login response: " + responseBody);
        }

        final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
        if (result.isStatusOk()) {
            logger.trace("login successful");
            sessionId = result.getSessionId();
            isLoggedIn = true;
            return true; // login successful :-)
        }

    } catch (HttpException he) {
        logger.debug("Fatal protocol violation: {}", he.toString());
        throw he;
    } catch (IOException ioe) {
        logger.debug("Fatal transport error: {}", ioe.toString());
        throw ioe;
    } finally {
        method.releaseConnection();
    }
    return false; // login not successful
}

From source file:org.eclipse.smarthome.binding.fsinternetradio.internal.radio.FrontierSiliconRadioConnection.java

/**
 * Performs a request to the radio with addition parameters.
 *
 * Typically used for changing parameters.
 *
 * @param REST/*from   ww w .  j a  va  2  s .  c om*/
 *            API requestString, e.g. "SET/netRemote.sys.power"
 * @param params
 *            , e.g. "value=1"
 * @return request result
 * @throws IOException if the request failed.
 */
public FrontierSiliconRadioApiResult doRequest(String requestString, String params) throws IOException {

    // 3 retries upon failure
    for (int i = 0; i < 2; i++) {
        if (!isLoggedIn && !doLogin()) {
            continue; // not logged in and login was not successful - try again!
        }

        final String url = "http://" + hostname + ":" + port + "/fsapi/" + requestString + "?pin=" + pin
                + "&sid=" + sessionId + (params == null || params.trim().length() == 0 ? "" : "&" + params);

        logger.trace("calling url: '" + url + "'");

        final HttpMethod method = new GetMethod(url);
        method.getParams().setSoTimeout(SOCKET_TIMEOUT);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(2, false));

        try {

            final int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                logger.warn("Method failed: " + method.getStatusLine());
                isLoggedIn = false;
                method.releaseConnection();
                continue;
            }

            final String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
            if (!responseBody.isEmpty()) {
                logger.trace("got result: " + responseBody);
            } else {
                logger.debug("got empty result");
                isLoggedIn = false;
                method.releaseConnection();
                continue;
            }

            final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
            if (result.isStatusOk()) {
                return result;
            }

            isLoggedIn = false;
            method.releaseConnection();
            continue; // try again
        } catch (HttpException he) {
            logger.error("Fatal protocol violation: {}", he.toString());
            isLoggedIn = false;
            throw he;
        } catch (IOException ioe) {
            logger.error("Fatal transport error: {}", ioe.toString());
            throw ioe;
        } finally {
            method.releaseConnection();
        }
    }
    isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?)
    return null;
}

From source file:org.eclipse.smarthome.io.net.http.HttpUtil.java

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 * //ww  w .  j ava2s  . c o m
 * @param httpMethod the HTTP method to use
 * @param url the url to execute (in milliseconds)
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or 
 * <code>null</code> if no content should be send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response body or <code>NULL</code> when the request went wrong
 */
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
        String proxyPassword, String nonProxyHosts) {

    HttpClient client = new HttpClient();

    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (StringUtils.isNotBlank(proxyUser)) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
        }
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && content != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    Credentials credentials = extractCredentials(url);
    if (credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.debug("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.debug(e.getMessage());
        }
    }

    try {

        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }

        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }

        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }

    return null;
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.HttpResponse.java

/**
 * Creates new object and fills it with retrieved URL information.
 * //from ww w  .  j a  v a 2s. c  o m
 * @param http
 *          HTTP protocol options HTTP to retrieve
 * @param filterProcessor
 *          filters to perform
 * @param urlString
 *          the url string
 * 
 * @throws IOException
 *           if error while retrieving URL occur
 */
public HttpResponse(HttpBase http, String urlString, FilterProcessor filterProcessor) throws IOException {
    _http = http;
    _urlString = urlString;
    HttpMethodBase httpMethod = null;
    try {
        httpMethod = getHttpMethod();
        setHttpParameters(http, httpMethod);
        _statusCode = Http.getClient().executeMethod(httpMethod);
        final Header[] headers = httpMethod.getResponseHeaders();
        for (int i = 0; i < headers.length; i++) {
            _headers.set(headers[i].getName(), headers[i].getValue());
        }
        // Content-Type filter should go here
        // TODO: Guess content type when Content-Type header is empty
        boolean contentTypeMatches = true;
        final String contentType = _headers.get(Response.CONTENT_TYPE);
        if ((contentType != null) && (filterProcessor != null)) {
            contentTypeMatches = filterProcessor.evaluateContentTypeFilters(contentType);
            LOG.debug("Content type header: " + contentType + ", passed filters: " + contentTypeMatches);
        }
        if (contentTypeMatches) {
            // always read content. Sometimes content is useful to find a cause for error.
            try {
                final InputStream in = httpMethod.getResponseBodyAsStream();
                if (in != null) {
                    final byte[] buffer = new byte[HttpBase.BUFFER_SIZE];
                    int totalRead = 0;
                    final ByteArrayOutputStream out = new ByteArrayOutputStream();
                    int tryAndRead = calculateTryToRead(totalRead);
                    int bufferFilled = in.read(buffer, 0, buffer.length);
                    while (bufferFilled != -1 && tryAndRead > 0) {
                        totalRead += bufferFilled;
                        out.write(buffer, 0, bufferFilled);
                        tryAndRead = calculateTryToRead(totalRead);
                        bufferFilled = in.read(buffer, 0, buffer.length);
                    }
                    _content = out.toByteArray();
                    in.close();
                }
            } catch (HttpException exception) {
                LOG.error("Http error occured ", exception);
                throw new IOException(exception.toString());
            } catch (IOException exception) {
                if (_statusCode == HttpResponseCode.CODE_200) {
                    throw new IOException(exception.toString());
                }
                // for codes other than 200 OK, we are fine with empty content
            }
            if (_content != null) {
                // check if we have to uncompress it
                final String contentEncoding = _headers.get(Response.CONTENT_ENCODING);
                if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
                    _content = http.processGzipEncoded(_content, urlString);
                }
                if (("application/x-gzip".equals(contentType)) || ("application/gzip".equals(contentType))) {
                    _content = http.processGzipEncoded(_content, urlString);
                }
            }
        } else {
            // URL wasn't fetched
            _statusCode = -1;
        }
    } catch (ProtocolException exception) {
        if (LOG.isErrorEnabled()) {
            LOG.error(exception);
        }
        throw new IOException(exception.toString());
    } catch (URISyntaxException exception) {
        if (LOG.isErrorEnabled()) {
            LOG.error(exception);
        }
        throw new IOException(exception.toString());
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.ktunaxa.referral.server.mvc.ProxyController.java

@SuppressWarnings("unchecked")
@RequestMapping(value = "/proxy")
public final void proxyAjaxCall(@RequestParam(required = true, value = "url") String url,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    // URL needs to be url decoded
    url = URLDecoder.decode(url, "utf-8");

    HttpClient client = new HttpClient();
    try {//from   w  w w . j  a  v  a  2  s .  c o m

        HttpMethod method = null;

        // Split this according to the type of request
        if ("GET".equals(request.getMethod())) {

            method = new GetMethod(url);
            NameValuePair[] pairs = new NameValuePair[request.getParameterMap().size()];
            int i = 0;
            for (Object name : request.getParameterMap().keySet()) {
                pairs[i++] = new NameValuePair((String) name, request.getParameter((String) name));
            }
            method.setQueryString(pairs);

        } else if ("POST".equals(request.getMethod())) {

            method = new PostMethod(url);

            // Set any eventual parameters that came with our original
            // request (POST params, for instance)
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {

                String paramName = (String) paramNames.nextElement();
                ((PostMethod) method).setParameter(paramName, request.getParameter(paramName));
            }

        } else {

            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

        // Execute the method
        client.executeMethod(method);

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {

            if (header.getName().equalsIgnoreCase("Content-Type")) {

                response.setContentType(header.getValue());
            }
        }

        // Write the body, flush and close
        response.getOutputStream().write(method.getResponseBody());

    } catch (HttpException e) {

        // log.error("Oops, something went wrong in the HTTP proxy", null, e);
        response.getOutputStream().write(e.toString().getBytes("UTF-8"));
        throw e;

    } catch (IOException e) {

        e.printStackTrace();
        response.getOutputStream().write(e.toString().getBytes("UTF-8"));
        throw e;
    }
}

From source file:org.manalang.monkeygrease.Config.java

public synchronized void load() {

    InputStream is = null;//w  ww  . j a  va 2 s  .c o  m
    GetMethod method = null;

    if (MonkeygreaseFilter.remoteConfigURL != "" && MonkeygreaseFilter.remoteConfigURL != null) {
        method = new GetMethod(MonkeygreaseFilter.remoteConfigURL);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        try {
            // Execute the method.
            int statusCode = MonkeygreaseFilter.client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                MonkeygreaseFilter.log.severe("Method failed: " + method.getStatusLine());
            }
            is = method.getResponseBodyAsStream();
        } catch (HttpException e) {
            MonkeygreaseFilter.log.severe("Fatal protocol violation: " + e.getMessage());
        } catch (IOException e) {
            MonkeygreaseFilter.log.severe("Fatal transport error: " + e.getMessage());
        }

    } else {
        is = context.getResourceAsStream(DEFAULT_WEB_CONF_FILE);

        if (is == null) {
            System.out.println("unable to find monkeygrease conf file " + DEFAULT_WEB_CONF_FILE);
        }
    }

    DocumentBuilder parser;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // factory.setValidating(true);
    // factory.setNamespaceAware(true);
    // factory.setIgnoringComments(true);
    // factory.setIgnoringElementContentWhitespace(true);
    try {
        parser = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        MonkeygreaseFilter.log.severe("Unable to setup XML parser for reading conf " + e.toString());
        return;
    }

    // parser.setErrorHandler(handler);
    // parser.setEntityResolver(handler);

    try {
        Document doc = parser.parse(is);

        if (MonkeygreaseFilter.remoteConfigURL != "" && MonkeygreaseFilter.remoteConfigURL != null)
            method.releaseConnection();

        NodeList rulesConf = doc.getElementsByTagName("rule");
        rules = new Rules();

        for (int i = 0; i < rulesConf.getLength(); i++) {
            Node ruleNode = rulesConf.item(i);
            Rule rule = new Rule(ruleNode);
            if (rule.isEnabled())
                rules.add(rule);
        }
        // processConfDoc(doc);
    } catch (SAXParseException e) {
        MonkeygreaseFilter.log.severe("Parse error on line " + e.getLineNumber() + " " + e.toString());
    } catch (Exception e) {
        MonkeygreaseFilter.log.severe("Exception loading conf " + " " + e.toString());
    }
}

From source file:org.openhab.action.telegram.internal.Telegram.java

@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message")
static public boolean sendTelegram(@ParamDoc(name = "group") String group,
        @ParamDoc(name = "message") String message) {

    if (groupTokens.get(group) == null) {
        logger.error("Bot '{}' not defined, action skipped", group);
        return false;
    }//from  w ww  . j a  v a2 s  .co m

    String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken());

    HttpClient client = new HttpClient();

    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setSoTimeout(HTTP_TIMEOUT);
    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] data = { new NameValuePair("chat_id", groupTokens.get(group).getChatId()),
            new NameValuePair("text", message) };
    postMethod.setRequestBody(data);

    try {
        int statusCode = client.executeMethod(postMethod);

        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            return true;
        }

        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: {}", postMethod.getStatusLine());
            return false;
        }

        InputStream tmpResponseStream = postMethod.getResponseBodyAsStream();
        Header encodingHeader = postMethod.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.debug("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.debug("Deflated InputStream from {}", url);
                }
            }
        }

        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }

    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
    } finally {
        postMethod.releaseConnection();
    }

    return true;
}