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;
}
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());
}
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);
}
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();
}
}
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;
}
Aggregations