Search in sources :

Example 1 with ByteArrayPartSource

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

use of org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource in project xwiki-platform by xwiki.

the class AttachmentsResourceTest method testPOSTAttachment.

@Test
public void testPOSTAttachment() throws Exception {
    final String attachmentName = String.format("%s.txt", UUID.randomUUID());
    final String content = "ATTACHMENT CONTENT";
    String attachmentsUri = buildURIForThisPage(AttachmentsResource.class, attachmentName);
    HttpClient httpClient = new HttpClient();
    httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(TestUtils.SUPER_ADMIN_CREDENTIALS.getUserName(), TestUtils.SUPER_ADMIN_CREDENTIALS.getPassword()));
    httpClient.getParams().setAuthenticationPreemptive(true);
    Part[] parts = new Part[1];
    ByteArrayPartSource baps = new ByteArrayPartSource(attachmentName, content.getBytes());
    parts[0] = new FilePart(attachmentName, baps);
    PostMethod postMethod = new PostMethod(attachmentsUri);
    MultipartRequestEntity mpre = new MultipartRequestEntity(parts, postMethod.getParams());
    postMethod.setRequestEntity(mpre);
    httpClient.executeMethod(postMethod);
    Assert.assertEquals(getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode());
    this.unmarshaller.unmarshal(postMethod.getResponseBodyAsStream());
    Header location = postMethod.getResponseHeader("location");
    GetMethod getMethod = executeGet(location.getValue());
    Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());
    Assert.assertEquals(content, getMethod.getResponseBodyAsString());
}
Also used : Header(org.apache.commons.httpclient.Header) PostMethod(org.apache.commons.httpclient.methods.PostMethod) 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) 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) AbstractHttpTest(org.xwiki.test.rest.framework.AbstractHttpTest) Test(org.junit.Test)

Example 3 with ByteArrayPartSource

use of org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource in project ecf by eclipse.

the class TestMultipartPost method testPostFilePart.

/**
 * Test that the body consisting of a file part can be posted.
 */
public void testPostFilePart() throws Exception {
    this.server.setHttpService(new EchoService());
    PostMethod method = new PostMethod();
    byte[] content = "Hello".getBytes();
    MultipartRequestEntity entity = new MultipartRequestEntity(new Part[] { new FilePart("param1", new ByteArrayPartSource("filename.txt", content), "text/plain", "ISO-8859-1") }, method.getParams());
    method.setRequestEntity(entity);
    client.executeMethod(method);
    assertEquals(200, method.getStatusCode());
    String body = method.getResponseBodyAsString();
    assertTrue(body.indexOf("Content-Disposition: form-data; name=\"param1\"; filename=\"filename.txt\"") >= 0);
    assertTrue(body.indexOf("Content-Type: text/plain; charset=ISO-8859-1") >= 0);
    assertTrue(body.indexOf("Content-Transfer-Encoding: binary") >= 0);
    assertTrue(body.indexOf("Hello") >= 0);
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)

Example 4 with ByteArrayPartSource

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

the class HttpOsgiClient method installBundle.

@Override
public void installBundle(InputStream in, String fileName) throws OsgiClientException {
    if (in == null) {
        throw new IllegalArgumentException("in may not be null");
    }
    if (fileName == null) {
        throw new IllegalArgumentException("fileName may not be null");
    }
    // append pseudo path after root URL to not get redirected for nothing
    final PostMethod filePost = new PostMethod(repositoryInfo.appendPath("system/console/install"));
    try {
        // set referrer
        filePost.setRequestHeader("referer", "about:blank");
        List<Part> partList = new ArrayList<>();
        partList.add(new StringPart("action", "install"));
        partList.add(new StringPart("_noredir_", "_noredir_"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(in, baos);
        PartSource partSource = new ByteArrayPartSource(fileName, baos.toByteArray());
        partList.add(new FilePart("bundlefile", partSource));
        partList.add(new StringPart("bundlestart", "start"));
        Part[] parts = partList.toArray(new Part[partList.size()]);
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        int status = getHttpClient().executeMethod(filePost);
        if (status != 200) {
            throw new OsgiClientException("Method execution returned status " + status);
        }
    } catch (IOException e) {
        throw new OsgiClientException(e);
    } finally {
        filePost.releaseConnection();
    }
}
Also used : ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) PartSource(org.apache.commons.httpclient.methods.multipart.PartSource) PostMethod(org.apache.commons.httpclient.methods.PostMethod) ArrayList(java.util.ArrayList) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) OsgiClientException(org.apache.sling.ide.osgi.OsgiClientException)

Example 5 with ByteArrayPartSource

use of org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource in project xwiki-platform by xwiki.

the class StoreTestUtils method doUpload.

public static HttpMethod doUpload(final String address, final UsernamePasswordCredentials userNameAndPassword, final Map<String, byte[]> uploads) throws IOException {
    final HttpClient client = new HttpClient();
    final PostMethod method = new PostMethod(address);
    if (userNameAndPassword != null) {
        client.getState().setCredentials(AuthScope.ANY, userNameAndPassword);
        client.getParams().setAuthenticationPreemptive(true);
    }
    Part[] parts = new Part[uploads.size()];
    int i = 0;
    for (Map.Entry<String, byte[]> e : uploads.entrySet()) {
        parts[i++] = new FilePart("filepath", new ByteArrayPartSource(e.getKey(), e.getValue()));
    }
    MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams());
    method.setRequestEntity(entity);
    client.executeMethod(method);
    return method;
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) Map(java.util.Map) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)

Aggregations

ByteArrayPartSource (org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)7 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)7 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)7 PostMethod (org.apache.commons.httpclient.methods.PostMethod)5 Part (org.apache.commons.httpclient.methods.multipart.Part)5 IOException (java.io.IOException)3 HttpClient (org.apache.commons.httpclient.HttpClient)3 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 ArrayList (java.util.ArrayList)2 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)2 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)2 GetMethod (org.apache.commons.httpclient.methods.GetMethod)2 RuntimeProperties (io.fabric8.api.RuntimeProperties)1 AbstractRuntimeProperties (io.fabric8.api.scr.AbstractRuntimeProperties)1 ProjectRequirements (io.fabric8.deployer.dto.ProjectRequirements)1 MavenResolver (io.fabric8.maven.MavenResolver)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1