use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project jaggery by wso2.
the class XMLHttpRequestHostObject method send.
private void send(Context cx, Object obj) throws ScriptException {
final HttpMethodBase method;
if ("GET".equalsIgnoreCase(methodName)) {
method = new GetMethod(this.url);
} else if ("HEAD".equalsIgnoreCase(methodName)) {
method = new HeadMethod(this.url);
} else if ("POST".equalsIgnoreCase(methodName)) {
PostMethod post = new PostMethod(this.url);
if (obj instanceof FormDataHostObject) {
FormDataHostObject fd = ((FormDataHostObject) obj);
List<Part> parts = new ArrayList<Part>();
for (Map.Entry<String, String> entry : fd) {
parts.add(new StringPart(entry.getKey(), entry.getValue()));
}
post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));
} else {
String content = getRequestContent(obj);
if (content != null) {
post.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
}
}
method = post;
} else if ("PUT".equalsIgnoreCase(methodName)) {
PutMethod put = new PutMethod(this.url);
String content = getRequestContent(obj);
if (content != null) {
put.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
}
method = put;
} else if ("DELETE".equalsIgnoreCase(methodName)) {
method = new DeleteMethod(this.url);
} else if ("TRACE".equalsIgnoreCase(methodName)) {
method = new TraceMethod(this.url);
} else if ("OPTIONS".equalsIgnoreCase(methodName)) {
method = new OptionsMethod(this.url);
} else {
throw new ScriptException("Unknown HTTP method : " + methodName);
}
for (Header header : requestHeaders) {
method.addRequestHeader(header);
}
if (username != null) {
httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
}
this.method = method;
final XMLHttpRequestHostObject xhr = this;
if (async) {
updateReadyState(cx, xhr, LOADING);
final ContextFactory factory = cx.getFactory();
final ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(new Callable() {
public Object call() throws Exception {
Context ctx = RhinoEngine.enterContext(factory);
try {
executeRequest(ctx, xhr);
} catch (ScriptException e) {
log.error(e.getMessage(), e);
} finally {
es.shutdown();
RhinoEngine.exitContext();
}
return null;
}
});
} else {
executeRequest(cx, xhr);
}
}
use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project zm-mailbox by Zimbra.
the class ZMailbox method uploadAttachments.
/**
* Uploads HTTP post parts to <tt>FileUploadServlet</tt>.
* @return the attachment id
*/
public String uploadAttachments(Part[] parts, int msTimeout) throws ServiceException {
String aid = null;
URI uri = getUploadURI();
HttpClient client = getHttpClient(uri);
// make the post
PostMethod post = new PostMethod(uri.toString());
post.getParams().setSoTimeout(msTimeout);
int statusCode;
try {
if (mCsrfToken != null) {
post.setRequestHeader(Constants.CSRF_TOKEN, mCsrfToken);
}
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
statusCode = HttpClientUtil.executeMethod(client, post);
// parse the response
if (statusCode == HttpServletResponse.SC_OK) {
String response = post.getResponseBodyAsString();
aid = getAttachmentId(response);
} else if (statusCode == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE) {
throw ZClientException.UPLOAD_SIZE_LIMIT_EXCEEDED("upload size limit exceeded", null);
} else {
throw ZClientException.UPLOAD_FAILED("Attachment post failed, status=" + statusCode, null);
}
} catch (IOException e) {
throw ZClientException.IO_ERROR(e.getMessage(), e);
} finally {
post.releaseConnection();
}
return aid;
}
use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project zm-mailbox by Zimbra.
the class TestFileUpload method testAdminUploadWithCsrfInFormField.
@Test
public void testAdminUploadWithCsrfInFormField() throws Exception {
SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
req.setCsrfSupported(true);
Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
String authToken = authResp.getAuthToken();
String csrfToken = authResp.getCsrfToken();
int port = 7071;
try {
port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
} catch (ServiceException e) {
ZimbraLog.test.error("Unable to get admin SOAP port", e);
}
String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
PostMethod post = new PostMethod(Url);
FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes()));
Part csrfPart = new StringPart("csrfToken", csrfToken);
String contentType = "application/x-msdownload";
part.setContentType(contentType);
HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
HttpState state = new HttpState();
state.addCookie(new org.apache.commons.httpclient.Cookie("localhost", ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false));
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
client.setState(state);
post.setRequestEntity(new MultipartRequestEntity(new Part[] { part, csrfPart }, post.getParams()));
int statusCode = HttpClientUtil.executeMethod(client, post);
Assert.assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode);
String resp = post.getResponseBodyAsString();
Assert.assertNotNull("Response should not be empty", resp);
Assert.assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}
use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project sling by apache.
the class SlingIntegrationTestClient method uploadToFileNodes.
/** Upload multiple files to file node structures */
public void uploadToFileNodes(String url, File[] localFiles, String[] fieldNames, String[] typeHints) throws IOException {
List<Part> partsList = new ArrayList<Part>();
for (int i = 0; i < localFiles.length; i++) {
Part filePart = new FilePart(fieldNames[i], localFiles[i]);
partsList.add(filePart);
if (typeHints != null) {
Part typeHintPart = new StringPart(fieldNames[i] + "@TypeHint", typeHints[i]);
partsList.add(typeHintPart);
}
}
final Part[] parts = partsList.toArray(new Part[partsList.size()]);
final PostMethod post = new PostMethod(url);
post.setFollowRedirects(false);
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
final int expected = 200;
final int status = httpClient.executeMethod(post);
if (status != expected) {
throw new HttpStatusCodeException(expected, status, "POST", HttpTestBase.getResponseBodyAsStream(post, 0));
}
}
use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project sling by apache.
the class SlingIntegrationTestClient method createNode.
/** Create a node under given path, using a POST to Sling
* @param url under which node is created
* @param multiPart if true, does a multipart POST
* @param localFile file to upload
* @param fieldName name of the file field
* @param typeHint typeHint of the file field
* @return the URL that Sling provides to display the node
*/
public String createNode(String url, NameValuePairList clientNodeProperties, Map<String, String> requestHeaders, boolean multiPart, File localFile, String fieldName, String typeHint) throws IOException {
final PostMethod post = new PostMethod(url);
post.setFollowRedirects(false);
// create a private copy of the properties to not tamper with
// the properties of the client
NameValuePairList nodeProperties = new NameValuePairList(clientNodeProperties);
// add sling specific properties
nodeProperties.prependIfNew(":redirect", "*");
nodeProperties.prependIfNew(":displayExtension", "");
nodeProperties.prependIfNew(":status", "browser");
// add fake property - otherwise the node is not created
if (clientNodeProperties == null) {
nodeProperties.add("jcr:created", "");
}
// force form encoding to UTF-8, which is what we use to convert the
// string parts into stream data
nodeProperties.addOrReplace("_charset_", "UTF-8");
if (nodeProperties.size() > 0) {
if (multiPart) {
final List<Part> partList = new ArrayList<Part>();
for (NameValuePair e : nodeProperties) {
if (e.getValue() != null) {
partList.add(new StringPart(e.getName(), e.getValue(), "UTF-8"));
}
}
if (localFile != null) {
partList.add(new FilePart(fieldName, localFile));
if (typeHint != null) {
partList.add(new StringPart(fieldName + "@TypeHint", typeHint));
}
}
final Part[] parts = partList.toArray(new Part[partList.size()]);
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
} else {
post.getParams().setContentCharset("UTF-8");
for (NameValuePair e : nodeProperties) {
post.addParameter(e.getName(), e.getValue());
}
}
}
if (requestHeaders != null) {
for (Map.Entry<String, String> e : requestHeaders.entrySet()) {
post.addRequestHeader(e.getKey(), e.getValue());
}
}
final int expected = 302;
final int status = httpClient.executeMethod(post);
if (status != expected) {
throw new HttpStatusCodeException(expected, status, "POST", url, HttpTestBase.getResponseBodyAsStream(post, 0));
}
String location = post.getResponseHeader("Location").getValue();
post.releaseConnection();
// simple check if host is missing
if (!location.startsWith("http://")) {
String host = HttpTestBase.HTTP_BASE_URL;
int idx = host.indexOf('/', 8);
if (idx > 0) {
host = host.substring(0, idx);
}
location = host + location;
}
return location;
}
Aggregations