Search in sources :

Example 1 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project openhab1-addons by openhab.

the class KM200Comm method sendDataToService.

/**
     * This function does the SEND http communication to the device
     *
     */
public Integer sendDataToService(String service, byte[] data) {
    // Create an instance of HttpClient.
    Integer rCode = null;
    if (client == null) {
        client = new HttpClient();
    }
    synchronized (client) {
        // Create a method instance.
        PostMethod method = new PostMethod("http://" + device.getIP4Address() + service);
        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        // Set the right header
        method.setRequestHeader("Accept", "application/json");
        method.addRequestHeader("User-Agent", "TeleHeater/2.2.3");
        method.setRequestEntity(new ByteArrayRequestEntity(data));
        try {
            rCode = client.executeMethod(method);
        } catch (Exception e) {
            logger.error("Failed to send data {}", e);
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        return rCode;
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) JSONException(org.json.JSONException) GeneralSecurityException(java.security.GeneralSecurityException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 2 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project zm-mailbox by Zimbra.

the class SoapHttpTransport method invoke.

public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, ResponseHandler respHandler) throws IOException, HttpException, ServiceException {
    PostMethod method = null;
    try {
        // Assemble post method.  Append document name, so that the request
        // type is written to the access log.
        String uri, query;
        int i = mUri.indexOf('?');
        if (i >= 0) {
            uri = mUri.substring(0, i);
            query = mUri.substring(i);
        } else {
            uri = mUri;
            query = "";
        }
        if (!uri.endsWith("/"))
            uri += '/';
        uri += getDocumentName(document);
        method = new PostMethod(uri + query);
        // Set user agent if it's specified.
        String agentName = getUserAgentName();
        if (agentName != null) {
            String agentVersion = getUserAgentVersion();
            if (agentVersion != null)
                agentName += " " + agentVersion;
            method.setRequestHeader(new Header("User-Agent", agentName));
        }
        // the content-type charset will determine encoding used
        // when we set the request body
        method.setRequestHeader("Content-Type", getRequestProtocol().getContentType());
        if (getClientIp() != null) {
            method.setRequestHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            if (ZimbraLog.misc.isDebugEnabled()) {
                ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            }
        }
        Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType);
        String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
        HttpMethodParams params = method.getParams();
        method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8"));
        if (getRequestProtocol().hasSOAPActionHeader())
            method.setRequestHeader("SOAPAction", mUri);
        if (mCustomHeaders != null) {
            for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.setRequestHeader(entry.getKey(), entry.getValue());
        }
        String host = method.getURI().getHost();
        HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin());
        String trustedToken = getTrustedToken();
        if (trustedToken != null) {
            state.addCookie(new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false));
        }
        params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES : CookiePolicy.BROWSER_COMPATIBILITY);
        params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(mRetryCount - 1, true));
        params.setSoTimeout(mTimeout);
        params.setVersion(HttpVersion.HTTP_1_1);
        method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");
        if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
            state.setProxyCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword()));
        }
        if (mHttpDebugListener != null) {
            mHttpDebugListener.sendSoapMessage(method, soapReq, state);
        }
        int responseCode = mClient.executeMethod(mHostConfig, method, state);
        //   real server issues will probably be "503" or "404"
        if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
            throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), uri);
        // Read the response body.  Use the stream API instead of the byte[]
        // version to avoid HTTPClient whining about a large response.
        InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream(), SoapProtocol.getCharset());
        String responseStr = "";
        try {
            if (respHandler != null) {
                respHandler.process(reader);
                return null;
            } else {
                responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), false);
                Element soapResp = parseSoapResponse(responseStr, raw);
                if (mHttpDebugListener != null) {
                    mHttpDebugListener.receiveSoapMessage(method, soapResp);
                }
                return soapResp;
            }
        } catch (SoapFaultException x) {
            // attach request/response to the exception and rethrow
            x.setFaultRequest(soapMessage);
            x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
            throw x;
        }
    } finally {
        // Release the connection to the connection manager
        if (method != null)
            method.releaseConnection();
        // exits.  Leave it here anyway.
        if (!mKeepAlive)
            mClient.getHttpConnectionManager().closeIdleConnections(0);
    }
}
Also used : ZimbraCookie(com.zimbra.common.util.ZimbraCookie) Cookie(org.apache.commons.httpclient.Cookie) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamReader(java.io.InputStreamReader) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Header(org.apache.commons.httpclient.Header) AuthScope(org.apache.commons.httpclient.auth.AuthScope) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project opennms by OpenNMS.

the class GoogleGeocoderService method ensureInitialized.

public void ensureInitialized() throws GeocoderException {
    if (m_geocoder == null) {
        final HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
        if (notEmpty(m_clientId) && notEmpty(m_clientKey)) {
            try {
                LOG.info("Initializing Google Geocoder using Client ID and Key.");
                m_geocoder = new AdvancedGeoCoder(httpClient, m_clientId, m_clientKey);
            } catch (final InvalidKeyException e) {
                throw new GeocoderException("Unable to initialize Google Geocoder.", e);
            }
        }
        if (m_geocoder == null) {
            LOG.info("Initializing Google Geocoder using default configuration.");
            m_geocoder = new AdvancedGeoCoder(httpClient);
        }
        /* Configure proxying, if necessary... */
        final String httpProxyHost = System.getProperty("http.proxyHost");
        final Integer httpProxyPort = Integer.getInteger("http.proxyPort");
        if (httpProxyHost != null && httpProxyPort != null) {
            LOG.info("Proxy configuration found, using {}:{} as HTTP proxy.", httpProxyHost, httpProxyPort);
            httpClient.getHostConfiguration().setProxy(httpProxyHost, httpProxyPort);
        } else {
            LOG.info("No proxy configuration found.");
        }
        /* Limit retries... */
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, true));
        httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, timeout);
        LOG.info("Google Geocoder initialized.");
    }
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) AdvancedGeoCoder(com.google.code.geocoder.AdvancedGeoCoder) MultiThreadedHttpConnectionManager(org.apache.commons.httpclient.MultiThreadedHttpConnectionManager) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) InvalidKeyException(java.security.InvalidKeyException) GeocoderException(org.opennms.features.geocoder.GeocoderException) TemporaryGeocoderException(org.opennms.features.geocoder.TemporaryGeocoderException)

Example 4 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project openhab1-addons by openhab.

the class Telegram method sendTelegramPhoto.

@ActionDoc(text = "Sends a Picture, protected by username/password authentication, via Telegram REST API")
public static boolean sendTelegramPhoto(@ParamDoc(name = "group") String group, @ParamDoc(name = "photoURL") String photoURL, @ParamDoc(name = "caption") String caption, @ParamDoc(name = "username") String username, @ParamDoc(name = "password") String password) {
    if (groupTokens.get(group) == null) {
        logger.error("Bot '{}' not defined, action skipped", group);
        return false;
    }
    if (photoURL == null) {
        logger.error("photoURL not defined, action skipped");
        return false;
    }
    // load image from url
    byte[] imageFromURL;
    HttpClient getClient = new HttpClient();
    if (username != null && password != null) {
        getClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        getClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
    }
    GetMethod getMethod = new GetMethod(photoURL);
    getMethod.getParams().setSoTimeout(HTTP_PHOTO_TIMEOUT);
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    try {
        int statusCode = getClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: {}", getMethod.getStatusLine());
            return false;
        }
        imageFromURL = getMethod.getResponseBody();
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        getMethod.releaseConnection();
    }
    // parse image type
    String imageType;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(imageFromURL));
        Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
        if (!imageReaders.hasNext()) {
            logger.error("photoURL does not represent a known image type");
            return false;
        }
        ImageReader reader = imageReaders.next();
        imageType = reader.getFormatName();
    } catch (IOException e) {
        logger.error("cannot parse photoURL as image: {}", e.getMessage());
        return false;
    }
    // post photo to telegram
    String url = String.format(TELEGRAM_PHOTO_URL, groupTokens.get(group).getToken());
    PostMethod postMethod = new PostMethod(url);
    try {
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setSoTimeout(HTTP_PHOTO_TIMEOUT);
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        Part[] parts = new Part[caption != null ? 3 : 2];
        parts[0] = new StringPart("chat_id", groupTokens.get(group).getChatId());
        parts[1] = new FilePart("photo", new ByteArrayPartSource(String.format("image.%s", imageType), imageFromURL));
        if (caption != null) {
            parts[2] = new StringPart("caption", caption, "UTF-8");
        }
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        HttpClient client = new HttpClient();
        int statusCode = client.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            return true;
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: {}", postMethod.getStatusLine());
            return false;
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        postMethod.releaseConnection();
    }
    return true;
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) ImageInputStream(javax.imageio.stream.ImageInputStream) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) IOException(java.io.IOException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) ByteArrayInputStream(java.io.ByteArrayInputStream) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) ImageReader(javax.imageio.ImageReader) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 5 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project openhab1-addons by openhab.

the class FrontierSiliconRadioConnection method doLogin.

/**
     * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for
     * future requests.
     * 
     * @return <code>true</code> if login was successful; <code>false</code> otherwise.
     */
public boolean doLogin() {
    // reset login flag
    isLoggedIn = false;
    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.warn("Method failed: " + method.getStatusLine());
        }
        final String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.trace("login response: " + responseBody);
        }
        try {
            final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
            if (result.isStatusOk()) {
                logger.trace("login successful");
                sessionId = result.getSessionId();
                isLoggedIn = true;
                // login successful :-)
                return true;
            }
        } catch (Exception e) {
            logger.error("Parsing response failed");
        }
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }
    // login not successful
    return false;
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Aggregations

DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)25 HttpClient (org.apache.commons.httpclient.HttpClient)20 IOException (java.io.IOException)16 HttpException (org.apache.commons.httpclient.HttpException)12 GetMethod (org.apache.commons.httpclient.methods.GetMethod)10 PostMethod (org.apache.commons.httpclient.methods.PostMethod)7 Header (org.apache.commons.httpclient.Header)6 HttpMethod (org.apache.commons.httpclient.HttpMethod)6 NameValuePair (org.apache.commons.httpclient.NameValuePair)5 ByteArrayInputStream (java.io.ByteArrayInputStream)3 InputStream (java.io.InputStream)3 GeneralSecurityException (java.security.GeneralSecurityException)3 GZIPInputStream (java.util.zip.GZIPInputStream)3 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)3 PluginTestVerifier (com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier)2 EngineUnavailableException (it.eng.spagobi.engines.talend.client.exception.EngineUnavailableException)2 ServiceInvocationFailedException (it.eng.spagobi.engines.talend.client.exception.ServiceInvocationFailedException)2 FileNotFoundException (java.io.FileNotFoundException)2 InflaterInputStream (java.util.zip.InflaterInputStream)2 ImageInputStream (javax.imageio.stream.ImageInputStream)2