List of usage examples for org.apache.commons.httpclient.methods.multipart ByteArrayPartSource ByteArrayPartSource
public ByteArrayPartSource(String paramString, byte[] paramArrayOfByte)
From source file:net.formio.servlet.MockServletRequests.java
/** * Creates new servlet request that contains given resource as multi part. * @param paramName/*from w ww. j a v a2 s. c om*/ * @param resourceName * @return */ public static MockHttpServletRequest newRequest(String paramName, String resourceName, String mimeType) { try { MockHttpServletRequest request = new MockHttpServletRequest(); // Load resource being uploaded ByteArrayOutputStream bos = new ByteArrayOutputStream(); Streams.copy(MockServletRequests.class.getResourceAsStream(resourceName), bos, true); byte[] fileContent = bos.toByteArray(); // Create part & entity from resource Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent), mimeType, (String) null) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); request.setContent(requestContent.toByteArray()); // Set content type of request (important, includes MIME boundary string) String contentType = multipartRequestEntity.getContentType(); request.setContentType(contentType); request.setMethod("POST"); return request; } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
From source file:net.formio.portlet.MockPortletRequests.java
/** * Creates new portlet request that contains given resource as multi part. * @param paramName// w w w . j a va2 s. c om * @param resourceName * @return */ public static MockMultipartActionRequest newRequest(String paramName, String resourceName, String mimeType) { try { MockMultipartActionRequest request = new MockMultipartActionRequest(); // Load resource being uploaded ByteArrayOutputStream bos = new ByteArrayOutputStream(); Streams.copy(MockPortletRequests.class.getResourceAsStream(resourceName), bos, true); byte[] fileContent = bos.toByteArray(); // Create part & entity from resource Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent), mimeType, (String) null) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); request.setContent(requestContent.toByteArray()); // Set content type of request (important, includes MIME boundary string) String contentType = multipartRequestEntity.getContentType(); request.setContentType(contentType); return request; } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
From source file:demo.jaxrs.search.client.Client.java
private static void uploadToCatalog(final String url, final HttpClient httpClient, final String filename) throws IOException, HttpException { System.out.println("Sent HTTP POST request to upload the file into catalog: " + filename); final PostMethod post = new PostMethod(url); final Part[] parts = { new FilePart(filename, new ByteArrayPartSource(filename, IOUtils.readBytesFromStream(Client.class.getResourceAsStream("/" + filename)))) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); try {// w ww .j a va2 s . c om int status = httpClient.executeMethod(post); if (status == 201) { System.out.println(post.getResponseHeader("Location")); } else if (status == 409) { System.out.println("Document already exists: " + filename); } } finally { post.releaseConnection(); } }
From source file:edu.umd.cs.buildServer.util.ServletAppender.java
@Override protected void append(LoggingEvent event) { if (!APPEND_TO_SUBMIT_SERVER) return;/*from w w w.j a va 2 s . co m*/ try { Throwable throwable = null; if (event.getThrowableInformation() != null) { String[] throwableStringRep = event.getThrowableStrRep(); StringBuffer stackTrace = new StringBuffer(); for (String stackTraceString : throwableStringRep) { stackTrace.append(stackTraceString); } throwable = new Throwable(stackTrace.toString()); } LoggingEvent newLoggingEvent = new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(), event.getLevel(), getConfig().getHostname() + ": " + event.getMessage(), throwable); HttpClient client = new HttpClient(); client.setConnectionTimeout(HTTP_TIMEOUT); String logURL = config.getServletURL(SUBMIT_SERVER_HANDLEBUILDSERVERLOGMESSAGE_PATH); MultipartPostMethod post = new MultipartPostMethod(logURL); // add password ByteArrayOutputStream sink = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(sink); out.writeObject(newLoggingEvent); out.flush(); // add serialized logging event object post.addPart(new FilePart("event", new ByteArrayPartSource("event.out", sink.toByteArray()))); int status = client.executeMethod(post); if (status != HttpStatus.SC_OK) { throw new IOException("Couldn't contact server: " + status); } } catch (IOException e) { // TODO any way to log these without an infinite loop? System.err.println(e.getMessage()); e.printStackTrace(System.err); } }
From source file:ch.sportchef.business.event.bundary.EventImageResourceTest.java
@Test public void uploadImageWithOK() throws IOException, ServletException { // arrange// ww w .ja va 2s. c o m final byte[] fileContent = readTestImage(); final Part[] parts = new Part[] { new FilePart(TEST_IMAGE_NAME, new ByteArrayPartSource(TEST_IMAGE_NAME, fileContent)) }; final MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); final ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); final ByteArrayInputStream inputStream = new ByteArrayInputStream(requestContent.toByteArray()); final ServletInputStreamMock inputStreamMock = new ServletInputStreamMock(inputStream); final String contentType = multipartRequestEntity.getContentType(); expect(httpServletRequest.getContentType()).andStubReturn(contentType); expect(httpServletRequest.getInputStream()).andStubReturn(inputStreamMock); eventImageServiceMock.uploadImage(anyLong(), anyObject()); mockProvider.replayAll(); // act final Response response = eventImageResource.uploadImage(httpServletRequest); // assert assertThat(response.getStatus(), is(OK.getStatusCode())); mockProvider.verifyAll(); }
From source file:com.zimbra.qa.unittest.TestFileUpload.java
@Test public void testAdminUploadWithCsrfInHeader() 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);//from ww w. j a v a 2s . c om 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())); 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 }, post.getParams())); post.addRequestHeader(Constants.CSRF_TOKEN, csrfToken); int statusCode = HttpClientUtil.executeMethod(client, post); assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode); String resp = post.getResponseBodyAsString(); assertNotNull("Response should not be empty", resp); assertTrue("Incorrect HTML response", resp.contains(RESP_STR)); }
From source file:com.netflix.postreview.ExtendedCrucibleSession.java
/** * Override addItemsToReview to differentiate the 3 cases of pairs present 1/1, 1/0, 0/1 (0/0 * being invalid).//from w w w .ja v a2 s. co m */ @Override public void addItemsToReview(PermId permId, Collection<UploadItem> uploadItems) throws RemoteApiException { final String REVIEW_SERVICE = "/rest-service/reviews-v1"; final String ADD_FILE = "/addFile"; try { String urlString = getBaseUrl() + REVIEW_SERVICE + "/" + permId.getId() + ADD_FILE; for (UploadItem uploadItem : uploadItems) { // Item add if (uploadItem.getOldContent() == null && uploadItem.getNewContent() != null) { ByteArrayPartSource targetNewFile = new ByteArrayPartSource(uploadItem.getFileName(), uploadItem.getNewContent()); Part[] parts = { new FilePart("file", targetNewFile, uploadItem.getNewContentType(), uploadItem.getNewCharset()) }; retrievePostResponse(urlString, parts, true); // Item modify // TODO: use this approach for deletions too for now. } else if (true) { //uploadItem.getOldContent() != null && uploadItem.getNewContent() != null) { ByteArrayPartSource targetNewFile = new ByteArrayPartSource(uploadItem.getFileName(), uploadItem.getNewContent()); ByteArrayPartSource targetOldFile = new ByteArrayPartSource(uploadItem.getFileName(), uploadItem.getOldContent()); Part[] parts = { new FilePart("file", targetNewFile, uploadItem.getNewContentType(), uploadItem.getNewCharset()), new FilePart("diffFile", targetOldFile, uploadItem.getOldContentType(), uploadItem.getOldCharset()) }; retrievePostResponse(urlString, parts, true); // Item delete // TODO: this rest combo doesn't work: crucible seems to need the "file" part... } else { // uploadItem.getOldContent() != null && uploadItem.getNewContent() == null ByteArrayPartSource targetOldFile = new ByteArrayPartSource(uploadItem.getFileName(), uploadItem.getOldContent()); Part[] parts = { new FilePart("diffFile", targetOldFile, uploadItem.getOldContentType(), uploadItem.getOldCharset()) }; retrievePostResponse(urlString, parts, true); } } } catch (JDOMException e) { throw new RemoteApiException(getBaseUrl() + ": Server returned malformed response", e); } }
From source file:com.intuit.tank.http.multipart.MultiPartRequest.java
protected List<Part> buildParts() { List<Part> parts = new ArrayList<Part>(); for (PartHolder h : parameters) { if (h.getFileName() == null) { StringPart stringPart = new StringPart(h.getPartName(), new String(h.getBodyAsString())); if (h.isContentTypeSet()) { stringPart.setContentType(h.getContentType()); }/*w ww . ja v a 2 s .c om*/ parts.add(stringPart); } else { PartSource partSource = new ByteArrayPartSource(h.getFileName(), h.getBody()); FilePart p = new FilePart(h.getPartName(), partSource); if (h.isContentTypeSet()) { p.setContentType(h.getContentType()); } parts.add(p); } } return parts; }
From source file:PublisherUtil.java
/** * Publishes a list of files and a datasource to the server with basic authentication to the server * /*www . j av a 2s . co m*/ * @param publishURL * The URL of the Pentaho server * @param publishPath * The path in the solution to place the files * @param publishFiles * Array of File objects to post to the server * @param dataSource * The datasource to publish to the server * @param publishPassword * The publishing password for the server * @param serverUserid * The userid to authenticate to the server * @param serverPassword * The password to authenticate with the server * @param overwrite * Whether the server should overwrite the file if it exists already * @param mkdirs * Whether the server should create any missing folders on the publish path * @return Server response as a string * @throws Exception */ public static String publish(final String publishURL, final String publishPath, final File publishFiles[], final String publishPassword, final String serverUserid, final String serverPassword, final boolean overwrite, final boolean mkdirs) throws Exception { int status = -1; System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "warn");//$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "warn");//$NON-NLS-1$ //$NON-NLS-2$ String fullURL = null; try { fullURL = publishURL + "?publishPath=" + URLEncoder.encode(publishPath, "UTF-8"); } catch (UnsupportedEncodingException e) { fullURL = publishURL + "?publishPath=" + publishPath; System.out.println("Erro de publicao na classe publisher!" + e); // throw new Exception("Erro de publicao na classe publisher!" + e); } if (publishPassword == null) { throw new IllegalArgumentException("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED"); //$NON-NLS-1$ // throw new IllegalArgumentException(Messages.getErrorString("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED")); //$NON-NLS-1$ } fullURL += "&publishKey=" + PublisherUtil.getPasswordKey(publishPassword); //$NON-NLS-1$ fullURL += "&overwrite=" + overwrite; //$NON-NLS-1$ fullURL += "&mkdirs=" + mkdirs; //$NON-NLS-1$ PostMethod filePost = new PostMethod(fullURL); Part[] parts = new Part[publishFiles.length]; for (int i = 0; i < publishFiles.length; i++) { try { File file = publishFiles[i]; FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); String reportNameEncoded = (URLEncoder.encode(file.getName(), "UTF-8")); ByteArrayPartSource source = new ByteArrayPartSource(reportNameEncoded, out.toByteArray()); parts[i] = new FilePart(reportNameEncoded, source, FilePart.DEFAULT_CONTENT_TYPE, "UTF-8"); } catch (Exception e) { PublisherUtil.logger.error(null, e); throw new Exception("Erro de publicao na classe publisher!" + e); } } filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); try { if ((serverUserid != null) && (serverUserid.length() > 0) && (serverPassword != null) && (serverPassword.length() > 0)) { Credentials creds = new UsernamePasswordCredentials(serverUserid, serverPassword); client.getState().setCredentials(AuthScope.ANY, creds); client.getParams().setAuthenticationPreemptive(true); } status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { String postResult = filePost.getResponseBodyAsString(); if (postResult != null) { try { return postResult.trim(); // +" - "+Integer.parseInt(postResult.trim()); } catch (NumberFormatException e) { PublisherUtil.logger.error(null, e); // throw new Exception("Erro de publicao na classe publisher!" + e + " " +PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS); return "" + PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS; } } } else if (status == HttpStatus.SC_UNAUTHORIZED) { return "" + PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS; } } catch (HttpException e) { PublisherUtil.logger.error(null, e); // throw new Exception("Erro de publicao na classe publisher!" + e ); } catch (IOException e) { PublisherUtil.logger.error(null, e); // throw new Exception("Erro de publicao na classe publisher!" + e ); } // return Messages.getString("REPOSITORYFILEPUBLISHER.USER_PUBLISHER_FAILED"); //$NON-NLS-1$ return "" + PublisherUtil.FILE_ADD_FAILED; }
From source file:com.zimbra.qa.unittest.TestFileUpload.java
@Test public void testMissingCsrfAdminUpload() 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);//from w ww . j a va2 s . c o m Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory())); com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response); String authToken = authResp.getAuthToken(); 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())); 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 }, post.getParams())); int statusCode = HttpClientUtil.executeMethod(client, post); assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode); String resp = post.getResponseBodyAsString(); assertNotNull("Response should not be empty", resp); assertTrue("Incorrect HTML response", resp.contains(RESP_STR)); }