Search in sources :

Example 1 with FilePart

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

the class FileUploadUtils method sendFile.

public static int sendFile(final String host, final String port, final String path, final String fileName, final InputStream inputStream, final long lengthInBytes, SendFileMethod httpMethod) {
    EntityEnclosingMethod method = null;
    try {
        method = httpMethod.forUri("http://" + host + ":" + port + "/" + path);
        Part[] parts = { new FilePart(fileName, new PartSource() {

            @Override
            public long getLength() {
                return lengthInBytes;
            }

            @Override
            public String getFileName() {
                return fileName;
            }

            @Override
            public InputStream createInputStream() throws IOException {
                return new BufferedInputStream(inputStream);
            }
        }) };
        method.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
        FILE_UPLOAD_HTTP_CLIENT.executeMethod(method);
        if (method.getStatusCode() >= 400) {
            String errorString = "POST Status Code: " + method.getStatusCode() + "\n";
            if (method.getResponseHeader("Error") != null) {
                errorString += "ServletException: " + method.getResponseHeader("Error").getValue();
            }
            throw new HttpException(errorString);
        }
        return method.getStatusCode();
    } catch (Exception e) {
        LOGGER.error("Caught exception while sending file: {}", fileName, e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}
Also used : PartSource(org.apache.commons.httpclient.methods.multipart.PartSource) BufferedInputStream(java.io.BufferedInputStream) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) HttpException(org.apache.commons.httpclient.HttpException) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 2 with FilePart

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

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

use of org.apache.commons.httpclient.methods.multipart.FilePart in project tdi-studio-se by Talend.

the class SpagoBITalendEngineClient_0_5_0 method deployJob.

/*
     * (non-Javadoc)
     * 
     * @see
     * it.eng.spagobi.engines.talend.client.ISpagoBITalendEngineClient#deployJob(it.eng.spagobi.engines.talend.client
     * .JobDeploymentDescriptor, java.io.File)
     */
public boolean deployJob(JobDeploymentDescriptor jobDeploymentDescriptor, File executableJobFiles) throws EngineUnavailableException, AuthenticationFailedException, ServiceInvocationFailedException {
    HttpClient client;
    PostMethod method;
    File deploymentDescriptorFile;
    boolean result = false;
    client = new HttpClient();
    method = new PostMethod(getServiceUrl(JOB_UPLOAD_SERVICE));
    deploymentDescriptorFile = null;
    try {
        //$NON-NLS-1$ //$NON-NLS-2$
        deploymentDescriptorFile = File.createTempFile("deploymentDescriptor", ".xml");
        FileWriter writer = new FileWriter(deploymentDescriptorFile);
        writer.write(jobDeploymentDescriptor.toXml());
        writer.flush();
        writer.close();
        Part[] parts = { new FilePart(executableJobFiles.getName(), executableJobFiles), //$NON-NLS-1$
        new FilePart("deploymentDescriptor", deploymentDescriptorFile) };
        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(method);
        if (status == HttpStatus.SC_OK) {
            if (//$NON-NLS-1$
            method.getResponseBodyAsString().equalsIgnoreCase("OK"))
                result = true;
        } else {
            throw new ServiceInvocationFailedException(Messages.getString("SpagoBITalendEngineClient_0_5_0.serviceExcFailed") + JOB_UPLOAD_SERVICE, //$NON-NLS-1$
            method.getStatusLine().toString(), method.getResponseBodyAsString());
        }
    } catch (HttpException e) {
        //$NON-NLS-1$
        throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient_0_5_0.protocolViolation") + e.getMessage());
    } catch (IOException e) {
        //$NON-NLS-1$
        throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient_0_5_0.transportError") + e.getMessage());
    } finally {
        method.releaseConnection();
        if (deploymentDescriptorFile != null)
            deploymentDescriptorFile.delete();
    }
    return result;
}
Also used : ServiceInvocationFailedException(it.eng.spagobi.engines.talend.client.exception.ServiceInvocationFailedException) PostMethod(org.apache.commons.httpclient.methods.PostMethod) FileWriter(java.io.FileWriter) IOException(java.io.IOException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) EngineUnavailableException(it.eng.spagobi.engines.talend.client.exception.EngineUnavailableException) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) File(java.io.File)

Example 5 with FilePart

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

the class ZMailbox method createAttachmentPart.

/**
     * Creates an <tt>HttpClient FilePart</tt> from the given filename and content.
     */
public FilePart createAttachmentPart(String filename, byte[] content) {
    FilePart part = new FilePart(filename, new ByteArrayPartSource(filename, content));
    String contentType = URLConnection.getFileNameMap().getContentTypeFor(filename);
    part.setContentType(contentType);
    return part;
}
Also used : FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)

Aggregations

FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)27 Part (org.apache.commons.httpclient.methods.multipart.Part)25 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)23 PostMethod (org.apache.commons.httpclient.methods.PostMethod)20 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)18 HttpClient (org.apache.commons.httpclient.HttpClient)12 File (java.io.File)10 IOException (java.io.IOException)7 ByteArrayPartSource (org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)7 Test (org.junit.Test)6 ArrayList (java.util.ArrayList)5 HttpState (org.apache.commons.httpclient.HttpState)4 FilePartSource (org.apache.commons.httpclient.methods.multipart.FilePartSource)4 HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)4 ServiceException (com.zimbra.common.service.ServiceException)3 Element (com.zimbra.common.soap.Element)3 SoapHttpTransport (com.zimbra.common.soap.SoapHttpTransport)3 HeaderElement (org.apache.commons.httpclient.HeaderElement)3 HttpException (org.apache.commons.httpclient.HttpException)3 PartSource (org.apache.commons.httpclient.methods.multipart.PartSource)3