List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity
public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams)
From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.services.SettingsLoaderImpl.java
public void saveConfigurationFile(String fileName, String config, RemoteSettings remoteSettings) throws SettingsLoaderException { try {/* w w w . j av a 2s. c o m*/ logger.debug( "Attempting to save '" + fileName + "' for '" + remoteSettings.getSettings().getEid() + "'"); PostMethod method = new PostMethod(remoteSettings.getBasePath() + "/hqu/tomcatserverconfig/tomcatserverconfig/saveConfigurationFile.hqu"); configureMethod(method, remoteSettings.getSettings().getEid(), remoteSettings.getSessionId(), remoteSettings.getCsrfNonce()); Part[] parts = new Part[] { new StringPart("fileName", fileName), new StringPart("file", config) }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); httpClient.executeMethod(method); if (method.getStatusCode() >= 300 && method.getStatusCode() < 400) { logger.info("Unable to save '" + fileName + "' configuration for '" + remoteSettings.getSettings().getEid() + "', HQ session expired"); throw new SettingsLoaderException(SESSION_EXPIRED_MESSAGE); } else if (method.getStatusCode() >= 400) { logger.warn("Unable to save '" + fileName + "' configuration for '" + remoteSettings.getSettings().getEid() + "', " + method.getStatusCode() + " " + method.getStatusText()); throw new SettingsLoaderException(method.getStatusText()); } remoteSettings.setCsrfNonce(method.getResponseBodyAsString()); logger.info("Saved '" + fileName + "' for '" + remoteSettings.getSettings().getEid() + "'"); } catch (SSLHandshakeException e) { logger.error("Server SSL certificate is untrusted: " + e.getMessage(), e); throw new SettingsLoaderException( "Unable to save '" + fileName + "' because the server is using an untrusted SSL certificate. " + "Please check the documentation for more information.", e); } catch (IOException e) { logger.error("Unable to save '" + fileName + "' for '" + remoteSettings.getSettings().getEid() + "': " + e.getMessage(), e); throw new SettingsLoaderException( "Saving configuration file failed because of a server error, please check the logs for more details", e); } }
From source file:com.ephesoft.dcma.boxexport.BoxExporter.java
/** * Method to process each document of the batch instance and export corresponding files to the box repository. * /*from w ww. j a va 2s .c o m*/ * @param batchInstanceIdentifier {@link String} * @param folderID {@link String} * @param authToken {@link String} * @param boxUploadFileType {@link String} * @param sFolderToBeExported {@link String} * @param listOfDocuments {@link List<Document>} * @throws DCMAApplicationException {@link DCMAApplicationException} */ private void processDocuments(final String batchInstanceIdentifier, final String folderID, final String authToken, final String boxUploadFileType, final String sFolderToBeExported, final List<Document> listOfDocuments) throws DCMAApplicationException { String exportMultiPageFileName = null; String url = BoxExportConstant.HTTPS_WWW_BOX_COM_API_1_0_UPLOAD_URL .replace(BoxExportConstant.AUTH_TOKEN_CONSTANT, authToken) .replace(BoxExportConstant.FOLDER_ID_CONSTANT, folderID); HttpClient client = new HttpClient(); PostMethod mPost = new PostMethod(url); try { for (Document document : listOfDocuments) { LOGGER.info("Processing document for box export : " + document.getIdentifier()); if (boxUploadFileType.equalsIgnoreCase(BoxExportConstant.MULTIPAGE_PDF)) { exportMultiPageFileName = document.getMultiPagePdfFile(); } else { exportMultiPageFileName = document.getMultiPageTiffFile(); } LOGGER.info("The file to be exported is : " + exportMultiPageFileName); File exportFile = new File(sFolderToBeExported + File.separator + exportMultiPageFileName); // Creating the data to be exported to Box Part[] parts = new Part[2]; parts[0] = new FilePart(exportMultiPageFileName, exportFile); String docLevelFieldData = getDocLevelFieldsData(document); LOGGER.info("Description for uploading file : " + docLevelFieldData); parts[1] = new StringPart(BoxExportConstant.DESCRIPTION, docLevelFieldData); MultipartRequestEntity entity = new MultipartRequestEntity(parts, mPost.getParams()); mPost.setRequestEntity(entity); // Sending the data to Box int statusCode = client.executeMethod(mPost); LOGGER.info("Status Code of method execution: " + statusCode); String responseBody = mPost.getResponseBodyAsString(); LOGGER.info("responseBody :: " + responseBody); // Getting and analyzing the response for the sent data org.w3c.dom.Document doc = XMLUtil.createDocumentFrom(mPost.getResponseBodyAsStream()); String statusOfResponse = XMLUtil.getValueFromXML(doc, BoxExportConstant.RESPONSE_STATUS); LOGGER.info("The status of response for upload is :" + statusOfResponse); if (null == statusOfResponse || !statusOfResponse.equals(BoxExportConstant.UPLOAD_OK)) { LOGGER.error("Error uploading files to Box. Exiting with error code : " + statusCode); throw new DCMAApplicationException(ERROR_EXPORTING_FILE + exportMultiPageFileName + BATCH_INSTANCE_ID + batchInstanceIdentifier); } } } catch (Exception e) { LOGGER.error( ERROR_EXPORTING_FILE + exportMultiPageFileName + BATCH_INSTANCE_ID + batchInstanceIdentifier, e); throw new DCMAApplicationException( ERROR_EXPORTING_FILE + exportMultiPageFileName + BATCH_INSTANCE_ID + batchInstanceIdentifier, e); } finally { mPost.releaseConnection(); } }
From source file:games.strategy.triplea.pbem.AxisAndAlliesForumPoster.java
public boolean postTurnSummary(final String message, final String subject) { try {//from www . j a v a 2 s .com login(); // Now we load the post page, and find the hidden fields needed to post final GetMethod get = new GetMethod( "http://www.axisandallies.org/forums/index.php?action=post;topic=" + m_topicId + ".0"); int status = m_client.executeMethod(m_hostConfiguration, get, m_httpState); String body = get.getResponseBodyAsString(); if (status == 200) { String numReplies; String seqNum; String sc; Matcher m = NUM_REPLIES_PATTERN.matcher(body); if (m.matches()) { numReplies = m.group(1); } else { throw new Exception("Hidden field 'num_replies' not found on page"); } m = SEQ_NUM_PATTERN.matcher(body); if (m.matches()) { seqNum = m.group(1); } else { throw new Exception("Hidden field 'seqnum' not found on page"); } m = SC_PATTERN.matcher(body); if (m.matches()) { sc = m.group(1); } else { throw new Exception("Hidden field 'sc' not found on page"); } // now we have the required hidden fields to reply to final PostMethod post = new PostMethod( "http://www.axisandallies.org/forums/index.php?action=post2;start=0;board=40"); try { // Construct the multi part post final List<Part> parts = new ArrayList<Part>(); parts.add(createStringPart("topic", m_topicId)); parts.add(createStringPart("subject", subject)); parts.add(createStringPart("icon", "xx")); parts.add(createStringPart("message", message)); // If the user has chosen to receive notifications, ensure this setting is passed on parts.add(createStringPart("notify", NOTIFY_PATTERN.matcher(body).matches() ? "1" : "0")); if (m_includeSaveGame && m_saveGameFile != null) { final FilePart part = new FilePart("attachment[]", m_saveGameFileName, m_saveGameFile); part.setContentType("application/octet-stream"); part.setTransferEncoding(null); part.setCharSet(null); parts.add(part); } parts.add(createStringPart("post", "Post")); parts.add(createStringPart("num_replies", numReplies)); parts.add(createStringPart("additional_options", "1")); parts.add(createStringPart("sc", sc)); parts.add(createStringPart("seqnum", seqNum)); final MultipartRequestEntity entity = new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), new HttpMethodParams()); post.setRequestEntity(entity); // add headers post.addRequestHeader("Referer", "http://www.axisandallies.org/forums/index.php?action=post;topic=" + m_topicId + ".0;num_replies=" + numReplies); post.addRequestHeader("Accept", "*/*"); try { // the site has spam prevention which means you can't post until 15 seconds after login Thread.sleep(15 * 1000); } catch (final InterruptedException ie) { ie.printStackTrace(); // this should never happen } post.setFollowRedirects(false); status = m_client.executeMethod(m_hostConfiguration, post, m_httpState); body = post.getResponseBodyAsString(); if (status == 302) { // site responds with a 302 redirect back to the forum index (board=40) // The syntax for post is ".....topic=xx.yy" where xx is the thread id, and yy is the post number in the given thread // since the site is lenient we can just give a high post_number to go to the last post in the thread m_turnSummaryRef = "http://www.axisandallies.org/forums/index.php?topic=" + m_topicId + ".10000"; } else { // these two patterns find general errors, where the first pattern checks if the error text appears, // the second pattern extracts the error message. This could be the "The last posting from your IP was less than 15 seconds ago.Please try again later" // this patter finds errors that are marked in red (for instance "You are not allowed to post URLs", or // "Some one else has posted while you vere reading" Matcher matcher = ERROR_LIST_PATTERN.matcher(body); if (matcher.matches()) { throw new Exception("The site gave an error: '" + matcher.group(1) + "'"); } matcher = AN_ERROR_OCCURRED_PATTERN.matcher(body); if (matcher.matches()) { matcher = ERROR_TEXT_PATTERN.matcher(body); if (matcher.matches()) { throw new Exception("The site gave an error: '" + matcher.group(1) + "'"); } } final Header refreshHeader = post.getResponseHeader("Refresh"); if (refreshHeader != null) { // sometimes the message will be flagged as spam, and a refresh url is given final String value = refreshHeader.getValue(); // refresh: 0; URL=http://...topic=26114.new%3bspam=true#new final Pattern p = Pattern.compile("[^;]*;\\s*url=.*spam=true.*", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); m = p.matcher(value); if (m.matches()) { throw new Exception("The summary was posted but was flagged as spam"); } } throw new Exception( "Unknown error, please contact the forum owner and also post a bug to the tripleA development team"); } } finally { post.releaseConnection(); // Commented out log out call since it was causing all of a user's sessions to be logged out and doesn't appear to be needed // final GetMethod logout = new GetMethod("http://www.axisandallies.org/forums/index.php?action=logout;sesc=" + sc); // try // { // status = m_client.executeMethod(m_hostConfiguration, logout, m_httpState); // // site responds with a 200 + Refresh header to redirect to index.php // if (status != 200) // { // // nothing we can do if this fails // } // } finally // { // logout.releaseConnection(); // } } } else { throw new Exception("Unable to load forum post " + m_topicId); } } catch (final Exception e) { m_turnSummaryRef = e.getMessage(); return false; } return true; }
From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java
/** * Sets up the given {@link PostMethod} to send the same multipart POST * data as was sent in the given {@link HttpServletRequest} * @param postMethodProxyRequest The {@link PostMethod} that we are * configuring to send a multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains * the mutlipart POST data to be sent via the {@link PostMethod} *//*w w w. j av a2 s. c om*/ @SuppressWarnings("unchecked") private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws IOException { _log.debug("handleMultipartPost()"); // 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(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // 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(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams()); postMethodProxyRequest.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 postMethodProxyRequest.setRequestHeader(HttpConstants.STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new IOException(fileUploadException); } }
From source file:edu.stanford.epad.common.plugins.PluginFileUtil.java
public static int sendFileToRemoteEPAD(String username, String epadHost, String epadSessionID, String projectID, String subjectID, String studyUID, String seriesUID, File file, String description) throws Exception { String url = buildEPADBaseURL(epadHost, EPADConfig.epadPort, "/epad/v2/" + getAction(projectID, subjectID, studyUID, seriesUID, username)); log.info("upload url " + url); HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); if (epadSessionID != null) postMethod.setRequestHeader("Cookie", "JSESSIONID=" + epadSessionID); try {/*from ww w . j a v a 2s . co m*/ Part[] parts = { new FilePart(file.getName(), file), new StringPart("description", description) }; postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); return client.executeMethod(postMethod); } catch (Exception e) { log.warning("Exception calling ePAD", e); return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } finally { postMethod.releaseConnection(); } }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST * data as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are * configuring to send a multipart POST request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the mutlipart POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} *//*from w ww .ja v a 2s . co m*/ @SuppressWarnings("unchecked") private void handleMultipartPost(PostMethod postMethodProxyRequest, 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(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // 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(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams()); postMethodProxyRequest.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 postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:com.ihelpoo.app.api.ApiClient.java
/** * post//from www.j ava2 s.co m * * @param url * @param params * @param files * @throws AppException */ private static InputStream _post(AppContext appContext, String url, Map<String, Object> params, Map<String, File> files) throws AppException { //System.out.println("post_url==> "+url); String cookie = getCookie(appContext); String userAgent = getUserAgent(appContext); HttpClient httpClient = null; PostMethod httpPost = null; //post??? int length = (params == null ? 0 : params.size()) + (files == null ? 0 : files.size()); Part[] parts = new Part[length]; int i = 0; if (params != null) for (String name : params.keySet()) { parts[i++] = new StringPart(name, String.valueOf(params.get(name)), UTF_8); } if (files != null) for (String file : files.keySet()) { try { parts[i++] = new FilePart(file, files.get(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } //System.out.println("post_key_file==> "+file); } String responseBody = ""; int time = 0; do { try { httpClient = getHttpClient(); httpPost = getHttpPost(url, cookie, userAgent); httpPost.setRequestEntity(new MultipartRequestEntity(parts, httpPost.getParams())); int statusCode = httpClient.executeMethod(httpPost); if (statusCode != HttpStatus.SC_OK) { throw AppException.http(statusCode); } else if (statusCode == HttpStatus.SC_OK) { Cookie[] cookies = httpClient.getState().getCookies(); String tmpcookies = ""; for (Cookie ck : cookies) { tmpcookies += ck.toString() + ";"; } //?cookie if (appContext != null && tmpcookies != "") { appContext.setProperty("cookie", tmpcookies); appCookie = tmpcookies; } } responseBody = httpPost.getResponseBodyAsString(); // System.out.println("XMLDATA=====>"+responseBody); break; } catch (HttpException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // ????? e.printStackTrace(); throw AppException.http(e); } catch (IOException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // ? e.printStackTrace(); throw AppException.network(e); } finally { // httpPost.releaseConnection(); httpClient = null; } } while (time < RETRY_TIME); responseBody = responseBody.replaceAll("\\p{Cntrl}", ""); // if(responseBody.contains("result") && responseBody.contains("errorCode") && appContext.containsProperty("user.uid")){//FIXME // try { // Result res = Result.parse(new ByteArrayInputStream(responseBody.getBytes())); // if(res.getErrorCode() == 0){ // appContext.logout(); // appContext.getUnLoginHandler().sendEmptyMessage(1); // } // } catch (Exception e) { // e.printStackTrace(); // } // } return new ByteArrayInputStream(responseBody.getBytes()); }
From source file:com.ephesoft.gxt.batchinstance.server.CopyTroubleshootingArtifacts.java
/** * Creates a post request for the calling a web service with given url. * //from w w w . j av a 2 s . c o m * @param tempLogFolderLocation {@link String} the temporary log folder path * @param webServiceURL {@link String} the url of web service * @param serverRegistry {@link ServerRegistry} the server information * @return {@link PostMethod} a post request */ private PostMethod createRequest(final String tempLogFolderLocation, final String webServiceURL, final ServerRegistry serverRegistry) { PostMethod postMethod = new PostMethod(webServiceURL); Part[] partArray = new Part[1]; String zipFolderPath = EphesoftStringUtil.concatenate(tempLogFolderLocation, File.separator, JAVA_APP_SERVER_LOG_FOLDER, File.separator, serverRegistry.getIpAddress()); partArray[0] = new StringPart(BatchInfoConstants.ZIP_FOLDER_PATH, zipFolderPath); LOGGER.debug(EphesoftStringUtil.concatenate("Log folder path for multiple server logs : ", zipFolderPath)); MultipartRequestEntity entity = new MultipartRequestEntity(partArray, postMethod.getParams()); postMethod.setRequestEntity(entity); return postMethod; }
From source file:com.zimbra.qa.unittest.TestFileUpload.java
private String postAndVerify(ZMailbox mbox, URI uri, boolean clearCookies, String requestId, String attContent) throws IOException { HttpClient client = mbox.getHttpClient(uri); if (clearCookies) { client.getState().clearCookies(); }/*from w ww .j a va 2s . co m*/ List<Part> parts = new ArrayList<Part>(); parts.add(new StringPart("requestId", requestId)); if (attContent != null) { parts.add(mbox.createAttachmentPart("test.txt", attContent.getBytes())); } PostMethod post = new PostMethod(uri.toString()); post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams())); int status = HttpClientUtil.executeMethod(client, post); assertEquals(200, status); String contentType = getHeaderValue(post, "Content-Type"); assertTrue(contentType, contentType.startsWith("text/html")); String content = post.getResponseBodyAsString(); post.releaseConnection(); return content; }
From source file:com.aptana.jira.core.JiraManager.java
/** * Adds an attachment to a JIRA ticket./*from w ww .j a v a 2s .co m*/ * * @param path * the path of the file to be attached * @param issue * the JIRA ticket * @throws JiraException */ public void addAttachment(IPath path, JiraIssue issue) throws JiraException { if (path == null || issue == null) { return; } if (user == null) { throw new JiraException(Messages.JiraManager_ERR_NotLoggedIn); } // Use Apache HTTPClient to POST the file HttpClient httpclient = new HttpClient(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user.getUsername(), user.getPassword()); httpclient.getState().setCredentials(new AuthScope(HOST_NAME, 443), creds); httpclient.getParams().setAuthenticationPreemptive(true); PostMethod filePost = null; try { filePost = new PostMethod(createAttachmentURL(issue)); File file = path.toFile(); // MUST USE "file" AS THE NAME!!! Part[] parts = { new FilePart("file", file) }; //$NON-NLS-1$ filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); filePost.setContentChunked(true); filePost.setDoAuthentication(true); // Special header to tell JIRA not to do XSFR checking filePost.setRequestHeader("X-Atlassian-Token", "nocheck"); //$NON-NLS-1$ //$NON-NLS-2$ int responseCode = httpclient.executeMethod(filePost); if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) { // TODO This is a JSON response that we should parse out "errorMessages" value(s) (its an array of // strings). throw new JiraException(filePost.getResponseBodyAsString()); } String json = filePost.getResponseBodyAsString(); IdeLog.logInfo(JiraCorePlugin.getDefault(), json); } catch (JiraException e) { throw e; } catch (Exception e) { throw new JiraException(e.getMessage(), e); } finally { if (filePost != null) { filePost.releaseConnection(); } } }