Search in sources :

Example 31 with GetMethod

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

the class SchemaUtils method getSchema.

/**
   * Given host, port and schema name, send a http GET request to download the {@link Schema}.
   *
   * @return schema on success.
   * <P><code>null</code> on failure.
   */
@Nullable
public static Schema getSchema(@Nonnull String host, int port, @Nonnull String schemaName) {
    Preconditions.checkNotNull(host);
    Preconditions.checkNotNull(schemaName);
    try {
        URL url = new URL("http", host, port, "/schemas/" + schemaName);
        GetMethod httpGet = new GetMethod(url.toString());
        try {
            int responseCode = HTTP_CLIENT.executeMethod(httpGet);
            String response = httpGet.getResponseBodyAsString();
            if (responseCode >= 400) {
                // File not find error code.
                if (responseCode == 404) {
                    LOGGER.info("Cannot find schema: {} from host: {}, port: {}", schemaName, host, port);
                } else {
                    LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
                }
                return null;
            }
            return Schema.fromString(response);
        } finally {
            httpGet.releaseConnection();
        }
    } catch (Exception e) {
        LOGGER.error("Caught exception while getting the schema: {} from host: {}, port: {}", schemaName, host, port, e);
        return null;
    }
}
Also used : GetMethod(org.apache.commons.httpclient.methods.GetMethod) URL(java.net.URL) IOException(java.io.IOException) Nullable(javax.annotation.Nullable)

Example 32 with GetMethod

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

the class MultiGetRequestTest method testMultiGet.

@Test
public void testMultiGet() {
    MultiGetRequest mget = new MultiGetRequest(Executors.newCachedThreadPool(), new MultiThreadedHttpConnectionManager());
    List<String> urls = Arrays.asList("http://localhost:" + String.valueOf(portStart) + URI_PATH, "http://localhost:" + String.valueOf(portStart + 1) + URI_PATH, "http://localhost:" + String.valueOf(portStart + 2) + URI_PATH, // 2nd request to the same server
    "http://localhost:" + String.valueOf(portStart) + URI_PATH);
    // timeout value needs to be less than 5000ms set above for
    // third server
    final int requestTimeoutMs = 1000;
    CompletionService<GetMethod> completionService = mget.execute(urls, requestTimeoutMs);
    int success = 0;
    int errors = 0;
    int timeouts = 0;
    for (int i = 0; i < urls.size(); i++) {
        GetMethod getMethod = null;
        try {
            getMethod = completionService.take().get();
            if (getMethod.getStatusCode() >= 300) {
                ++errors;
                Assert.assertEquals(getMethod.getResponseBodyAsString(), ERROR_MSG);
            } else {
                ++success;
                Assert.assertEquals(getMethod.getResponseBodyAsString(), SUCCESS_MSG);
            }
        } catch (InterruptedException e) {
            LOGGER.error("Interrupted", e);
            ++errors;
        } catch (ExecutionException e) {
            if (Throwables.getRootCause(e) instanceof SocketTimeoutException) {
                LOGGER.debug("Timeout");
                ++timeouts;
            } else {
                LOGGER.error("Error", e);
                ++errors;
            }
        } catch (IOException e) {
            ++errors;
        }
    }
    Assert.assertEquals(2, success);
    Assert.assertEquals(1, errors);
    Assert.assertEquals(1, timeouts);
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) MultiThreadedHttpConnectionManager(org.apache.commons.httpclient.MultiThreadedHttpConnectionManager) GetMethod(org.apache.commons.httpclient.methods.GetMethod) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 33 with GetMethod

use of org.apache.commons.httpclient.methods.GetMethod 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 34 with GetMethod

use of org.apache.commons.httpclient.methods.GetMethod 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 35 with GetMethod

use of org.apache.commons.httpclient.methods.GetMethod 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

GetMethod (org.apache.commons.httpclient.methods.GetMethod)357 HttpClient (org.apache.commons.httpclient.HttpClient)216 HttpMethod (org.apache.commons.httpclient.HttpMethod)93 IOException (java.io.IOException)82 Test (org.junit.Test)70 InputStream (java.io.InputStream)65 HttpException (org.apache.commons.httpclient.HttpException)41 Map (java.util.Map)39 ArrayList (java.util.ArrayList)37 HashMap (java.util.HashMap)36 JSONParser (org.json.simple.parser.JSONParser)34 JSONObject (org.json.simple.JSONObject)31 Header (org.apache.commons.httpclient.Header)22 Element (org.w3c.dom.Element)22 PostMethod (org.apache.commons.httpclient.methods.PostMethod)21 TypeToken (com.google.gson.reflect.TypeToken)20 List (java.util.List)19 HttpState (org.apache.commons.httpclient.HttpState)18 URI (java.net.URI)17 JSONArray (org.json.simple.JSONArray)17