use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity 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;
}
use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project fabric8 by jboss-fuse.
the class ProxyServlet method handleMultipartPost.
/**
* Sets up the given {@link EntityEnclosingMethod} to send the same multipart
* data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
*
* @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
* configuring to send a multipart request
* @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains
* the mutlipart data to be sent via the {@link EntityEnclosingMethod}
*/
private void handleMultipartPost(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest) throws ServletException {
// Create a factory for disk-based file items
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// Set factory constraints
diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
// Create a new file upload handler
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// Parse the request
try {
// Get the multipart items as a list
List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
// Create a list to hold all of the parts
List<Part> listParts = new ArrayList<Part>();
// Iterate the multipart items list
for (FileItem fileItemCurrent : listFileItems) {
// If the current item is a form field, then create a string part
if (fileItemCurrent.isFormField()) {
StringPart stringPart = new StringPart(// The field name
fileItemCurrent.getFieldName(), // The field value
fileItemCurrent.getString());
// Add the part to the list
listParts.add(stringPart);
} else {
// The item is a file upload, so we create a FilePart
FilePart filePart = new FilePart(// The field name
fileItemCurrent.getFieldName(), new ByteArrayPartSource(// The uploaded file name
fileItemCurrent.getName(), // The uploaded file contents
fileItemCurrent.get()));
// Add the part to the list
listParts.add(filePart);
}
}
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(listParts.toArray(new Part[] {}), entityEnclosingMethod.getParams());
entityEnclosingMethod.setRequestEntity(multipartRequestEntity);
// The current content-type header (received from the client) IS of
// type "multipart/form-data", but the content-type header also
// contains the chunk boundary string of the chunks. Currently, this
// header is using the boundary of the client request, since we
// blindly copied all headers from the client request to the proxy
// request. However, we are creating a new request with a new chunk
// boundary string, so it is necessary that we re-set the
// content-type string to reflect the new chunk boundary string
entityEnclosingMethod.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType());
} catch (FileUploadException fileUploadException) {
throw new ServletException(fileUploadException);
}
}
use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project fabric8 by jboss-fuse.
the class MavenProxyServletSupportTest method testUploadWithMimeMultipartFormData.
@Test
public void testUploadWithMimeMultipartFormData() throws Exception {
new File("target/maven/proxy/tmp/multipart").mkdirs();
System.setProperty("karaf.data", new File("target").getCanonicalPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jas = new JarOutputStream(baos);
addEntry(jas, "META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n".getBytes());
addEntry(jas, "META-INF/maven/io.fabric8/mybundle/pom.properties", "groupId=io.fabric8\nartifactId=mybundle\nversion=1.0\n".getBytes());
jas.close();
byte[] jarBytes = baos.toByteArray();
RuntimeProperties props = new MockRuntimeProperties();
MavenResolver resolver = EasyMock.createMock(MavenResolver.class);
MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer, new File("target/upload"), 0);
servlet.setFileItemFactory(new DiskFileItemFactory(0, new File("target/maven/proxy/tmp/multipart")));
HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
FilePart part = new FilePart("file[]", new ByteArrayPartSource("mybundle-1.0.jar", jarBytes));
MultipartRequestEntity entity = new MultipartRequestEntity(new Part[] { part }, new HttpMethodParams());
final ByteArrayOutputStream requestBytes = new ByteArrayOutputStream();
entity.writeRequest(requestBytes);
final byte[] multipartRequestBytes = requestBytes.toByteArray();
EasyMock.expect(request.getPathInfo()).andReturn("/mybundle-1.0.jar");
EasyMock.expect(request.getHeader(MavenProxyServletSupport.LOCATION_HEADER)).andReturn(null);
EasyMock.expect(request.getParameter("profile")).andReturn("my");
EasyMock.expect(request.getParameter("version")).andReturn("1.0");
EasyMock.expect(request.getContentType()).andReturn(entity.getContentType()).anyTimes();
EasyMock.expect(request.getHeader("Content-length")).andReturn(Long.toString(entity.getContentLength())).anyTimes();
EasyMock.expect(request.getContentLength()).andReturn((int) entity.getContentLength()).anyTimes();
EasyMock.expect(request.getCharacterEncoding()).andReturn("ISO-8859-1").anyTimes();
Capture<String> location = EasyMock.newCapture(CaptureType.ALL);
response.setStatus(HttpServletResponse.SC_ACCEPTED);
EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {
private int pos = 0;
@Override
public int read() throws IOException {
return pos >= multipartRequestBytes.length ? -1 : (multipartRequestBytes[pos++] & 0xFF);
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
}
});
Capture<ProjectRequirements> requirementsCapture = EasyMock.newCapture(CaptureType.FIRST);
EasyMock.expect(projectDeployer.deployProject(EasyMock.capture(requirementsCapture), EasyMock.eq(true))).andReturn(null);
EasyMock.replay(resolver, request, response, projectDeployer);
servlet.doPut(request, response);
FileInputStream fis = new FileInputStream("target/upload/io.fabric8/mybundle/1.0/mybundle-1.0.jar");
ByteArrayOutputStream storedBundleBytes = new ByteArrayOutputStream();
IOUtils.copy(fis, storedBundleBytes);
fis.close();
Assert.assertArrayEquals(jarBytes, storedBundleBytes.toByteArray());
ProjectRequirements pr = requirementsCapture.getValue();
List<String> bundles = pr.getBundles();
assertThat(bundles.size(), equalTo(1));
assertThat(bundles.get(0), equalTo("mvn:io.fabric8/mybundle/1.0"));
assertThat(pr.getProfileId(), equalTo("my"));
assertThat(pr.getVersion(), equalTo("1.0"));
assertThat(pr.getGroupId(), nullValue());
assertThat(pr.getArtifactId(), nullValue());
EasyMock.verify(resolver, request, response, projectDeployer);
}
use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project ecf by eclipse.
the class TestMultipartPost method testPostFilePartUnknownLength.
public void testPostFilePartUnknownLength() throws Exception {
this.server.setHttpService(new EchoService());
String enc = "ISO-8859-1";
PostMethod method = new PostMethod();
byte[] content = "Hello".getBytes(enc);
MultipartRequestEntity entity = new MultipartRequestEntity(new Part[] { new FilePart("param1", new TestPartSource("filename.txt", content), "text/plain", enc) }, 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=" + enc) >= 0);
assertTrue(body.indexOf("Content-Transfer-Encoding: binary") >= 0);
assertTrue(body.indexOf("Hello") >= 0);
}
use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project ecf by eclipse.
the class MultipartRequest method execute.
/**
* TODO: make sure we are using the MultipartRequestEntity in the correct
* manner. The deprecated MultipartPostMethod was very different.
* @throws IOException
*/
@Override
public void execute() throws IOException {
((PostMethod) method).setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), method.getParams()));
super.execute();
}
Aggregations