List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity
public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams)
From source file:org.geoserver.importer.rest.RESTDataTest.java
int postNewTaskAsMultiPartForm(int imp, String data) throws Exception { File dir = unpack(data);//from www . ja va 2s .co m List<Part> parts = new ArrayList<Part>(); for (File f : dir.listFiles()) { parts.add(new FilePart(f.getName(), f)); } MultipartRequestEntity multipart = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), new PostMethod().getParams()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); multipart.writeRequest(bout); MockHttpServletRequest req = createRequest("/rest/imports/" + imp + "/tasks"); req.setContentType(multipart.getContentType()); req.addHeader("Content-Type", multipart.getContentType()); req.setMethod("POST"); req.setBodyContent(bout.toByteArray()); MockHttpServletResponse resp = dispatch(req); assertEquals(201, resp.getStatusCode()); assertNotNull(resp.getHeader("Location")); assertTrue(resp.getHeader("Location").matches(".*/imports/" + imp + "/tasks/\\d")); assertEquals("application/json", resp.getContentType()); JSONObject json = (JSONObject) json(resp); JSONObject task = json.getJSONObject("task"); return task.getInt("id"); }
From source file:org.geoserver.importer.rest.TaskResourceTest.java
public void testDeleteTask() throws Exception { MockHttpServletResponse resp = postAsServletResponse("/rest/imports", ""); assertEquals(201, resp.getStatusCode()); assertNotNull(resp.getHeader("Location")); String[] split = resp.getHeader("Location").split("/"); Integer id = Integer.parseInt(split[split.length - 1]); ImportContext context = importer.getContext(id); File dir = unpack("shape/archsites_epsg_prj.zip"); unpack("shape/bugsites_esri_prj.tar.gz", dir); new File(dir, "extra.file").createNewFile(); File[] files = dir.listFiles(); Part[] parts = new Part[files.length]; for (int i = 0; i < files.length; i++) { parts[i] = new FilePart(files[i].getName(), files[i]); }//from w w w .j av a2 s .co m MultipartRequestEntity multipart = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); multipart.writeRequest(bout); MockHttpServletRequest req = createRequest("/rest/imports/" + id + "/tasks"); req.setContentType(multipart.getContentType()); req.addHeader("Content-Type", multipart.getContentType()); req.setMethod("POST"); req.setBodyContent(bout.toByteArray()); resp = dispatch(req); context = importer.getContext(context.getId()); assertEquals(2, context.getTasks().size()); req = createRequest("/rest/imports/" + id + "/tasks/1"); req.setMethod("DELETE"); resp = dispatch(req); assertEquals(204, resp.getStatusCode()); context = importer.getContext(context.getId()); assertEquals(1, context.getTasks().size()); }
From source file:org.geoserver.importer.rest.TaskResourceTest.java
public void testPostMultiPartFormData() throws Exception { MockHttpServletResponse resp = postAsServletResponse("/rest/imports", ""); assertEquals(201, resp.getStatusCode()); assertNotNull(resp.getHeader("Location")); String[] split = resp.getHeader("Location").split("/"); Integer id = Integer.parseInt(split[split.length - 1]); ImportContext context = importer.getContext(id); assertNull(context.getData());/*from ww w . j av a 2 s . c om*/ assertTrue(context.getTasks().isEmpty()); File dir = unpack("shape/archsites_epsg_prj.zip"); Part[] parts = new Part[] { new FilePart("archsites.shp", new File(dir, "archsites.shp")), new FilePart("archsites.dbf", new File(dir, "archsites.dbf")), new FilePart("archsites.shx", new File(dir, "archsites.shx")), new FilePart("archsites.prj", new File(dir, "archsites.prj")) }; MultipartRequestEntity multipart = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); multipart.writeRequest(bout); MockHttpServletRequest req = createRequest("/rest/imports/" + id + "/tasks"); req.setContentType(multipart.getContentType()); req.addHeader("Content-Type", multipart.getContentType()); req.setMethod("POST"); req.setBodyContent(bout.toByteArray()); resp = dispatch(req); context = importer.getContext(context.getId()); assertNull(context.getData()); assertEquals(1, context.getTasks().size()); ImportTask task = context.getTasks().get(0); assertTrue(task.getData() instanceof SpatialFile); assertEquals(ImportTask.State.READY, task.getState()); }
From source file:org.iavante.sling.gad.administration.impl.AbstractHttpOperation.java
/** Execute a POST request and check status */ protected Header[] assertAuthenticatedPostMultipartStatus(Credentials creds, String url, List<String> expectedStatusCode, Part[] parts, String assertMessage) throws IOException { Header[] headers = null;//from w w w .ja v a 2s . co m URL baseUrl = new URL(HTTP_BASE_URL); List authPrefs = new ArrayList(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); HttpClient httpClient = new HttpClient(); httpClient.getParams().setAuthenticationPreemptive(true); httpClient.getState().setCredentials(AuthScope.ANY, creds); httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); PostMethod post = new PostMethod(url); post.setFollowRedirects(false); post.setDoAuthentication(true); try { if (parts != null) { post.setRequestEntity((RequestEntity) new MultipartRequestEntity(parts, post.getParams())); } final int status = httpClient.executeMethod(post); if (!expectedStatusCode.contains("" + status)) { log.error("ResponseCode: " + status + " isn't in " + expectedStatusCode.toString()); throw new IOException("ResponseCode: " + status + " isn't in " + expectedStatusCode.toString()); } headers = post.getResponseHeaders(); } finally { post.releaseConnection(); } return headers; }
From source file:org.iavante.uploader.ifaces.impl.UploadServiceImpl.java
/** * POST to a specified url.//from ww w . j a va2 s .c o m * * @param request * @param urlNotification * @param params * @return * @throws Exception */ private String restConnection2(HttpServletRequest request, String urlNotification, Map params) throws Exception { if (out.isInfoEnabled()) out.info("restConnection, ini"); String rt = request.getParameter("rt"); if (rt == null) { rt = "gad/source"; } if (out.isInfoEnabled()) out.info("restConnection, rt -> " + rt); PostMethod post = new PostMethod(urlNotification); List<Part> listPart = new ArrayList<Part>(); listPart.add(new StringPart("sling:resourceType", rt)); listPart.add(new StringPart("jcr:lastModified", "")); listPart.add(new StringPart("jcr:lastModifiedBy", "")); listPart.add(new FilePart("body.txt", new File(bodyFilename))); // parts[3] = new StringPart("filename", f.getName()), new FilePart("data", // f); Set set = params.entrySet(); Iterator it = set.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); if ("".compareTo((String) entry.getValue()) != 0) { String campo = (String) relation.get("" + entry.getKey()); listPart.add(new StringPart(campo, "" + entry.getValue())); } } int cont = 0; if ("".compareTo((String) params.get("video")) != 0) { listPart.add(new StringPart("track_1_type", "video")); cont++; } if ("".compareTo((String) params.get("audio")) != 0) { listPart.add(new StringPart("track_2_type", "audio")); cont++; } if (cont > 0) { listPart.add(new StringPart("tracks_number", "" + cont)); } Part[] parts = new Part[listPart.size()]; for (int i = 0; i < listPart.size(); i++) { parts[i] = listPart.get(i); } post.setRequestEntity((RequestEntity) new MultipartRequestEntity(parts, post.getParams())); post.setDoAuthentication(true); SlingHttpServletRequest req = (SlingHttpServletRequest) request; String credentials = authTools.extractUserPass(req); int colIdx = credentials.indexOf(':'); if (colIdx < 0) { userCreds = new UsernamePasswordCredentials(credentials); } else { userCreds = new UsernamePasswordCredentials(credentials.substring(0, colIdx), credentials.substring(colIdx + 1)); } client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, userCreds); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); int responseCode = -1; String responseMessage = ""; try { client.executeMethod(post); responseCode = post.getStatusCode(); responseMessage = post.getResponseBodyAsString(); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } finally { post.releaseConnection(); } if (responseCode != 201 && responseCode != 200) { throw new IOException("sendContentToRevision, code=" + responseCode); } if (out.isInfoEnabled()) out.info("restConnection, end"); return responseMessage + " (" + responseCode + ")"; }
From source file:org.iavante.uploader.ifaces.UploadServiceIT.java
/** * Tests a valid upload action.// ww w . ja v a2 s .c o m * * @exception Exception * Invalid httpRequest Exception */ public void test_ValidUpload() throws Exception { PostMethod post0 = new PostMethod(SLING_URL + CONTENT); Part[] parts0 = { new StringPart("title", "Prueba") }; post0.setRequestEntity((RequestEntity) new MultipartRequestEntity(parts0, post0.getParams())); post0.setDoAuthentication(true); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, defaultcreds); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); try { client.executeMethod(post0); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } assertEquals(201, post0.getStatusCode()); File f = new File(VIDEODIR + VIDEONAME); PostMethod post = new PostMethod(SLING_URL + UPLOADER_URL); Part[] parts = { new StringPart("coreurl", CORE_URL), new StringPart("content", CONTENT), new StringPart("filename", f.getName()), new FilePart("data", f) }; post.setRequestEntity((RequestEntity) new MultipartRequestEntity(parts, post.getParams())); post.setDoAuthentication(true); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, defaultcreds); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); try { client.executeMethod(post); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } assertEquals(200, post.getStatusCode()); if (post.getStatusCode() == 200) { // --------------------------------------------------- // --------------------------------------------------- uploadService.removeFile("/mnt/gad/input_repository/" + VIDEONAME); PostMethod post2 = new PostMethod(SLING_URL + CONTENT); Part[] parts2 = { new StringPart(":operation", "delete") }; post2.setRequestEntity((RequestEntity) new MultipartRequestEntity(parts2, post2.getParams())); post2.setDoAuthentication(true); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, defaultcreds); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); try { client.executeMethod(post2); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } assertEquals(post2.getStatusCode(), 200); } post.releaseConnection(); }
From source file:org.intermine.webservice.client.util.HttpConnection.java
private void setMultiPartPostEntity(PostMethod postMethod, MultiPartRequest req) { List<Part> parts = req.getParts(); if (!parts.isEmpty()) { RequestEntity entity = new MultipartRequestEntity(req.getParts().toArray(new Part[1]), postMethod.getParams()); postMethod.setRequestEntity(entity); }/* w w w . j a va 2 s. co m*/ }
From source file:org.jaggeryjs2.xhr.XMLHttpRequest.java
private void sendRequest(Object obj) throws Exception { 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 FormData) { FormData fd = ((FormData) obj); List<Part> parts = new ArrayList<Part>(); for (Map.Entry<String, String> entry : fd) { parts.add(new StringPart(entry.getKey(), entry.getValue())); }/* w w w. j ava 2s.c o m*/ 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 Exception("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 XMLHttpRequest xhr = this; if (async) { updateReadyState(xhr, LOADING); final ExecutorService es = Executors.newSingleThreadExecutor(); es.submit(new Callable() { public Object call() throws Exception { try { executeRequest(xhr); } catch (Exception e) { log.error(e.getMessage(), e); } finally { es.shutdown(); } return null; } }); } else { executeRequest(xhr); } }
From source file:org.jahia.services.templates.ForgeHelper.java
/** * Manage Private App Store/* ww w.j a va 2s . c om*/ */ String createForgeModule(ModuleReleaseInfo releaseInfo, File jar) throws IOException { String moduleUrl = null; final String url = releaseInfo.getForgeUrl(); HttpClient client = httpClientService.getHttpClient(url); // Get token from Private App Store home page GetMethod getMethod = new GetMethod(url + "/home.html"); getMethod.addRequestHeader("Authorization", "Basic " + Base64.encode((releaseInfo.getUsername() + ":" + releaseInfo.getPassword()).getBytes())); String token = ""; try { client.executeMethod(getMethod); Source source = new Source(getMethod.getResponseBodyAsString()); if (source.getFirstElementByClass("file_upload") != null) { List<net.htmlparser.jericho.Element> els = source.getFirstElementByClass("file_upload") .getAllElements("input"); for (net.htmlparser.jericho.Element el : els) { if (StringUtils.equals(el.getAttributeValue("name"), "form-token")) { token = el.getAttributeValue("value"); } } } else { throw new IOException( "Unable to get Private App Store site information, please check your credentials"); } } finally { getMethod.releaseConnection(); } Part[] parts = { new StringPart("form-token", token), new FilePart("file", jar) }; // send module PostMethod postMethod = new PostMethod(url + "/contents/modules-repository.createModuleFromJar.do"); postMethod.getParams().setSoTimeout(0); postMethod.addRequestHeader("Authorization", "Basic " + Base64.encode((releaseInfo.getUsername() + ":" + releaseInfo.getPassword()).getBytes())); postMethod.addRequestHeader("accept", "application/json"); postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); String result = null; try { client.executeMethod(null, postMethod); StatusLine statusLine = postMethod.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == SC_OK) { result = postMethod.getResponseBodyAsString(); } else { logger.warn("Connection to URL: " + url + " failed with status " + statusLine); } } catch (HttpException e) { logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e); } catch (IOException e) { logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e); } finally { postMethod.releaseConnection(); } if (StringUtils.isNotEmpty(result)) { try { JSONObject json = new JSONObject(result); if (!json.isNull("moduleAbsoluteUrl")) { moduleUrl = json.getString("moduleAbsoluteUrl"); } else if (!json.isNull("error")) { throw new IOException(json.getString("error")); } else { logger.warn("Cannot find 'moduleAbsoluteUrl' entry in the create module actin response: {}", result); throw new IOException("unknown"); } } catch (JSONException e) { logger.error("Unable to parse the response of the module creation action. Cause: " + e.getMessage(), e); } } return moduleUrl; }
From source file:org.jbpm.bpel.tools.ant.DeploymentTask.java
protected void writeRequest(PostMethod post) throws IOException { // process part String contentType = URLConnection.getFileNameMap().getContentTypeFor(processArchive.getName()); FilePart processPart = new FilePart("processArchive", processArchive, contentType, FileUtil.DEFAULT_CHARSET.name()); // multipart request post.setRequestEntity(new MultipartRequestEntity(new Part[] { processPart }, post.getParams())); log("deploying process: " + processArchive.getName()); }