List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity
public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams)
From source file:org.opencastproject.distribution.hydrant.HydrantDistributionService.java
/** * Distributes the mediapackage's element to the location that is returned by the concrete implementation. In * addition, a representation of the distributed element is added to the mediapackage. * //ww w. j a va 2 s. c o m * @see org.opencastproject.distribution.api.DistributionService#distribute(String, MediaPackageElement) */ protected MediaPackageElement distribute(Job job, MediaPackage mediapackage, String elementId) throws DistributionException { if (mediapackage == null) throw new IllegalArgumentException("Mediapackage must be specified"); if (elementId == null) throw new IllegalArgumentException("Element ID must be specified"); String mediaPackageId = mediapackage.getIdentifier().compact(); MediaPackageElement element = mediapackage.getElementById(elementId); // Make sure the element exists if (mediapackage.getElementById(elementId) == null) throw new IllegalStateException("No element " + elementId + " found in mediapackage"); try { // The hydrant server only supports tracks if (!(element instanceof Track)) { return null; } String parentpid = mediapackage.getTitle(); if (parentpid == null) { throw new DistributionException("Could not find Hydrant pid in mediapackage."); } logger.trace("Found parent pid: {}", parentpid); try { String url = UrlSupport.concat(new String[] { hydrantUrl, "derivatives" }); MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); HttpClient client = new HttpClient(mgr); Credentials defaultcreds = new UsernamePasswordCredentials(hydrantAdminUsername, hydrantAdminPassword); client.getState().setCredentials(AuthScope.ANY, defaultcreds); client.getParams().setAuthenticationPreemptive(true); PostMethod post = new PostMethod(url); post.setDoAuthentication(true); Part[] parts = { new StringPart("stream_url", element.getURI().toString()), new StringPart("master", parentpid), }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); int status = client.executeMethod(post); logger.debug("Got status: " + status); logger.trace("Got response body: " + post.getResponseBodyAsString()); } catch (IOException e) { logger.debug("Exception distributing to Hydrant: " + e.getCause()); throw new DistributionException("Error distributing to Hydrant instance", e); } logger.info("Distributed {} to hydrant", elementId); // Create a representation of the distributed file in the mediapackage MediaPackageElement distributedElement = (MediaPackageElement) element.clone(); //TODO Create and set a valid distribution URI /* try { distributedElement.setURI(getDistributionUri(mediaPackageId, element)); } catch (URISyntaxException e) { throw new DistributionException("Distributed element produces an invalid URI", e); } */ distributedElement.setIdentifier(null); logger.info("Finished distribution of {}", element); return distributedElement; } catch (Exception e) { logger.warn("Error distributing " + element, e); if (e instanceof DistributionException) { throw (DistributionException) e; } else { throw new DistributionException(e); } } }
From source file:org.opencms.applet.upload.FileUploadApplet.java
/** * Uploads the zipfile to the OpenCms.<p> * /*from w w w .java 2 s .c om*/ * @param uploadFile the zipfile to upload */ private void uploadZipFile(File uploadFile) { m_action = m_actionOutputUpload; repaint(); PostMethod post = new PostMethod(m_targetUrl); try { Part[] parts = new Part[5]; parts[0] = new FilePart(uploadFile.getName(), uploadFile); parts[1] = new StringPart("action", "submitform"); parts[2] = new StringPart("unzipfile", "true"); parts[3] = new StringPart("uploadfolder", m_uploadFolder); parts[4] = new StringPart("clientfolder", m_fileSelector.getCurrentDirectory().getAbsolutePath()); HttpMethodParams methodParams = post.getParams(); methodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); MultipartRequestEntity request = new MultipartRequestEntity(parts, methodParams); post.setRequestEntity(request); // add jsessionid query string String sessionId = getParameter("sessionId"); String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId; post.setQueryString(query); post.addRequestHeader(C_JSESSIONID, sessionId); HttpClient client = new HttpClient(); HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams(); connectionParams.setConnectionTimeout(5000); // add the session cookie client.getState(); client.getHostConfiguration().getHost(); HttpState initialState = new HttpState(); URI uri = new URI(m_targetUrl, false); Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false); initialState.addCookie(sessionCookie); client.setState(initialState); // no execute the file upload int status = client.executeMethod(post); if (status == HttpStatus.SC_OK) { //return to the specified url and frame target getAppletContext().showDocument(new URL(m_redirectUrl), m_redirectTargetFrame); } else { // create the error text String error = m_errorLine1 + "\n" + post.getStatusLine(); //JOptionPane.showMessageDialog(this, error, "Error!", JOptionPane.ERROR_MESSAGE); getAppletContext().showDocument(new URL(m_errorUrl + "?action=showerror&uploaderror=" + error), "explorer_files"); } } catch (RuntimeException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { post.releaseConnection(); // finally delete the zipFile on the harddisc uploadFile.delete(); } }
From source file:org.openehealth.ipf.platform.camel.lbs.http.process.AbstractLbsHttpTest.java
@Test public void testMultipartWithoutResourceExtract() throws Exception { PostMethod method = new PostMethod(ENDPOINT_NO_EXTRACT); Part[] parts = new Part[] { new FilePart("file1", file), new FilePart("file2", file), new StringPart("text", "testtext") }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); mock.expectedMessageCount(1);// ww w. j a va 2 s . c o m mock.whenAnyExchangeReceived(new Processor() { @Override public void process(Exchange received) throws Exception { // Must be done in here because the connection is only valid during // processing HttpServletRequest request = received.getIn().getBody(HttpServletRequest.class); assertNotNull(request); assertTrue("did not receive a multipart message", ServletFileUpload.isMultipartContent(request)); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List files = upload.parseRequest(request); assertEquals(3, files.size()); FileItem fileItem = (FileItem) files.get(0); assertEquals("file1", fileItem.getFieldName()); assertEquals("blu bla", fileItem.getString()); fileItem = (FileItem) files.get(1); assertEquals("file2", fileItem.getFieldName()); assertEquals("blu bla", fileItem.getString()); fileItem = (FileItem) files.get(2); assertEquals("text", fileItem.getFieldName()); assertEquals("testtext", fileItem.getString()); } }); httpClient.executeMethod(method); method.releaseConnection(); mock.assertIsSatisfied(); }
From source file:org.openehealth.ipf.platform.camel.lbs.http.process.AbstractLbsHttpTest.java
private void testMultipart(String endpoint) throws Exception { PostMethod method = new PostMethod(endpoint); Part[] parts = new Part[] { new FilePart("file1", file), new FilePart("file2", file), new StringPart("text1", "testtext1"), new StringPart("text2", "testtext2") }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); mock.expectedMessageCount(1);// www . j a v a 2s. c o m mock.whenAnyExchangeReceived(outputGenerator); httpClient.executeMethod(method); assertEquals("testoutput", method.getResponseBodyAsString()); method.releaseConnection(); mock.assertIsSatisfied(); Map<String, String> receivedContent = outputGenerator.getReceivedContent(); assertEquals(4, receivedContent.size()); assertEquals("blu bla", receivedContent.get("file1")); assertEquals("blu bla", receivedContent.get("file2")); assertEquals("testtext1", receivedContent.get("text1")); assertEquals("testtext2", receivedContent.get("text2")); assertEquals("blu bla", outputGenerator.getReceivedBody()); }
From source file:org.openehealth.ipf.platform.camel.lbs.http.process.HttpResourceHandler.java
private void integrateToMultipart(Message message, ResourceList resourceList) { message.setHeader(Exchange.HTTP_METHOD, HttpMethods.POST); PostMethod method = new PostMethod(); Part[] parts = new Part[resourceList.size()]; int idx = 0;//from w w w . j ava 2s.co m for (ResourceDataSource resource : resourceList) { parts[idx] = new ResourcePart(resource.getId(), resource); ++idx; } message.setBody(new MultipartRequestEntity(parts, method.getParams())); }
From source file:org.openmicroscopy.shoola.svc.proxy.MessengerFileRequest.java
/** * Prepares the <code>method</code> to post. * @see Request#marshal()/*from w w w .j av a 2 s .c o m*/ */ public HttpMethod marshal() throws TransportException { //Create request. PostMethod request = new PostMethod(); try { Part[] parts = { new StringPart(TOKEN, token), new StringPart(READER, reader), new FilePart(FILE, file) }; request.setRequestEntity(new MultipartRequestEntity(parts, request.getParams())); } catch (Exception e) { throw new TransportException("Cannot prepare file to submit", e); } return request; }
From source file:org.openmrs.module.sync.server.ServerConnection.java
public static ConnectionResponse sendExportedData(String url, String username, String password, String content, boolean isResponse) { // Default response - default constructor instantiates contains error codes ConnectionResponse syncResponse = new ConnectionResponse(); HttpClient client = new HttpClient(); url = url + SyncConstants.DATA_IMPORT_SERVLET; log.info("POST multipart request to " + url); if (url.startsWith("https")) { try {//ww w.ja v a2s . c o m if (Boolean.parseBoolean(Context.getAdministrationService() .getGlobalProperty(SyncConstants.PROPERTY_ALLOW_SELFSIGNED_CERTS))) { // It is necessary to provide a relative url (from the host name and port to the right) String relativeUrl; URI uri = new URI(url, true); String host = uri.getHost(); int port = uri.getPort(); // URI.getPort() returns -1 if port is not explicitly set if (port <= 0) { port = SyncConstants.DEFAULT_HTTPS_PORT; relativeUrl = url.split(host, 2)[1]; } else { relativeUrl = url.split(host + ":" + port, 2)[1]; } Protocol easyhttps = new Protocol("https", (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), port); client.getHostConfiguration().setHost(host, port, easyhttps); url = relativeUrl; } } catch (IOException ioe) { log.error("Unable to configure SSL to accept self-signed certificates"); } catch (GeneralSecurityException e) { log.error("Unable to configure SSL to accept self-signed certificates"); } } PostMethod method = new PostMethod(url); try { boolean useCompression = Boolean.parseBoolean(Context.getAdministrationService() .getGlobalProperty(SyncConstants.PROPERTY_ENABLE_COMPRESSION, "true")); log.info("use compression: " + useCompression); // Compress content ConnectionRequest request = new ConnectionRequest(content, useCompression); // Create up multipart request Part[] parts = { new FilePart("syncDataFile", new ByteArrayPartSource("syncDataFile", request.getBytes())), new StringPart("username", username), new StringPart("password", password), new StringPart("compressed", String.valueOf(useCompression)), new StringPart("isResponse", String.valueOf(isResponse)), new StringPart("checksum", String.valueOf(request.getChecksum())) }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); // Open a connection to the server and post the data client.getHttpConnectionManager().getParams().setSoTimeout(ServerConnection.getTimeout().intValue()); client.getHttpConnectionManager().getParams() .setConnectionTimeout(ServerConnection.getTimeout().intValue()); int status = client.executeMethod(method); // As long as the response is OK (200) if (status == HttpStatus.SC_OK) { // Decompress the response from the server //log.info("Response from server:" + method.getResponseBodyAsString()); // Check to see if the child/parent sent back a compressed response Header compressionHeader = method.getResponseHeader("Enable-Compression"); useCompression = (compressionHeader != null) ? new Boolean(compressionHeader.getValue()) : false; log.info("Response header Enable-Compression: " + useCompression); // Decompress the data received (if compression is enabled) syncResponse = new ConnectionResponse(method.getResponseBodyAsStream(), useCompression); // Now we want to validate the checksum Header checksumHeader = method.getResponseHeader("Content-Checksum"); long checksumReceived = (checksumHeader != null) ? new Long(checksumHeader.getValue()) : 0; log.info("Response header Content-Checksum: " + checksumReceived); log.info("checksum value received in response header: " + checksumReceived); log.info("checksum of payload: " + syncResponse.getChecksum()); // TODO Need to figure out what to do with this response if (checksumReceived > 0 && (checksumReceived != syncResponse.getChecksum())) { log.error("ERROR: FAILED CHECKSUM!"); syncResponse.setState(ServerConnectionState.CONNECTION_FAILED); // contains error message } } // if there's an error response code we should set the tran else { // HTTP error response code syncResponse .setResponsePayload("HTTP " + status + " Error Code: " + method.getResponseBodyAsString()); syncResponse.setState(ServerConnectionState.CONNECTION_FAILED); // contains error message } } catch (MalformedURLException mue) { log.error("Malformed URL " + url, mue); syncResponse.setState(ServerConnectionState.MALFORMED_URL); } catch (Exception e) { // all other exceptions really just mean that the connection was bad log.error("Error occurred while sending/receiving data ", e); syncResponse.setState(ServerConnectionState.CONNECTION_FAILED); } finally { method.releaseConnection(); } return syncResponse; }
From source file:org.oryxeditor.server.TBPMServlet.java
private String sendRequest(File img, String fileName) { HttpClient client = new HttpClient(); client.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 30000); PostMethod method = new PostMethod(TBPM_RECOGNITION_URL); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); String response = ""; try {/*from w w w .jav a 2s.co m*/ Part[] parts = { new FilePart(img.getName(), img) }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); client.executeMethod(method); //TODO handle response status response = method.getResponseBodyAsString(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } method.releaseConnection(); return response; }
From source file:org.pentaho.platform.util.client.PublisherUtil.java
/** * Publishes a list of files and a datasource to the server with basic authentication to the server * // w ww.ja v a 2 s .c om * @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 */ public static int 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) { 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; } if (publishPassword == null) { throw new IllegalArgumentException( Messages.getInstance().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); } } filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); try { // If server userid/password was supplied, use basic authentication to // authenticate with the server. 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 Integer.parseInt(postResult.trim()); } catch (NumberFormatException e) { PublisherUtil.logger.error(null, e); 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); } catch (IOException e) { PublisherUtil.logger.error(null, e); } // return Messages.getString("REPOSITORYFILEPUBLISHER.USER_PUBLISHER_FAILED"); //$NON-NLS-1$ return PublisherUtil.FILE_ADD_FAILED; }
From source file:org.pmedv.core.util.UploadUtils.java
public static boolean uploadFile(File sourceFile, String targetURL, UploadMonitor monitor) { log.info("uploading " + sourceFile + " to " + targetURL); PostMethod filePost = new PostMethod(targetURL); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); filePost.getParams().setContentCharset("ISO-8859-15"); try {/* w w w . ja va 2s. com*/ Part[] parts = { new CustomizableFilePart(sourceFile.getName(), sourceFile, monitor) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); Credentials defaultcreds = new UsernamePasswordCredentials(username, password); client.getState().setCredentials(new AuthScope(hostname, port, AuthScope.ANY_REALM), defaultcreds); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { log.info("Upload complete, response=" + filePost.getResponseBodyAsString()); } else { log.info("Upload failed, response=" + HttpStatus.getStatusText(status)); return false; } } catch (Exception ex) { log.error("An exception occured :"); log.error(ResourceUtils.getStackTrace(ex)); return false; } finally { filePost.releaseConnection(); } return true; }