Search in sources :

Example 1 with StringPart

use of org.apache.commons.httpclient.methods.multipart.StringPart 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 2 with StringPart

use of org.apache.commons.httpclient.methods.multipart.StringPart 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 3 with StringPart

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

the class MultiPartFormTest method createMultipartRequestEntity.

private RequestEntity createMultipartRequestEntity() throws Exception {
    File file = new File("src/main/resources/META-INF/NOTICE.txt");
    Part[] parts = { new StringPart("comment", "A binary file of some kind"), new FilePart(file.getName(), file) };
    return new MultipartRequestEntity(parts, new HttpMethodParams());
}
Also used : StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) File(java.io.File) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart)

Example 4 with StringPart

use of org.apache.commons.httpclient.methods.multipart.StringPart in project zm-mailbox by Zimbra.

the class TestFileUpload method postAndVerify.

private String postAndVerify(ZMailbox mbox, URI uri, boolean clearCookies, String requestId, String attContent) throws IOException {
    HttpClient client = mbox.getHttpClient(uri);
    if (clearCookies) {
        client.getState().clearCookies();
    }
    List<Part> parts = new ArrayList<Part>();
    parts.add(new StringPart("requestId", requestId));
    if (attContent != null) {
        parts.add(mbox.createAttachmentPart("test.txt", attContent.getBytes()));
    }
    PostMethod post = new PostMethod(uri.toString());
    post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));
    int status = HttpClientUtil.executeMethod(client, post);
    Assert.assertEquals(200, status);
    String contentType = getHeaderValue(post, "Content-Type");
    Assert.assertTrue(contentType, contentType.startsWith("text/html"));
    String content = post.getResponseBodyAsString();
    post.releaseConnection();
    return content;
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) 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) ArrayList(java.util.ArrayList) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)

Example 5 with StringPart

use of org.apache.commons.httpclient.methods.multipart.StringPart in project sling by apache.

the class AbstractBundleDeployMojo method post.

private void post(String targetURL, File file) throws MojoExecutionException {
    PostMethod filePost = new PostMethod(targetURL);
    try {
        Part[] parts = { new FilePart(file.getName(), new FilePartSource(file.getName(), file)), new StringPart("_noredir_", "_noredir_") };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            getLog().info("Bundle deployed");
        } else {
            String msg = "Deployment failed, cause: " + HttpStatus.getStatusText(status);
            if (failOnError) {
                throw new MojoExecutionException(msg);
            } else {
                getLog().error(msg);
            }
        }
    } catch (Exception ex) {
        throw new MojoExecutionException("Deployment on " + targetURL + " failed, cause: " + ex.getMessage(), ex);
    } finally {
        filePost.releaseConnection();
    }
}
Also used : FilePartSource(org.apache.commons.httpclient.methods.multipart.FilePartSource) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) PostMethod(org.apache.commons.httpclient.methods.PostMethod) 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) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException)

Aggregations

MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)22 Part (org.apache.commons.httpclient.methods.multipart.Part)22 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)22 PostMethod (org.apache.commons.httpclient.methods.PostMethod)19 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)19 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 HttpClient (org.apache.commons.httpclient.HttpClient)7 File (java.io.File)6 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)4 Test (org.junit.Test)4 Map (java.util.Map)3 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)3 ByteArrayPartSource (org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)3 FilePartSource (org.apache.commons.httpclient.methods.multipart.FilePartSource)3 HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 RepositoryException (org.apache.sling.ide.transport.RepositoryException)2 PostParameter (weibo4j.model.PostParameter)2 WeiboException (weibo4j.model.WeiboException)2