Search in sources :

Example 16 with PostMethod

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

the class SchemaUtils method postSchema.

/**
   * Given host, port and schema, send a http POST request to upload the {@link Schema}.
   *
   * @return <code>true</code> on success.
   * <P><code>false</code> on failure.
   */
public static boolean postSchema(@Nonnull String host, int port, @Nonnull Schema schema) {
    Preconditions.checkNotNull(host);
    Preconditions.checkNotNull(schema);
    try {
        URL url = new URL("http", host, port, "/schemas");
        PostMethod httpPost = new PostMethod(url.toString());
        try {
            Part[] parts = { new StringPart(schema.getSchemaName(), schema.toString()) };
            MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());
            httpPost.setRequestEntity(requestEntity);
            int responseCode = HTTP_CLIENT.executeMethod(httpPost);
            if (responseCode >= 400) {
                String response = httpPost.getResponseBodyAsString();
                LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
                return false;
            }
            return true;
        } finally {
            httpPost.releaseConnection();
        }
    } catch (Exception e) {
        LOGGER.error("Caught exception while posting the schema: {} to host: {}, port: {}", schema.getSchemaName(), host, port, e);
        return false;
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) Part(org.apache.commons.httpclient.methods.multipart.Part) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) URL(java.net.URL) IOException(java.io.IOException)

Example 17 with PostMethod

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

the class FileUploadUtils method sendSegmentJsonImpl.

public static int sendSegmentJsonImpl(final String host, final String port, final JSONObject segmentJson) {
    PostMethod postMethod = null;
    try {
        RequestEntity requestEntity = new StringRequestEntity(segmentJson.toString(), ContentType.APPLICATION_JSON.getMimeType(), ContentType.APPLICATION_JSON.getCharset().name());
        postMethod = new PostMethod("http://" + host + ":" + port + "/" + SEGMENTS_PATH);
        postMethod.setRequestEntity(requestEntity);
        postMethod.setRequestHeader(UPLOAD_TYPE, FileUploadType.JSON.toString());
        int statusCode = FILE_UPLOAD_HTTP_CLIENT.executeMethod(postMethod);
        if (statusCode >= 400) {
            String errorString = "POST Status Code: " + statusCode + "\n";
            if (postMethod.getResponseHeader("Error") != null) {
                errorString += "ServletException: " + postMethod.getResponseHeader("Error").getValue();
            }
            throw new HttpException(errorString);
        }
        return statusCode;
    } catch (Exception e) {
        LOGGER.error("Caught exception while sending json: {}", segmentJson.toString(), e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpException(org.apache.commons.httpclient.HttpException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 18 with PostMethod

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

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

use of org.apache.commons.httpclient.methods.PostMethod in project camel by apache.

the class NettyHttpMethodRestrictTest method testProperHttpMethod.

@Test
public void testProperHttpMethod() throws Exception {
    HttpClient httpClient = new HttpClient();
    PostMethod httpPost = new PostMethod(getUrl());
    StringRequestEntity reqEntity = new StringRequestEntity("This is a test", null, null);
    httpPost.setRequestEntity(reqEntity);
    int status = httpClient.executeMethod(httpPost);
    assertEquals("Get a wrong response status", 200, status);
    String result = httpPost.getResponseBodyAsString();
    assertEquals("Get a wrong result", "This is a test response", result);
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) Test(org.junit.Test)

Aggregations

PostMethod (org.apache.commons.httpclient.methods.PostMethod)203 HttpClient (org.apache.commons.httpclient.HttpClient)114 Test (org.junit.Test)55 IOException (java.io.IOException)32 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)28 Part (org.apache.commons.httpclient.methods.multipart.Part)25 NameValuePair (org.apache.commons.httpclient.NameValuePair)24 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)23 Map (java.util.Map)21 GetMethod (org.apache.commons.httpclient.methods.GetMethod)21 StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)21 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)21 HttpMethod (org.apache.commons.httpclient.HttpMethod)17 Header (org.apache.commons.httpclient.Header)16 Note (org.apache.zeppelin.notebook.Note)13 HttpException (org.apache.commons.httpclient.HttpException)12 File (java.io.File)11 InputStream (java.io.InputStream)11 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)11 JSONParser (org.json.simple.parser.JSONParser)11