Search in sources :

Example 21 with HttpClient

use of org.apache.commons.httpclient.HttpClient in project Openfire by igniterealtime.

the class FaviconServlet method init.

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    // Create a pool of HTTP connections to use to get the favicons
    client = new HttpClient(new MultiThreadedHttpConnectionManager());
    HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
    params.setConnectionTimeout(2000);
    params.setSoTimeout(2000);
    // Load the default favicon to use when no favicon was found of a remote host
    try {
        URL resource = config.getServletContext().getResource("/images/server_16x16.gif");
        defaultBytes = getImage(resource.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    // Initialize caches.
    missesCache = CacheFactory.createCache("Favicon Misses");
    hitsCache = CacheFactory.createCache("Favicon Hits");
}
Also used : MalformedURLException(java.net.MalformedURLException) HttpConnectionManagerParams(org.apache.commons.httpclient.params.HttpConnectionManagerParams) HttpClient(org.apache.commons.httpclient.HttpClient) MultiThreadedHttpConnectionManager(org.apache.commons.httpclient.MultiThreadedHttpConnectionManager) URL(java.net.URL)

Example 22 with HttpClient

use of org.apache.commons.httpclient.HttpClient in project Openfire by igniterealtime.

the class UpdateManager method downloadPlugin.

/**
     * Download and install latest version of plugin.
     *
     * @param url the URL of the latest version of the plugin.
     * @return true if the plugin was successfully downloaded and installed.
     */
public boolean downloadPlugin(String url) {
    boolean installed = false;
    // Download and install new version of plugin
    HttpClient httpClient = new HttpClient();
    // Check if a proxy should be used
    if (isUsingProxy()) {
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(getProxyHost(), getProxyPort());
        httpClient.setHostConfiguration(hc);
    }
    GetMethod getMethod = new GetMethod(url);
    //execute the method
    try {
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode == 200) {
            //get the resonse as an InputStream
            try (InputStream in = getMethod.getResponseBodyAsStream()) {
                String pluginFilename = url.substring(url.lastIndexOf("/") + 1);
                installed = XMPPServer.getInstance().getPluginManager().installPlugin(in, pluginFilename);
            }
            if (installed) {
                // Remove the plugin from the list of plugins to update
                for (Update update : pluginUpdates) {
                    if (update.getURL().equals(url)) {
                        update.setDownloaded(true);
                    }
                }
                // Save response in a file for later retrieval
                saveLatestServerInfo();
            }
        }
    } catch (IOException e) {
        Log.warn("Error downloading new plugin version", e);
    }
    return installed;
}
Also used : HostConfiguration(org.apache.commons.httpclient.HostConfiguration) InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) IOException(java.io.IOException)

Example 23 with HttpClient

use of org.apache.commons.httpclient.HttpClient in project pinot by linkedin.

the class ChangeTableState method execute.

@Override
public boolean execute() throws Exception {
    if (_controllerHost == null) {
        _controllerHost = NetUtil.getHostAddress();
    }
    String stateValue = _state.toLowerCase();
    if (!stateValue.equals("enable") && !stateValue.equals("disable") && !stateValue.equals("drop")) {
        throw new IllegalArgumentException("Invalid value for state: " + _state + "\n Value must be one of enable|disable|drop");
    }
    HttpClient httpClient = new HttpClient();
    HttpURL url = new HttpURL(_controllerHost, Integer.parseInt(_controllerPort), URI_TABLES_PATH + _tableName);
    url.setQuery("state", stateValue);
    GetMethod httpGet = new GetMethod(url.getEscapedURI());
    int status = httpClient.executeMethod(httpGet);
    if (status != 200) {
        throw new RuntimeException("Failed to change table state, error: " + httpGet.getResponseBodyAsString());
    }
    return true;
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpURL(org.apache.commons.httpclient.HttpURL)

Example 24 with HttpClient

use of org.apache.commons.httpclient.HttpClient in project pinpoint by naver.

the class HttpClientIT method test.

@Test
public void test() throws Exception {
    HttpClient client = new HttpClient();
    client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT);
    client.getParams().setSoTimeout(SO_TIMEOUT);
    GetMethod method = new GetMethod("http://google.com");
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    method.setQueryString(new NameValuePair[] { new NameValuePair("key2", "value2") });
    try {
        // Execute the method.
        client.executeMethod(method);
    } catch (Exception ignored) {
    } finally {
        method.releaseConnection();
    }
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) PluginTestVerifier(com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier) Test(org.junit.Test)

Example 25 with HttpClient

use of org.apache.commons.httpclient.HttpClient 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)

Aggregations

HttpClient (org.apache.commons.httpclient.HttpClient)389 GetMethod (org.apache.commons.httpclient.methods.GetMethod)217 PostMethod (org.apache.commons.httpclient.methods.PostMethod)115 HttpMethod (org.apache.commons.httpclient.HttpMethod)98 Test (org.junit.Test)86 IOException (java.io.IOException)79 InputStream (java.io.InputStream)65 JSONParser (org.json.simple.parser.JSONParser)44 HttpException (org.apache.commons.httpclient.HttpException)43 JSONObject (org.json.simple.JSONObject)40 Map (java.util.Map)32 ArrayList (java.util.ArrayList)27 HttpState (org.apache.commons.httpclient.HttpState)25 ZMailbox (com.zimbra.client.ZMailbox)23 Account (com.zimbra.cs.account.Account)22 HashMap (java.util.HashMap)22 ServiceException (com.zimbra.common.service.ServiceException)21 JSONArray (org.json.simple.JSONArray)21 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)20 Element (org.w3c.dom.Element)20