下面列出了怎么用org.apache.commons.httpclient.methods.multipart.Part的API类实例代码及写法,或者点击链接到github查看源代码。
public PostRequest buildMultipartPostRequest(File file, String filename, String siteId, String containerId) throws IOException
{
Part[] parts =
{
new FilePart("filedata", file.getName(), file, "text/plain", null),
new StringPart("filename", filename),
new StringPart("description", "description"),
new StringPart("siteid", siteId),
new StringPart("containerid", containerId)
};
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());
ByteArrayOutputStream os = new ByteArrayOutputStream();
multipartRequestEntity.writeRequest(os);
PostRequest postReq = new PostRequest(UPLOAD_URL, os.toByteArray(), multipartRequestEntity.getContentType());
return postReq;
}
/**
* Adds a <tt>Content-Type</tt> request header.
*
* @param state current state of http requests
* @param conn the connection to use for I/O
*
* @throws IOException if an I/O (transport) error occurs. Some transport exceptions
* can be recovered from.
* @throws HttpException if a protocol exception occurs. Usually protocol exceptions
* cannot be recovered from.
*
* @since 3.0
*/
protected void addContentTypeRequestHeader(HttpState state,
HttpConnection conn)
throws IOException, HttpException {
LOG.trace("enter EntityEnclosingMethod.addContentTypeRequestHeader("
+ "HttpState, HttpConnection)");
if (!parameters.isEmpty()) {
StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
if (Part.getBoundary() != null) {
buffer.append("; boundary=");
buffer.append(Part.getBoundary());
}
setRequestHeader("Content-Type", buffer.toString());
}
}
@Test
public void testUploadFile() throws IOException, URISyntaxException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getNodeURI()).path("files").build();
// create single page
final URL fileUrl = RepositoryEntriesITCase.class.getResource("singlepage.html");
assertNotNull(fileUrl);
final File file = new File(fileUrl.toURI());
final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", file), new StringPart("filename", file.getName()) };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertEquals(code, 200);
final OlatNamedContainerImpl folder = BCCourseNode.getNodeFolderContainer((BCCourseNode) bcNode, course1.getCourseEnvironment());
final VFSItem item = folder.resolve(file.getName());
assertNotNull(item);
}
@Test
public void testUploadFile() throws IOException, URISyntaxException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getNodeURI()).path("files").build();
// create single page
final URL fileUrl = RepositoryEntriesITCase.class.getResource("singlepage.html");
assertNotNull(fileUrl);
final File file = new File(fileUrl.toURI());
final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", file), new StringPart("filename", file.getName()) };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertEquals(code, 200);
final OlatNamedContainerImpl folder = BCCourseNode.getNodeFolderContainer((BCCourseNode) bcNode, course1.getCourseEnvironment());
final VFSItem item = folder.resolve(file.getName());
assertNotNull(item);
}
private MockHttpServletRequest getMultipartRequest( ) throws Exception
{
MockHttpServletRequest request = new MockHttpServletRequest( );
byte [ ] fileContent = new byte [ ] {
1, 2, 3
};
Part [ ] parts = new Part [ ] {
new FilePart( "file1", new ByteArrayPartSource( "file1", fileContent ) )
};
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( parts, new PostMethod( ).getParams( ) );
// Serialize request body
ByteArrayOutputStream requestContent = new ByteArrayOutputStream( );
multipartRequestEntity.writeRequest( requestContent );
// Set request body to HTTP servlet request
request.setContent( requestContent.toByteArray( ) );
// Set content type to HTTP servlet request (important, includes Mime boundary string)
request.setContentType( multipartRequestEntity.getContentType( ) );
request.setMethod( "POST" );
return request;
}
/**
* <p>This creates a HttpMethod with the message as its payload and image attachment. The message should be a properly formatted JSON
* String (No validation is done on this).</p>
*
* <p>The message can be easily created using the {@link #getJsonPayload(Message)} method.</p>
*
* @param uri The full URI which we will post to
* @param message A properly formatted JSON message. UTF-8 is expected
* @param image A complete instance of ImageAttachment object
* @throws IOException
*/
public HttpMethod getJsonPostForMultipartRequestEntity(String uri, String message, ImageAttachment image) throws IOException {
PostMethod post = new PostMethod(uri);
StringPart bodyPart = new StringPart("json", message);
bodyPart.setContentType("application/json");
FilePart filePart= new FilePart("feedItemFileUpload", image.retrieveObjectFile());
filePart.setContentType(image.retrieveContentType());
Part[] parts = {
bodyPart,
filePart,
};
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
return post;
}
/**
* Imports a model from a JSON file.
*/
public static void importModel() throws Exception {
// Upload file to H2O
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(URL + "/Upload.json?key=" + JSON_FILE.getName());
Part[] parts = { new FilePart(JSON_FILE.getName(), JSON_FILE) };
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
if( 200 != client.executeMethod(post) )
throw new RuntimeException("Request failed: " + post.getStatusLine());
post.releaseConnection();
// Parse the key into a model
GetMethod get = new GetMethod(URL + "/2/ImportModel.json?" //
+ "destination_key=MyImportedNeuralNet&" //
+ "type=NeuralNetModel&" //
+ "json=" + JSON_FILE.getName());
if( 200 != client.executeMethod(get) )
throw new RuntimeException("Request failed: " + get.getStatusLine());
get.releaseConnection();
}
public String upload(String http, String tagName, File file, Map<String, String> dataMap) {
String body = null;
PostMethod filePost = new PostMethod(http);
try {
if (dataMap != null) {
// 通过以下方法可以模拟页面参数提交
// filePost.setParameter("name", "中文");
Iterator<Map.Entry<String, String>> i = dataMap.entrySet().iterator();
while (i.hasNext()) {
Map.Entry<String, String> entry = i.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
filePost.setParameter(inputName, inputValue);
}
}
Part[] parts = { new FilePart(file.getName(), file) };
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
body = filePost.getResponseBodyAsString();
if (status == HttpStatus.SC_OK) {// 上传成功
} else {// 上传失败
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection();
}
return body;
}
public PostRequest buildMultipartPostRequest(File file) throws IOException
{
Part[] parts = { new FilePart("filedata", file.getName(), file, "application/zip", null) };
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());
ByteArrayOutputStream os = new ByteArrayOutputStream();
multipartRequestEntity.writeRequest(os);
PostRequest postReq = new PostRequest(UPLOAD_URL, os.toByteArray(), multipartRequestEntity.getContentType());
return postReq;
}
private void addPartIfNotNull(List<Part> list, String partName, Object partValue)
{
if (partValue != null)
{
list.add(new StringPart(partName, partValue.toString()));
}
}
/**
* Adds a binary file part
*
* @param parameterName The name of the parameter
* @param parameterFile The name of the file.
* @throws FileNotFoundException If the file cannot be found.
*/
public void addParameter(String parameterName, File parameterFile)
throws FileNotFoundException {
LOG.trace("enter MultipartPostMethod.addParameter(String parameterName, "
+ "File parameterFile)");
Part param = new FilePart(parameterName, parameterFile);
parameters.add(param);
}
public void addFile(final int executionId, final String uid, final File file) throws Exception {
PostMethod method = new PostMethod(baseUri + "executions/" + executionId + "/details/" + uid + "/file/");
Part[] parts = new Part[] { new FilePart("file", file) };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int responseCode = client.executeMethod(method);
handleResponseCode(method, responseCode);
}
@Test
public void testImportCp() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("cp-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "cp-demo.zip"), new StringPart("resourcename", "CP demo"),
new StringPart("displayname", "CP demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("CP demo", re.getDisplayname());
}
@Test
public void testImportTest() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("qti-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "qti-demo.zip"), new StringPart("resourcename", "QTI demo"),
new StringPart("displayname", "QTI demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("QTI demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportQuestionnaire() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("questionnaire-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "questionnaire-demo.zip"), new StringPart("resourcename", "Questionnaire demo"),
new StringPart("displayname", "Questionnaire demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Questionnaire demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportWiki() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("wiki-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "wiki-demo.zip"), new StringPart("resourcename", "Wiki demo"),
new StringPart("displayname", "Wiki demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Wiki demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportBlog() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("blog-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "blog-demo.zip"), new StringPart("resourcename", "Blog demo"),
new StringPart("displayname", "Blog demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Blog demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testPortrait() throws IOException, URISyntaxException {
final URL portraitUrl = RepositoryEntriesITCase.class.getResource("portrait.jpg");
assertNotNull(portraitUrl);
final File portrait = new File(portraitUrl.toURI());
final HttpClient c = loginWithCookie("rest-one", "A6B7C8");
// upload portrait
final String request = "/users/" + id1.getKey() + "/portrait";
final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", portrait), new StringPart("filename", "portrait.jpg") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertEquals(code, 200);
method.releaseConnection();
// check if big and small portraits exist
final DisplayPortraitManager dps = DisplayPortraitManager.getInstance();
final File uploadDir = dps.getPortraitDir(id1);
assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_SMALL_FILENAME).exists());
assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_BIG_FILENAME).exists());
// check get portrait
final String getRequest = "/users/" + id1.getKey() + "/portrait";
final GetMethod getMethod = createGet(getRequest, MediaType.APPLICATION_OCTET_STREAM, true);
final int getCode = c.executeMethod(getMethod);
assertEquals(getCode, 200);
final InputStream in = getMethod.getResponseBodyAsStream();
int b = 0;
int count = 0;
while ((b = in.read()) > -1) {
count++;
}
assertEquals(-1, b);// up to end of file
assertTrue(count > 1000);// enough bytes
method.releaseConnection();
}
@Test
public void testImportCp() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("cp-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "cp-demo.zip"), new StringPart("resourcename", "CP demo"),
new StringPart("displayname", "CP demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("CP demo", re.getDisplayname());
}
@Test
public void testImportTest() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("qti-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "qti-demo.zip"), new StringPart("resourcename", "QTI demo"),
new StringPart("displayname", "QTI demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("QTI demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportQuestionnaire() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("questionnaire-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "questionnaire-demo.zip"), new StringPart("resourcename", "Questionnaire demo"),
new StringPart("displayname", "Questionnaire demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Questionnaire demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportWiki() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("wiki-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "wiki-demo.zip"), new StringPart("resourcename", "Wiki demo"),
new StringPart("displayname", "Wiki demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Wiki demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testImportBlog() throws HttpException, IOException, URISyntaxException {
final URL cpUrl = RepositoryEntriesITCase.class.getResource("blog-demo.zip");
assertNotNull(cpUrl);
final File cp = new File(cpUrl.toURI());
final HttpClient c = loginWithCookie("administrator", "olat");
final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "blog-demo.zip"), new StringPart("resourcename", "Blog demo"),
new StringPart("displayname", "Blog demo") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
assertNotNull(vo);
final Long key = vo.getKey();
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
assertNotNull(re);
assertNotNull(re.getOwnerGroup());
assertNotNull(re.getOlatResource());
assertEquals("Blog demo", re.getDisplayname());
log.info(re.getOlatResource().getResourceableTypeName());
}
@Test
public void testPortrait() throws IOException, URISyntaxException {
final URL portraitUrl = RepositoryEntriesITCase.class.getResource("portrait.jpg");
assertNotNull(portraitUrl);
final File portrait = new File(portraitUrl.toURI());
final HttpClient c = loginWithCookie("rest-one", "A6B7C8");
// upload portrait
final String request = "/users/" + id1.getKey() + "/portrait";
final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
final Part[] parts = { new FilePart("file", portrait), new StringPart("filename", "portrait.jpg") };
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
final int code = c.executeMethod(method);
assertEquals(code, 200);
method.releaseConnection();
// check if big and small portraits exist
final DisplayPortraitManager dps = DisplayPortraitManager.getInstance();
final File uploadDir = dps.getPortraitDir(id1);
assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_SMALL_FILENAME).exists());
assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_BIG_FILENAME).exists());
// check get portrait
final String getRequest = "/users/" + id1.getKey() + "/portrait";
final GetMethod getMethod = createGet(getRequest, MediaType.APPLICATION_OCTET_STREAM, true);
final int getCode = c.executeMethod(getMethod);
assertEquals(getCode, 200);
final InputStream in = getMethod.getResponseBodyAsStream();
int b = 0;
int count = 0;
while ((b = in.read()) > -1) {
count++;
}
assertEquals(-1, b);// up to end of file
assertTrue(count > 1000);// enough bytes
method.releaseConnection();
}
private static RequestEntity buildMultiPartEntity(final IContext context,
final IMendixObject source, Map<String, String> params)
throws IOException, CoreException {
// MWE: don't set contenttype to CONTENTTYPE_MULTIPART; this will be
// done by the request entity and add the boundaries
List<Part> parts = Lists.newArrayList();
// This object self could be a filedocument
if (Core.isSubClassOf(FileDocument.entityName, source.getType())) {
String partName = getFileDocumentFileName(context, source);
if (partName == null || partName.isEmpty())
throw new IllegalArgumentException("The filename of a System.FileDocument in a multipart request should reflect the part name and cannot be empty");
addFilePart(context, partName, source, parts);
}
// .. or one of its children could be a filedocument. This way multiple
// file parts, or specifically named file parts can be send
for (String name : getAssociationsReferingToFileDocs(source
.getMetaObject())) {
IMendixIdentifier subObject = (IMendixIdentifier) source.getValue(
context, name);
params.remove(Utils.getShortMemberName(name));
if (subObject != null) {
addFilePart(context, Utils.getShortMemberName(name),
Core.retrieveId(context, subObject), parts);
}
}
// serialize any other members as 'normal' key value pairs
for (Entry<String, String> e : params.entrySet()) {
parts.add(new StringPart(e.getKey(), e.getValue(),
RestServices.UTF8));
}
params.clear();
return new MultipartRequestEntity(parts.toArray(new Part[0]),
new HttpMethodParams());
}
private static void addFilePart(final IContext context, String partname,
final IMendixObject source, List<Part> parts) throws IOException {
ByteArrayPartSource p = new ByteArrayPartSource(
getFileDocumentFileName(context, source),
IOUtils.toByteArray(Core.getFileDocumentContent(context, source)));
parts.add(new FilePart(partname, p));
}
public static PostMethod sendMultipartPostRequest(String url, String body)
throws IOException {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
// our handlers ignore key...so we can put anything here
Part[] parts = {new StringPart("body", body)};
postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
httpClient.executeMethod(postMethod);
return postMethod;
}
public static PutMethod sendMultipartPutRequest(String url, String body)
throws IOException {
HttpClient httpClient = new HttpClient();
PutMethod putMethod = new PutMethod(url);
// our handlers ignore key...so we can put anything here
Part[] parts = {new StringPart("body", body)};
putMethod.setRequestEntity(new MultipartRequestEntity(parts, putMethod.getParams()));
httpClient.executeMethod(putMethod);
return putMethod;
}
/**
* 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.toSingleLineJsonString())};
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;
}
}
private static Part[] createSendPhotoRequestParts(TelegramBot bot, byte[] image, String imageType, String caption) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("chat_id", bot.getChatId()));
partList.add(new FilePart("photo", new ByteArrayPartSource(String.format("image.%s", imageType), image)));
if (StringUtils.isNotBlank(caption)) {
partList.add(new StringPart("caption", caption, "UTF-8"));
}
if (StringUtils.isNotBlank(bot.getParseMode())) {
partList.add(new StringPart("parse_mode", bot.getParseMode()));
}
return partList.toArray(new Part[0]);
}