List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity
public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams)
From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java
/** * @param targetFile/*w w w. jav a 2 s . com*/ * @param fileName * @param isThumb * @return */ private synchronized boolean sendFile(final File targetFile, final String fileName, final boolean isThumb)/*, final boolean saveInCache)*/ { String targetURL = writeURLStr; PostMethod filePost = new PostMethod(targetURL); fillValuesArray(); try { log.debug("Uploading " + targetFile.getName() + " to " + targetURL); Part[] parts = { new FilePart(targetFile.getName(), targetFile), new StringPart("type", isThumb ? "T" : "O"), new StringPart("store", fileName), new StringPart("token", generateToken(fileName)), new StringPart("coll", values[0]), new StringPart("disp", values[1]), new StringPart("div", values[2]), new StringPart("inst", values[3]), }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); updateServerTimeDelta(filePost); //log.debug("---------------------------------------------------"); log.debug(filePost.getResponseBodyAsString()); //log.debug("---------------------------------------------------"); if (status == HttpStatus.SC_OK) { return true; } } catch (Exception ex) { log.error("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { filePost.releaseConnection(); } return false; }
From source file:edu.unc.lib.dl.fedora.ManagementClient.java
public String upload(byte[] bytes, String fileName) { String result = null;/*w w w . ja v a 2 s . c o m*/ // construct a post request to Fedora upload service String uploadURL = this.getFedoraContextUrl() + "/upload"; PostMethod post = new PostMethod(uploadURL); post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); log.debug("Uploading XML with forwarded groups: " + GroupsThreadStore.getGroupString()); post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString()); try { log.debug("Uploading to " + uploadURL); Part[] parts = { new FilePart("file", new ByteArrayPartSource(fileName, bytes)) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); int status = httpClient.executeMethod(post); StringWriter sw = new StringWriter(); try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) { int b; while ((b = in.read()) != -1) { pw.write(b); } } if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_ACCEPTED) { result = sw.toString().trim(); log.debug("Upload complete, response=" + result); } else { log.warn("Upload failed, response=" + HttpStatus.getStatusText(status)); log.debug(sw.toString().trim()); } } catch (Exception ex) { log.error("Upload failed due to error", ex); throw new ServiceException(ex); } finally { post.releaseConnection(); } return result; }
From source file:com.twelve.capital.external.feed.util.HttpImpl.java
protected void processPostMethod(PostMethod postMethod, List<Http.FilePart> fileParts, Map<String, String> parts) { if ((fileParts == null) || fileParts.isEmpty()) { if (parts != null) { for (Map.Entry<String, String> entry : parts.entrySet()) { String value = entry.getValue(); if (value != null) { postMethod.addParameter(entry.getKey(), value); }/*from www . j a v a 2 s. c o m*/ } } } else { List<Part> partsList = new ArrayList<Part>(); if (parts != null) { for (Map.Entry<String, String> entry : parts.entrySet()) { String value = entry.getValue(); if (value != null) { StringPart stringPart = new StringPart(entry.getKey(), value); partsList.add(stringPart); } } } for (Http.FilePart filePart : fileParts) { partsList.add(toCommonsFilePart(filePart)); } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( partsList.toArray(new Part[partsList.size()]), postMethod.getParams()); postMethod.setRequestEntity(multipartRequestEntity); } }
From source file:com.ning.http.client.providers.apache.ApacheAsyncHttpProvider.java
private MultipartRequestEntity createMultipartRequestEntity(String charset, List<Part> params, HttpMethodParams methodParams) throws FileNotFoundException { org.apache.commons.httpclient.methods.multipart.Part[] parts = new org.apache.commons.httpclient.methods.multipart.Part[params .size()];/*from ww w . ja v a2 s. c o m*/ int i = 0; for (Part part : params) { if (part instanceof StringPart) { parts[i] = new org.apache.commons.httpclient.methods.multipart.StringPart(part.getName(), ((StringPart) part).getValue(), charset); } else if (part instanceof FilePart) { parts[i] = new org.apache.commons.httpclient.methods.multipart.FilePart(part.getName(), ((FilePart) part).getFile(), ((FilePart) part).getMimeType(), ((FilePart) part).getCharSet()); } else if (part instanceof ByteArrayPart) { PartSource source = new ByteArrayPartSource(((ByteArrayPart) part).getFileName(), ((ByteArrayPart) part).getData()); parts[i] = new org.apache.commons.httpclient.methods.multipart.FilePart(part.getName(), source, ((ByteArrayPart) part).getMimeType(), ((ByteArrayPart) part).getCharSet()); } else if (part == null) { throw new NullPointerException("Part cannot be null"); } else { throw new IllegalArgumentException( String.format("Unsupported part type for multipart parameter %s", part.getName())); } ++i; } return new MultipartRequestEntity(parts, methodParams); }
From source file:edu.harvard.hmdc.dvnplugin.DVNOAIUrlCacher.java
private boolean processTermsOfUseResponse() throws IOException { //get the location header to find out where to redirect to String location = conn.getResponseHeaderValue("location"); releaseConnection();// w w w . j a v a 2 s . com GetMethod method = null; int status = 200; String jsessionid = null; try { logger.debug3("making Get method " + location + "&clicker=downloadServlet"); method = new GetMethod(location + "&clicker=downloadServlet"); // instruct method not to follow redirects: method.setFollowRedirects(false); logger.debug3("executing method"); status = getClient().executeMethod(method); InputStream in = method.getResponseBodyAsStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(in)); String line = null; String vdcid = null; String viewstate = null; String studyid = null; String remotefileid = null; String regexpJsession = "jsessionid=([^\"?&]*)"; String regexpViewState = "ViewState\" value=\"([^\"]*)\""; String regexpStudyId = "studyId\" value=\"([0-9]*)\""; String regexpRemoteFileId = "fileId=([0-9]*)"; Pattern patternJsession = Pattern.compile(regexpJsession); Pattern patternViewState = Pattern.compile(regexpViewState); Pattern patternStudyId = Pattern.compile(regexpStudyId); Pattern patternRemoteFileId = Pattern.compile(regexpRemoteFileId); Matcher matcher = null; matcher = patternRemoteFileId.matcher(fetchUrl); if (matcher.find()) { remotefileid = matcher.group(1); logger.debug3("TermsOfUse: found fileid " + remotefileid); } while ((line = rd.readLine()) != null) { matcher = patternJsession.matcher(line); if (matcher.find()) { jsessionid = matcher.group(1); logger.debug3("TermsOfUse: found jsessionid " + jsessionid); } matcher = patternViewState.matcher(line); if (matcher.find()) { viewstate = matcher.group(1); logger.debug3("TermsOfUse: found viewstate " + viewstate); } matcher = patternStudyId.matcher(line); if (matcher.find()) { studyid = matcher.group(1); logger.debug3("TermsOfUse: found studyid " + studyid); } } rd.close(); method.releaseConnection(); logger.debug3("released TermsOfUse GET connection"); //boolean notTrue = false; //if ( notTrue ) { if (jsessionid != null) { logger.debug3("TermsOfUse: obtained authorization information"); location = location.substring(0, location.indexOf("?")); logger.debug3("Connecting again " + location + ";jsessionid=" + jsessionid); PostMethod TOUpostMethod = new PostMethod(location + ";jsessionid=" + jsessionid); // instruct method not to follow redirects: TOUpostMethod.setFollowRedirects(false); Part[] parts = { new StringPart("pageName", "TermsOfUsePage"), new StringPart("content:termsOfUsePageView:form1:vdcId", ""), new StringPart("content:termsOfUsePageView:form1:studyId", studyid), new StringPart("content:termsOfUsePageView:form1:redirectPage", "/FileDownload/?fileId=" + remotefileid), new StringPart("content:termsOfUsePageView:form1:tou", "download"), new StringPart("content:termsOfUsePageView:form1:termsAccepted", "on"), new StringPart("content:termsOfUsePageView:form1:termsButton", "Continue"), new StringPart("content:termsOfUsePageView:form1_hidden", "content:termsOfUsePageView:form1_hidden'"), new StringPart("javax.faces.ViewState", viewstate) }; TOUpostMethod.addRequestHeader("Cookie", "JSESSIONID=" + jsessionid); TOUpostMethod.setRequestEntity(new MultipartRequestEntity(parts, TOUpostMethod.getParams())); status = getClient().executeMethod(TOUpostMethod); // TODO -- more diagnostics needed here! logger.debug3("TermsOfUse POST: received code " + status); if (status == 302) { String newLocation = null; for (int i = 0; i < TOUpostMethod.getResponseHeaders().length; i++) { String headerName = TOUpostMethod.getResponseHeaders()[i].getName(); if (headerName.equals("Location")) { newLocation = TOUpostMethod.getResponseHeaders()[i].getValue(); } } logger.debug3("TermsOfUse POST: redirected to " + newLocation); } TOUpostMethod.releaseConnection(); logger.debug3("released TermsOfUse POST connection"); } // } catch (IOException e) { //logger.debug2("failed to access TermsOfUse page", e); //return false; } catch (MalformedURLException ex) { logger.debug2("failed to acquire TermsOfUse authorization", ex); return false; } catch (IOException ex) { logger.debug2("failed to acquire TermsOfUse authorization", ex); return false; } catch (RuntimeException e) { logger.warning("failed to acquire TermsOfUse authorization", e); return false; } // OK, we can try again now! logger.debug3("trying to access the file again " + fetchUrl); try { conn = makeConnection(fetchUrl, connectionPool); if (localAddr != null) { conn.setLocalAddress(localAddr); } if (reqProps != null) { for (Iterator iter = reqProps.keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); conn.setRequestProperty(key, reqProps.getProperty(key)); } } conn.setRequestProperty("user-agent", LockssDaemon.getUserAgent()); String myCookie = "JSESSIONID=" + jsessionid; logger.debug3("setting cookie: " + myCookie); conn.addRequestProperty("Cookie", myCookie); logger.debug3("executing request"); conn.execute(); } catch (MalformedURLException ex) { logger.debug2("openConnection", ex); throw resultMap.getMalformedURLException(ex); } catch (IOException ex) { logger.debug2("openConnection", ex); throw resultMap.getHostException(ex); } catch (RuntimeException e) { logger.warning("openConnection: unexpected exception", e); throw e; } return true; }
From source file:com.adobe.share.api.ShareAPI.java
/** * Prepares a new HTTP multi-part POST request for uploading files. The * format for these requests adheres to the standard RFC1867. For details, * see http://www.ietf.org/rfc/rfc1867.txt. * * @param user the user/*from w w w. j a v a2 s. co m*/ * @param url the url * @param anon the anon * @param requestBody the request body * @param file the file * * @return the post method * * @throws FileNotFoundException the file not found exception */ protected final PostMethod createFilePostRequest(final ShareAPIUser user, final String url, final boolean anon, final String requestBody, final File file) throws FileNotFoundException { PostMethod filePost = new PostMethod(url); StringPart p1 = new StringPart("request", requestBody); Part[] parts = { p1, new FilePart("file", file.getName(), file) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); filePost.setRequestHeader("Authorization", generateAuthorization(user, anon, "POST", url)); return filePost; }
From source file:com.apatar.rss.RssNode.java
private void publishing() throws HttpException, IOException, ApatarException { Object obj = ApplicationData.getProject().getProjectData(getConnectionDataID()).getData(); if (!(obj instanceof CreateNewParams)) { return;/*w ww. j a v a 2 s .co m*/ } CreateNewParams params = (CreateNewParams) obj; PostMethod method = new PostMethod(PUBLISH_URL); String tempFolderName = "publish/"; File tempFolder = new File(tempFolderName); if (!tempFolder.exists()) { tempFolder.mkdir(); } String fileName = rssTitle == null ? "temp" : rssTitle.replaceAll("[|/\\:*?\"<> ]", "_") + ".aptr"; ReadWriteXMLDataUi rwXMLdata = new ReadWriteXMLDataUi(); File tempFile = rwXMLdata.writeXMLData(fileName.toString(), ApplicationData.getProject(), true); int partCount = 15; if (publishId != null) { partCount++; } Part[] parts = new Part[partCount]; parts[0] = new StringPart("option", "com_remository"); parts[1] = new StringPart("task", ""); parts[2] = new StringPart("element", "component"); parts[3] = new StringPart("client", ""); parts[4] = new StringPart("oldid", "0"); parts[5] = new FilePart("userfile", tempFile); parts[6] = new StringPart("containerid", "15"); parts[7] = new StringPart("filetitle", rssTitle == null ? "" : rssTitle); parts[8] = new StringPart("description", description == null ? "" : description); parts[9] = new StringPart("smalldesc", description == null ? "" : description); parts[10] = new StringPart("filetags", "RSS"); parts[11] = new StringPart("pubExternal", "true"); parts[12] = new StringPart("username", username); parts[13] = new StringPart("password", CoreUtils.getMD5(password)); parts[14] = new FilePart("rssfile", params.getFile()); if (publishId != null) { parts[15] = new StringPart("dmid", publishId); } method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Upload failed, response=" + HttpStatus.getStatusText(status)); } else { if (publishId == null) { StringBuffer buff = new StringBuffer(method.getResponseBodyAsString()); Matcher matcher = ApatarRegExp.getMatcher("<meta name=\"dmid\" content=\"[a-zA-Z_0-9]+\"", buff.toString()); while (matcher.find()) { String result = matcher.group(); if (result == null || result.equals("")) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Publishing error"); return; } result = result.replaceFirst("<meta name=\"dmid\" content=\"", ""); result = result.replace("\"", ""); publishId = result; return; } } JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Publishing error"); } }
From source file:fedora.test.api.TestRESTAPI.java
private HttpResponse putOrPost(String method, Object requestContent, boolean authenticate) throws Exception { if (url == null || url.length() == 0) { throw new IllegalArgumentException("url must be a non-empty value"); } else if (!(url.startsWith("http://") || url.startsWith("https://"))) { url = getBaseURL() + url;/*w w w. ja va2 s. c om*/ } EntityEnclosingMethod httpMethod = null; try { if (method.equals("PUT")) { httpMethod = new PutMethod(url); } else if (method.equals("POST")) { httpMethod = new PostMethod(url); } else { throw new IllegalArgumentException("method must be one of PUT or POST."); } httpMethod.setDoAuthentication(authenticate); httpMethod.getParams().setParameter("Connection", "Keep-Alive"); if (requestContent != null) { httpMethod.setContentChunked(chunked); if (requestContent instanceof String) { httpMethod.setRequestEntity( new StringRequestEntity((String) requestContent, "text/xml", "utf-8")); } else if (requestContent instanceof File) { Part[] parts = { new StringPart("param_name", "value"), new FilePart(((File) requestContent).getName(), (File) requestContent) }; httpMethod.setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams())); } else { throw new IllegalArgumentException("requestContent must be a String or File"); } } getClient(authenticate).executeMethod(httpMethod); return new HttpResponse(httpMethod); } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
public byte[] getData(Context context) throws IOException, EngineException { HttpMethod method = null;//from w ww . java2 s. c om try { // Fire event for plugins long t0 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context); // Retrieving httpState getHttpState(context); Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array..."); Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl); // Setting the referer referer = sUrl; URL url = null; url = new URL(sUrl); // Proxy configuration Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url); Engine.logBeans.debug("(HttpConnector) Https: " + https); String host = ""; int port = -1; if (sUrl.toLowerCase().startsWith("https:")) { if (!https) { Engine.logBeans.debug("(HttpConnector) Setting up SSL properties"); certificateManager.collectStoreInformation(context); } url = new URL(sUrl); host = url.getHost(); port = url.getPort(); if (port == -1) port = 443; Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); Engine.logBeans .debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged); if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != port)) { Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket"); Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, this.trustAllServerCertificates), port); hostConfiguration.setHost(host, port, myhttps); } sUrl = url.getFile(); Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl); } else { url = new URL(sUrl); host = url.getHost(); port = url.getPort(); Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); hostConfiguration.setHost(host, port); } AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction; // Retrieve HTTP method HttpMethodType httpVerb = httpTransaction.getHttpVerb(); String sHttpVerb = httpVerb.name(); final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb(); if (sCustomHttpVerb.length() > 0) { Engine.logBeans.debug( "(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'"); switch (httpVerb) { case GET: method = new GetMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case POST: method = new PostMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case PUT: method = new PutMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case DELETE: method = new DeleteMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case HEAD: method = new HeadMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case OPTIONS: method = new OptionsMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case TRACE: method = new TraceMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; } } else { Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb); switch (httpVerb) { case GET: method = new GetMethod(sUrl); break; case POST: method = new PostMethod(sUrl); break; case PUT: method = new PutMethod(sUrl); break; case DELETE: method = new DeleteMethod(sUrl); break; case HEAD: method = new HeadMethod(sUrl); break; case OPTIONS: method = new OptionsMethod(sUrl); break; case TRACE: method = new TraceMethod(sUrl); break; } } // Setting HTTP parameters boolean hasUserAgent = false; for (List<String> httpParameter : httpParameters) { String key = httpParameter.get(0); String value = httpParameter.get(1); if (key.equalsIgnoreCase("host") && !value.equals(host)) { value = host; } if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) { method.setRequestHeader(key, value); } if (HeaderName.UserAgent.is(key)) { hasUserAgent = true; } } // set user-agent header if not found if (!hasUserAgent) { HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context)); } // Setting POST or PUT parameters if any Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data"); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method; AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject; if (doMultipartFormData) { RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction .getVariable(Parameter.HttpBody.getName()); if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) { String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName()); String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName()); File file = new File(filepath); if (file.exists()) { HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType)); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } else { List<Part> parts = new LinkedList<Part>(); for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if ("POST".equals(httpVariable.getHttpMethod())) { Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addFormDataPart(parts, httpVariable, httpVariableValue); } } } else { addFormDataPart(parts, httpVariable, httpObjectVariableValue); } } } } MultipartRequestEntity mre = new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams()); HeaderName.ContentType.setRequestHeader(method, mre.getContentType()); entityEnclosingMethod.setRequestEntity(mre); } } else if (MimeType.TextXml.is(contentType)) { final MimeMultipart[] mp = { null }; for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) { Engine.logBeans.trace( "(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM"); MimeMultipart mimeMultipart = mp[0]; try { if (mimeMultipart == null) { Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request"); mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\""); MimeBodyPart bp = new MimeBodyPart(); bp.setText(postQuery, "UTF-8"); bp.setHeader(HeaderName.ContentType.value(), contentType); mimeMultipart.addBodyPart(bp); } Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addMtomPart(mimeMultipart, httpVariable, httpVariableValue); } } } else { addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue); } mp[0] = mimeMultipart; } catch (Exception e) { Engine.logBeans.warn( "(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(), e); } } } } if (mp[0] == null) { entityEnclosingMethod.setRequestEntity( new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8")); } else { Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: " + mp[0].getContentType()); HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType()); entityEnclosingMethod.setRequestEntity(new RequestEntity() { @Override public void writeRequest(OutputStream outputStream) throws IOException { try { mp[0].writeTo(outputStream); } catch (MessagingException e) { new IOException(e); } } @Override public boolean isRepeatable() { return true; } @Override public String getContentType() { return mp[0].getContentType(); } @Override public long getContentLength() { return -1; } }); } } else { String charset = httpTransaction.getComputedUrlEncodingCharset(); HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod .setRequestEntity(new StringRequestEntity(postQuery, contentType, charset)); } } // Getting the result Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body"); byte[] result = executeMethod(method, context); Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0)); // Fire event for plugins long t1 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1); fireDataChanged(new ConnectorEvent(this, result)); return result; } finally { if (method != null) method.releaseConnection(); } }
From source file:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java
private String dvnRemoteAuth(String remoteHost) { // if successful, this method will return the JSESSION string // for the authenticated session on the remote DVN. String remoteJsessionid = null; String remoteDvnUser = null;//from www .j a va 2 s . c o m String remoteDvnPw = null; GetMethod loginGetMethod = null; PostMethod loginPostMethod = null; RemoteAccessAuth remoteAuth = studyService.lookupRemoteAuthByHost(remoteHost); if (remoteAuth == null) { return null; } remoteDvnUser = remoteAuth.getAuthCred1(); remoteDvnPw = remoteAuth.getAuthCred2(); if (remoteDvnUser == null || remoteDvnPw == null) { return null; } int status = 0; try { String remoteAuthUrl = "http://" + remoteHost + "/dvn/faces/login/LoginPage.xhtml"; loginGetMethod = new GetMethod(remoteAuthUrl); loginGetMethod.setFollowRedirects(false); status = getClient().executeMethod(loginGetMethod); InputStream in = loginGetMethod.getResponseBodyAsStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(in)); String line = null; String viewstate = null; String regexpJsession = "jsessionid=([^\"?&]*)"; String regexpViewState = "ViewState\" value=\"([^\"]*)\""; Pattern patternJsession = Pattern.compile(regexpJsession); Pattern patternViewState = Pattern.compile(regexpViewState); Matcher matcher = null; while ((line = rd.readLine()) != null) { matcher = patternJsession.matcher(line); if (matcher.find()) { remoteJsessionid = matcher.group(1); } matcher = patternViewState.matcher(line); if (matcher.find()) { viewstate = matcher.group(1); } } rd.close(); loginGetMethod.releaseConnection(); if (remoteJsessionid != null) { // We have found Jsession; // now we can log in, // has to be a POST method: loginPostMethod = new PostMethod(remoteAuthUrl + ";jsessionid=" + remoteJsessionid); loginPostMethod.setFollowRedirects(false); Part[] parts = { new StringPart("vanillaLoginForm:vdcId", ""), new StringPart("vanillaLoginForm:username", remoteDvnUser), new StringPart("vanillaLoginForm:password", remoteDvnPw), new StringPart("vanillaLoginForm_hidden", "vanillaLoginForm_hidden"), new StringPart("vanillaLoginForm:button1", "Log in"), new StringPart("javax.faces.ViewState", viewstate) }; loginPostMethod.setRequestEntity(new MultipartRequestEntity(parts, loginPostMethod.getParams())); loginPostMethod.addRequestHeader("Cookie", "JSESSIONID=" + remoteJsessionid); status = getClient().executeMethod(loginPostMethod); String redirectLocation = null; if (status == 302) { for (int i = 0; i < loginPostMethod.getResponseHeaders().length; i++) { String headerName = loginPostMethod.getResponseHeaders()[i].getName(); if (headerName.equals("Location")) { redirectLocation = loginPostMethod.getResponseHeaders()[i].getValue(); } } } loginPostMethod.releaseConnection(); int counter = 0; int redirectLimit = 20; // number of redirects we are willing to follow before we give up. while (status == 302 && counter < redirectLimit) { if (counter > 0) { for (int i = 0; i < loginGetMethod.getResponseHeaders().length; i++) { String headerName = loginGetMethod.getResponseHeaders()[i].getName(); if (headerName.equals("Location")) { redirectLocation = loginGetMethod.getResponseHeaders()[i].getValue(); } } } // try following redirects until we get a static page, // or until we exceed the hoop limit. if (redirectLocation.matches(".*TermsOfUsePage.*")) { loginGetMethod = remoteAccessTOU(redirectLocation + "&clicker=downloadServlet", remoteJsessionid, null, null); if (loginGetMethod != null) { status = loginGetMethod.getStatusCode(); } } else { loginGetMethod = new GetMethod(redirectLocation); loginGetMethod.setFollowRedirects(false); loginGetMethod.addRequestHeader("Cookie", "JSESSIONID=" + remoteJsessionid); status = getClient().executeMethod(loginGetMethod); //InputStream in = loginGetMethod.getResponseBodyAsStream(); //BufferedReader rd = new BufferedReader(new InputStreamReader(in)); //rd.close(); loginGetMethod.releaseConnection(); counter++; } } } } catch (IOException ex) { if (loginGetMethod != null) { loginGetMethod.releaseConnection(); } if (loginPostMethod != null) { loginPostMethod.releaseConnection(); } return null; } return remoteJsessionid; }