List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text, Charset charset) throws UnsupportedEncodingException
From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java
public void changeAppIcon(String applicationHash, File appIcon) throws AppCloudIntegrationTestException { HttpClient httpclient = null;/*from w w w . j av a 2 s .co m*/ org.apache.http.HttpResponse response = null; try { httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httppost = new HttpPost(this.endpoint); httppost.setConfig(requestConfig); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(PARAM_NAME_CHANGE_ICON, new FileBody(appIcon)); builder.addPart(PARAM_NAME_ACTION, new StringBody(CHANGE_APP_ICON_ACTION, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_HASH_ID, new StringBody(applicationHash, ContentType.TEXT_PLAIN)); httppost.setEntity(builder.build()); httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE)); response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity()); throw new AppCloudIntegrationTestException("Update app icon failed " + result); } } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) { // In most of the cases, even though connection is timed out, actual activity is completed. // And this will be asserted so if it failed due to a valid case, it will be captured. log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1); } catch (IOException e) { log.error("Failed to invoke app icon update API.", e); throw new AppCloudIntegrationTestException("Failed to invoke app icon update API.", e); } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(httpclient); } }
From source file:de.tu_dortmund.ub.data.dswarm.Task.java
/** * upload a file and update an existing resource with it * * @param resourceUUID/*from www . j av a 2 s . c om*/ * @param filename * @param name * @param description * @return responseJson * @throws Exception */ private String uploadFileAndUpdateResource(String resourceUUID, String filename, String name, String description) throws Exception { if (null == resourceUUID) throw new Exception("ID of the resource to update was null."); String responseJson = null; String file = config.getProperty("resource.watchfolder") + File.separatorChar + filename; // ggf. Preprocessing: insert CDATA in XML and write new XML file to tmp folder if (Boolean.parseBoolean(config.getProperty("resource.preprocessing"))) { Document document = new SAXBuilder().build(new File(file)); file = config.getProperty("preprocessing.folder") + File.separatorChar + UUID.randomUUID() + ".xml"; XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new FileWriter(file)); out.output(new SAXBuilder().build(new StringReader( XmlTransformer.xmlOutputter(document, config.getProperty("preprocessing.xslt"), null))), bufferedWriter); } finally { if (bufferedWriter != null) { bufferedWriter.close(); } } } // upload CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPut httpPut = new HttpPut(config.getProperty("engine.dswarm.api") + "resources/" + resourceUUID); FileBody fileBody = new FileBody(new File(file)); StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN); StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fileBody) .addPart("name", stringBodyForName).addPart("description", stringBodyForDescription).build(); httpPut.setEntity(reqEntity); logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpPut.getRequestLine()); CloseableHttpResponse httpResponse = httpclient.execute(httpPut); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { logger.info("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, "UTF-8"); responseJson = writer.toString(); logger.info("[" + config.getProperty("service.name") + "] responseJson : " + responseJson); break; } default: { logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); } } EntityUtils.consume(httpEntity); } finally { httpResponse.close(); } } finally { httpclient.close(); } return responseJson; }
From source file:immf.ImodeNetClient.java
/** * ????//w w w. j a v a 2s . c o m * * @param fileIdList * @param contentType * @param filename * @param data */ private synchronized String sendAttachFile(List<String> fileIdList, boolean isInline, String contentType, String filename, byte[] data) throws IOException { MultipartEntity multi = new MultipartEntity(); int i = 0; for (Iterator<String> iterator = fileIdList.iterator(); iterator.hasNext(); i++) { String fileId = (String) iterator.next(); try { multi.addPart("tmpfile(" + i + ").id", new StringBody(fileId, Charset.forName("UTF-8"))); } catch (Exception e) { log.error("sendAttachFile (" + i + ")", e); } } multi.addPart("stmpfile.data", new ByteArrayBody(data, contentType, filename)); String url = null; if (isInline) { url = ImgupUrl; } else { url = FileupUrl; } HttpPost post = new HttpPost(url + "?pwsp=" + this.getPwspQuery()); try { addDumyHeader(post); post.setEntity(multi); HttpResponse res = this.executeHttp(post); if (res.getStatusLine().getStatusCode() != 200) { log.warn("attachefile error. " + filename + "/" + res.getStatusLine().getStatusCode() + "/" + res.getStatusLine().getReasonPhrase()); throw new IOException(filename + " error. " + res.getStatusLine().getStatusCode() + "/" + res.getStatusLine().getReasonPhrase()); } if (!isJson(res)) { log.warn("Fileupload??JSON??????"); if (res != null) log.debug(toStringBody(res)); throw new IOException("Bad attached file"); } JSONObject json = JSONObject.fromObject(toStringBody(res)); String result = json.getJSONObject("common").getString("result"); if (!result.equals("PW1000")) { log.debug(json.toString(2)); throw new IOException("Bad fileupload[" + filename + "] response " + result); } // ?ID? String objName = null; if (isInline) { objName = "listPcimg"; } else { objName = "file"; } String fileId = json.getJSONObject("data").getJSONObject(objName).getString("id"); fileIdList.add(fileId); return fileId; } finally { post.abort(); } }
From source file:lucee.runtime.tag.Http4.java
private void _doEndTag(Struct cfhttp) throws PageException, IOException { BasicHttpParams params = new BasicHttpParams(); DefaultHttpClient client = HTTPEngine4Impl.createClient(params, redirect ? HTTPEngine.MAX_REDIRECT : 0); ConfigWeb cw = pageContext.getConfig(); HttpRequestBase req = null;/*from w ww.j ava 2 s. c o m*/ HttpContext httpContext = null; //HttpRequestBase req = init(pageContext.getConfig(),this,client,params,url,port); { if (StringUtil.isEmpty(charset, true)) charset = ((PageContextImpl) pageContext).getWebCharset().name(); else charset = charset.trim(); // check if has fileUploads boolean doUploadFile = false; for (int i = 0; i < this.params.size(); i++) { if ((this.params.get(i)).getType().equalsIgnoreCase("file")) { doUploadFile = true; break; } } // parse url (also query string) int len = this.params.size(); StringBuilder sbQS = new StringBuilder(); for (int i = 0; i < len; i++) { HttpParamBean param = this.params.get(i); String type = param.getType(); // URL if (type.equals("url")) { if (sbQS.length() > 0) sbQS.append('&'); sbQS.append(param.getEncoded() ? HttpImpl.urlenc(param.getName(), charset) : param.getName()); sbQS.append('='); sbQS.append(param.getEncoded() ? HttpImpl.urlenc(param.getValueAsString(), charset) : param.getValueAsString()); } } String host = null; HttpHost httpHost; try { URL _url = HTTPUtil.toURL(url, port, encoded); httpHost = new HttpHost(_url.getHost(), _url.getPort()); host = _url.getHost(); url = _url.toExternalForm(); if (sbQS.length() > 0) { // no existing QS if (StringUtil.isEmpty(_url.getQuery())) { url += "?" + sbQS; } else { url += "&" + sbQS; } } } catch (MalformedURLException mue) { throw Caster.toPageException(mue); } // select best matching method (get,post, post multpart (file)) boolean isBinary = false; boolean doMultiPart = doUploadFile || this.multiPart; HttpPost post = null; HttpEntityEnclosingRequest eem = null; if (this.method == METHOD_GET) { req = new HttpGet(url); } else if (this.method == METHOD_HEAD) { req = new HttpHead(url); } else if (this.method == METHOD_DELETE) { isBinary = true; req = new HttpDelete(url); } else if (this.method == METHOD_PUT) { isBinary = true; HttpPut put = new HttpPut(url); req = put; eem = put; } else if (this.method == METHOD_TRACE) { isBinary = true; req = new HttpTrace(url); } else if (this.method == METHOD_OPTIONS) { isBinary = true; req = new HttpOptions(url); } else if (this.method == METHOD_PATCH) { isBinary = true; eem = HTTPPatchFactory.getHTTPPatch(url); req = (HttpRequestBase) eem; } else { isBinary = true; post = new HttpPost(url); req = post; eem = post; } boolean hasForm = false; boolean hasBody = false; boolean hasContentType = false; // Set http params ArrayList<FormBodyPart> parts = new ArrayList<FormBodyPart>(); StringBuilder acceptEncoding = new StringBuilder(); java.util.List<NameValuePair> postParam = post != null ? new ArrayList<NameValuePair>() : null; for (int i = 0; i < len; i++) { HttpParamBean param = this.params.get(i); String type = param.getType(); // URL if (type.equals("url")) { //listQS.add(new BasicNameValuePair(translateEncoding(param.getName(), http.charset),translateEncoding(param.getValueAsString(), http.charset))); } // Form else if (type.equals("formfield") || type.equals("form")) { hasForm = true; if (this.method == METHOD_GET) throw new ApplicationException( "httpparam with type formfield can only be used when the method attribute of the parent http tag is set to post"); if (post != null) { if (doMultiPart) { parts.add(new FormBodyPart(param.getName(), new StringBody(param.getValueAsString(), CharsetUtil.toCharset(charset)))); } else { postParam.add(new BasicNameValuePair(param.getName(), param.getValueAsString())); } } //else if(multi!=null)multi.addParameter(param.getName(),param.getValueAsString()); } // CGI else if (type.equals("cgi")) { if (param.getEncoded()) req.addHeader(HttpImpl.urlenc(param.getName(), charset), HttpImpl.urlenc(param.getValueAsString(), charset)); else req.addHeader(param.getName(), param.getValueAsString()); } // Header else if (type.startsWith("head")) { if (param.getName().equalsIgnoreCase("content-type")) hasContentType = true; if (param.getName().equalsIgnoreCase("Content-Length")) { } else if (param.getName().equalsIgnoreCase("Accept-Encoding")) { acceptEncoding.append(HttpImpl.headerValue(param.getValueAsString())); acceptEncoding.append(", "); } else req.addHeader(param.getName(), HttpImpl.headerValue(param.getValueAsString())); } // Cookie else if (type.equals("cookie")) { HTTPEngine4Impl.addCookie(client, host, param.getName(), param.getValueAsString(), "/", charset); } // File else if (type.equals("file")) { hasForm = true; if (this.method == METHOD_GET) throw new ApplicationException( "httpparam type file can't only be used, when method of the tag http equal post"); String strCT = HttpImpl.getContentType(param); ContentType ct = HTTPUtil.toContentType(strCT, null); String mt = "text/xml"; if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true)) mt = ct.getMimeType(); String cs = charset; if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true)) cs = ct.getCharset(); if (doMultiPart) { try { Resource res = param.getFile(); parts.add(new FormBodyPart(param.getName(), new ResourceBody(res, mt, res.getName(), cs))); //parts.add(new ResourcePart(param.getName(),new ResourcePartSource(param.getFile()),getContentType(param),_charset)); } catch (FileNotFoundException e) { throw new ApplicationException("can't upload file, path is invalid", e.getMessage()); } } } // XML else if (type.equals("xml")) { ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null); String mt = "text/xml"; if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true)) mt = ct.getMimeType(); String cs = charset; if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true)) cs = ct.getCharset(); hasBody = true; hasContentType = true; req.addHeader("Content-type", mt + "; charset=" + cs); if (eem == null) throw new ApplicationException("type xml is only supported for type post and put"); HTTPEngine4Impl.setBody(eem, param.getValueAsString(), mt, cs); } // Body else if (type.equals("body")) { ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null); String mt = null; if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true)) mt = ct.getMimeType(); String cs = charset; if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true)) cs = ct.getCharset(); hasBody = true; if (eem == null) throw new ApplicationException("type body is only supported for type post and put"); HTTPEngine4Impl.setBody(eem, param.getValue(), mt, cs); } else { throw new ApplicationException("invalid type [" + type + "]"); } } // post params if (postParam != null && postParam.size() > 0) post.setEntity(new org.apache.http.client.entity.UrlEncodedFormEntity(postParam, charset)); if (compression) { acceptEncoding.append("gzip"); } else { acceptEncoding.append("deflate;q=0"); req.setHeader("TE", "deflate;q=0"); } req.setHeader("Accept-Encoding", acceptEncoding.toString()); // multipart if (doMultiPart && eem != null) { hasContentType = true; boolean doIt = true; if (!this.multiPart && parts.size() == 1) { ContentBody body = parts.get(0).getBody(); if (body instanceof StringBody) { StringBody sb = (StringBody) body; try { org.apache.http.entity.ContentType ct = org.apache.http.entity.ContentType .create(sb.getMimeType(), sb.getCharset()); String str = IOUtil.toString(sb.getReader()); StringEntity entity = new StringEntity(str, ct); eem.setEntity(entity); } catch (IOException e) { throw Caster.toPageException(e); } doIt = false; } } if (doIt) { MultipartEntity mpe = new MultipartEntity(HttpMultipartMode.STRICT); Iterator<FormBodyPart> it = parts.iterator(); while (it.hasNext()) { FormBodyPart part = it.next(); mpe.addPart(part.getName(), part.getBody()); } eem.setEntity(mpe); } //eem.setRequestEntity(new MultipartRequestEntityFlex(parts.toArray(new Part[parts.size()]), eem.getParams(),http.multiPartType)); } if (hasBody && hasForm) throw new ApplicationException("mixing httpparam type file/formfield and body/XML is not allowed"); if (!hasContentType) { if (isBinary) { if (hasBody) req.addHeader("Content-type", "application/octet-stream"); else req.addHeader("Content-type", "application/x-www-form-urlencoded; charset=" + charset); } else { if (hasBody) req.addHeader("Content-type", "text/html; charset=" + charset); } } // set User Agent if (!HttpImpl.hasHeaderIgnoreCase(req, "User-Agent")) req.setHeader("User-Agent", this.useragent); // set timeout if (this.timeout > 0L) HTTPEngine4Impl.setTimeout(params, (int) this.timeout); // set Username and Password if (this.username != null) { if (this.password == null) this.password = ""; if (AUTH_TYPE_NTLM == this.authType) { if (StringUtil.isEmpty(this.workStation, true)) throw new ApplicationException( "attribute workstation is required when authentication type is [NTLM]"); if (StringUtil.isEmpty(this.domain, true)) throw new ApplicationException( "attribute domain is required when authentication type is [NTLM]"); HTTPEngine4Impl.setNTCredentials(client, this.username, this.password, this.workStation, this.domain); } else httpContext = HTTPEngine4Impl.setCredentials(client, httpHost, this.username, this.password, preauth); } // set Proxy ProxyData proxy = null; if (!StringUtil.isEmpty(this.proxyserver)) { proxy = ProxyDataImpl.getInstance(this.proxyserver, this.proxyport, this.proxyuser, this.proxypassword); } if (pageContext.getConfig().isProxyEnableFor(host)) { proxy = pageContext.getConfig().getProxyData(); } HTTPEngine4Impl.setProxy(client, req, proxy); } try { if (httpContext == null) httpContext = new BasicHttpContext(); /////////////////////////////////////////// EXECUTE ///////////////////////////////////////////////// Executor4 e = new Executor4(this, client, httpContext, req, redirect); HTTPResponse4Impl rsp = null; if (timeout < 0) { try { rsp = e.execute(httpContext); } catch (Throwable t) { if (!throwonerror) { setUnknownHost(cfhttp, t); return; } throw toPageException(t); } } else { e.start(); try { synchronized (this) {//print.err(timeout); this.wait(timeout); } } catch (InterruptedException ie) { throw Caster.toPageException(ie); } if (e.t != null) { if (!throwonerror) { setUnknownHost(cfhttp, e.t); return; } throw toPageException(e.t); } rsp = e.response; if (!e.done) { req.abort(); if (throwonerror) throw new HTTPException("408 Request Time-out", "a timeout occurred in tag http", 408, "Time-out", rsp.getURL()); setRequestTimeout(cfhttp); return; //throw new ApplicationException("timeout"); } } /////////////////////////////////////////// EXECUTE ///////////////////////////////////////////////// Charset responseCharset = CharsetUtil.toCharset(rsp.getCharset()); // Write Response Scope //String rawHeader=httpMethod.getStatusLine().toString(); String mimetype = null; String contentEncoding = null; // status code cfhttp.set(STATUSCODE, ((rsp.getStatusCode() + " " + rsp.getStatusText()).trim())); cfhttp.set(STATUS_CODE, new Double(rsp.getStatusCode())); cfhttp.set(STATUS_TEXT, (rsp.getStatusText())); cfhttp.set(HTTP_VERSION, (rsp.getProtocolVersion())); //responseHeader lucee.commons.net.http.Header[] headers = rsp.getAllHeaders(); StringBuffer raw = new StringBuffer(rsp.getStatusLine() + " "); Struct responseHeader = new StructImpl(); Struct cookie; Array setCookie = new ArrayImpl(); Query cookies = new QueryImpl( new String[] { "name", "value", "path", "domain", "expires", "secure", "httpOnly" }, 0, "cookies"); for (int i = 0; i < headers.length; i++) { lucee.commons.net.http.Header header = headers[i]; //print.ln(header); raw.append(header.toString() + " "); if (header.getName().equalsIgnoreCase("Set-Cookie")) { setCookie.append(header.getValue()); parseCookie(cookies, header.getValue()); } else { //print.ln(header.getName()+"-"+header.getValue()); Object value = responseHeader.get(KeyImpl.getInstance(header.getName()), null); if (value == null) responseHeader.set(KeyImpl.getInstance(header.getName()), header.getValue()); else { Array arr = null; if (value instanceof Array) { arr = (Array) value; } else { arr = new ArrayImpl(); responseHeader.set(KeyImpl.getInstance(header.getName()), arr); arr.appendEL(value); } arr.appendEL(header.getValue()); } } // Content-Type if (header.getName().equalsIgnoreCase("Content-Type")) { mimetype = header.getValue(); if (mimetype == null) mimetype = NO_MIMETYPE; } // Content-Encoding if (header.getName().equalsIgnoreCase("Content-Encoding")) { contentEncoding = header.getValue(); } } cfhttp.set(RESPONSEHEADER, responseHeader); cfhttp.set(KeyConstants._cookies, cookies); responseHeader.set(STATUS_CODE, new Double(rsp.getStatusCode())); responseHeader.set(EXPLANATION, (rsp.getStatusText())); if (setCookie.size() > 0) responseHeader.set(SET_COOKIE, setCookie); // is text boolean isText = mimetype == null || mimetype == NO_MIMETYPE || HTTPUtil.isTextMimeType(mimetype); // is multipart boolean isMultipart = MultiPartResponseUtils.isMultipart(mimetype); cfhttp.set(KeyConstants._text, Caster.toBoolean(isText)); // mimetype charset //boolean responseProvideCharset=false; if (!StringUtil.isEmpty(mimetype, true)) { if (isText) { String[] types = HTTPUtil.splitMimeTypeAndCharset(mimetype, null); if (types[0] != null) cfhttp.set(KeyConstants._mimetype, types[0]); if (types[1] != null) cfhttp.set(CHARSET, types[1]); } else cfhttp.set(KeyConstants._mimetype, mimetype); } else cfhttp.set(KeyConstants._mimetype, NO_MIMETYPE); // File Resource file = null; if (strFile != null && strPath != null) { file = ResourceUtil.toResourceNotExisting(pageContext, strPath).getRealResource(strFile); } else if (strFile != null) { file = ResourceUtil.toResourceNotExisting(pageContext, strFile); } else if (strPath != null) { file = ResourceUtil.toResourceNotExisting(pageContext, strPath); //Resource dir = file.getParentResource(); if (file.isDirectory()) { file = file.getRealResource(req.getURI().getPath());// TODO was getName() ->http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/URI.html#getName() } } if (file != null) pageContext.getConfig().getSecurityManager().checkFileLocation(file); // filecontent InputStream is = null; if (isText && getAsBinary != GET_AS_BINARY_YES) { String str; try { // read content if (method != METHOD_HEAD) { is = rsp.getContentAsStream(); if (is != null && HttpImpl.isGzipEncoded(contentEncoding)) is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is) : new GZIPInputStream(is); } try { try { str = is == null ? "" : IOUtil.toString(is, responseCharset); } catch (EOFException eof) { if (is instanceof CachingGZIPInputStream) { str = IOUtil.toString(is = ((CachingGZIPInputStream) is).getRawData(), responseCharset); } else throw eof; } } catch (UnsupportedEncodingException uee) { str = IOUtil.toString(is, (Charset) null); } } catch (IOException ioe) { throw Caster.toPageException(ioe); } finally { IOUtil.closeEL(is); } if (str == null) str = ""; if (resolveurl) { //if(e.redirectURL!=null)url=e.redirectURL.toExternalForm(); str = new URLResolver().transform(str, e.response.getTargetURL(), false); } cfhttp.set(FILE_CONTENT, str); try { if (file != null) { IOUtil.write(file, str, ((PageContextImpl) pageContext).getWebCharset(), false); } } catch (IOException e1) { } if (name != null) { Query qry = CSVParser.toQuery(str, delimiter, textqualifier, columns, firstrowasheaders); pageContext.setVariable(name, qry); } } // Binary else { byte[] barr = null; if (HttpImpl.isGzipEncoded(contentEncoding)) { if (method != METHOD_HEAD) { is = rsp.getContentAsStream(); is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is) : new GZIPInputStream(is); } try { try { barr = is == null ? new byte[0] : IOUtil.toBytes(is); } catch (EOFException eof) { if (is instanceof CachingGZIPInputStream) barr = IOUtil.toBytes(((CachingGZIPInputStream) is).getRawData()); else throw eof; } } catch (IOException t) { throw Caster.toPageException(t); } finally { IOUtil.closeEL(is); } } else { try { if (method != METHOD_HEAD) barr = rsp.getContentAsByteArray(); else barr = new byte[0]; } catch (IOException t) { throw Caster.toPageException(t); } } //IF Multipart response get file content and parse parts if (barr != null) { if (isMultipart) { cfhttp.set(FILE_CONTENT, MultiPartResponseUtils.getParts(barr, mimetype)); } else { cfhttp.set(FILE_CONTENT, barr); } } else cfhttp.set(FILE_CONTENT, ""); if (file != null) { try { if (barr != null) IOUtil.copy(new ByteArrayInputStream(barr), file, true); } catch (IOException ioe) { throw Caster.toPageException(ioe); } } } // header cfhttp.set(KeyConstants._header, raw.toString()); if (!HttpImpl.isStatusOK(rsp.getStatusCode())) { String msg = rsp.getStatusCode() + " " + rsp.getStatusText(); cfhttp.setEL(ERROR_DETAIL, msg); if (throwonerror) { throw new HTTPException(msg, null, rsp.getStatusCode(), rsp.getStatusText(), rsp.getURL()); } } } finally { //rsp.release(); } }
From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java
/** * /*from ww w. ja v a2 s .co m*/ * @param post {@link HttpPost} * @return String posted body if computable * @throws IOException if sending the data fails due to I/O */ @Override protected String sendPostData(HttpPost post) throws IOException { // Buffer to hold the post body, except file content StringBuilder postedBody = new StringBuilder(1000); FileContentServer contentServer = FileContentServer.getServer(); HTTPFileArg staticFiles[] = getHTTPFiles(); HTTPFileArg dynFiles[] = testElement.getDynamicFiles(); VariableFileArg variableFiles[] = testElement.getVariableFiles(); String[] attachmentsNumber = null; boolean thresholdCheck = testElement.getRecordType() >= testElement.getThreshold(); final String contentEncoding = getContentEncodingOrNull(); final boolean haveContentEncoding = contentEncoding != null; boolean hasContent = false; // If a content encoding is specified, we use that as the // encoding of any parameter values Charset charset = null; if (haveContentEncoding) { charset = Charset.forName(contentEncoding); } // Write the request to our own stream MultipartEntity multiPart = new MultipartEntity( getDoBrowserCompatibleMultipart() ? HttpMultipartMode.BROWSER_COMPATIBLE : HttpMultipartMode.STRICT, null, charset); // Create the parts // Add any parameters PropertyIterator args = getArguments().iterator(); while (args.hasNext()) { HTTPArgument arg = (HTTPArgument) args.next().getObjectValue(); String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } FormBodyPart formPart; StringBody stringBody = new StringBody(arg.getValue(), charset); formPart = new FormBodyPart(arg.getName(), stringBody); multiPart.addPart(formPart); hasContent = true; } /* * set parameters controlled by threshold */ if (!testElement.getArgumentThreshold() || thresholdCheck) { args = testElement.getOwnArguments().iterator(); while (args.hasNext()) { HTTPArgument arg = (HTTPArgument) args.next().getObjectValue(); String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } FormBodyPart formPart; StringBody stringBody = new StringBody(arg.getValue(), charset); formPart = new FormBodyPart(arg.getName(), stringBody); multiPart.addPart(formPart); hasContent = true; } } // Add all files // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here. ViewableByteBody[] viewableByteBodies = new ViewableByteBody[variableFiles.length + staticFiles.length + dynFiles.length]; int i = 0; //Variable Files if (!testElement.getVariableThreshold() || thresholdCheck) for (int j = 0; j < variableFiles.length; j++, i++) { VariableFileArg file = variableFiles[j]; viewableByteBodies[i] = new ViewableByteBody(file.getContent().getBytes(), file.getMimeType(), file.getName()); multiPart.addPart(file.getParamName(), viewableByteBodies[i]); hasContent = true; } //Static Files if (!testElement.getStaticThreshold() || thresholdCheck) for (i = 0; i < staticFiles.length; i++) { HTTPFileArg file = staticFiles[i]; viewableByteBodies[i] = new ViewableByteBody(contentServer.getFileContent(file.getPath()), file.getMimeType(), new File(file.getPath()).getName()); multiPart.addPart(file.getParamName(), viewableByteBodies[i]); hasContent = true; } //Dynamic Files if (!testElement.getDynamicThreshold() || thresholdCheck) { attachmentsNumber = testElement.getAttachmentNumbers().split(","); for (int j = 0; j < attachmentsNumber.length && !attachmentsNumber[j].isEmpty(); i++, j++) { int fileNum = Integer.parseInt(attachmentsNumber[j]) - 1; if (fileNum >= dynFiles.length) { log.warn("trying to send file out of dynamic files range (" + Integer.toString(fileNum + 1) + " of " + Integer.toString(dynFiles.length) + ")\nfile was skipped"); i--; continue; } HTTPFileArg file = dynFiles[fileNum]; viewableByteBodies[i] = new ViewableByteBody(contentServer.getFileContent(file.getPath()), file.getMimeType(), new File(file.getPath()).getName()); multiPart.addPart(file.getParamName(), viewableByteBodies[i]); hasContent = true; } } post.setEntity(multiPart); if (!hasContent) log.warn("POST has no content!"); if (multiPart.isRepeatable()) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); //stop the content from appearing in sampler result if (!testElement.getLogFiles()) { for (ViewableByteBody fileBody : viewableByteBodies) { if (fileBody != null) fileBody.hideFileData = true; else break; } } multiPart.writeTo(bos); //Set it back, in order for the content to be sent if (!testElement.getLogFiles()) { for (ViewableByteBody fileBody : viewableByteBodies) { if (fileBody != null) fileBody.hideFileData = false; else break; } } bos.flush(); // We get the posted bytes using the encoding used to create it postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient : contentEncoding)); bos.close(); } else { postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$ } return postedBody.toString(); }
From source file:lucee.runtime.tag.Http41.java
private void _doEndTag(Struct cfhttp) throws PageException, IOException { HttpClientBuilder builder = HttpClients.custom(); // redirect//from w w w . j a va 2 s . co m if (redirect) builder.setRedirectStrategy(new DefaultRedirectStrategy()); else builder.disableRedirectHandling(); // cookies BasicCookieStore cookieStore = new BasicCookieStore(); builder.setDefaultCookieStore(cookieStore); ConfigWeb cw = pageContext.getConfig(); HttpRequestBase req = null; HttpContext httpContext = null; //HttpRequestBase req = init(pageContext.getConfig(),this,client,params,url,port); { if (StringUtil.isEmpty(charset, true)) charset = ((PageContextImpl) pageContext).getWebCharset().name(); else charset = charset.trim(); // check if has fileUploads boolean doUploadFile = false; for (int i = 0; i < this.params.size(); i++) { if ((this.params.get(i)).getType().equalsIgnoreCase("file")) { doUploadFile = true; break; } } // parse url (also query string) int len = this.params.size(); StringBuilder sbQS = new StringBuilder(); for (int i = 0; i < len; i++) { HttpParamBean param = this.params.get(i); String type = param.getType(); // URL if (type.equals("url")) { if (sbQS.length() > 0) sbQS.append('&'); sbQS.append(param.getEncoded() ? HttpImpl.urlenc(param.getName(), charset) : param.getName()); sbQS.append('='); sbQS.append(param.getEncoded() ? HttpImpl.urlenc(param.getValueAsString(), charset) : param.getValueAsString()); } } String host = null; HttpHost httpHost; try { URL _url = HTTPUtil.toURL(url, port, encoded); httpHost = new HttpHost(_url.getHost(), _url.getPort()); host = _url.getHost(); url = _url.toExternalForm(); if (sbQS.length() > 0) { // no existing QS if (StringUtil.isEmpty(_url.getQuery())) { url += "?" + sbQS; } else { url += "&" + sbQS; } } } catch (MalformedURLException mue) { throw Caster.toPageException(mue); } // select best matching method (get,post, post multpart (file)) boolean isBinary = false; boolean doMultiPart = doUploadFile || this.multiPart; HttpPost post = null; HttpEntityEnclosingRequest eem = null; if (this.method == METHOD_GET) { req = new HttpGet(url); } else if (this.method == METHOD_HEAD) { req = new HttpHead(url); } else if (this.method == METHOD_DELETE) { isBinary = true; req = new HttpDelete(url); } else if (this.method == METHOD_PUT) { isBinary = true; HttpPut put = new HttpPut(url); req = put; eem = put; } else if (this.method == METHOD_TRACE) { isBinary = true; req = new HttpTrace(url); } else if (this.method == METHOD_OPTIONS) { isBinary = true; req = new HttpOptions(url); } else if (this.method == METHOD_PATCH) { isBinary = true; eem = HTTPPatchFactory.getHTTPPatch(url); req = (HttpRequestBase) eem; } else { isBinary = true; post = new HttpPost(url); req = post; eem = post; } boolean hasForm = false; boolean hasBody = false; boolean hasContentType = false; // Set http params ArrayList<FormBodyPart> parts = new ArrayList<FormBodyPart>(); StringBuilder acceptEncoding = new StringBuilder(); java.util.List<NameValuePair> postParam = post != null ? new ArrayList<NameValuePair>() : null; for (int i = 0; i < len; i++) { HttpParamBean param = this.params.get(i); String type = param.getType(); // URL if (type.equals("url")) { //listQS.add(new BasicNameValuePair(translateEncoding(param.getName(), http.charset),translateEncoding(param.getValueAsString(), http.charset))); } // Form else if (type.equals("formfield") || type.equals("form")) { hasForm = true; if (this.method == METHOD_GET) throw new ApplicationException( "httpparam with type formfield can only be used when the method attribute of the parent http tag is set to post"); if (post != null) { if (doMultiPart) { parts.add(new FormBodyPart(param.getName(), new StringBody(param.getValueAsString(), CharsetUtil.toCharset(charset)))); } else { postParam.add(new BasicNameValuePair(param.getName(), param.getValueAsString())); } } //else if(multi!=null)multi.addParameter(param.getName(),param.getValueAsString()); } // CGI else if (type.equals("cgi")) { if (param.getEncoded()) req.addHeader(HttpImpl.urlenc(param.getName(), charset), HttpImpl.urlenc(param.getValueAsString(), charset)); else req.addHeader(param.getName(), param.getValueAsString()); } // Header else if (type.startsWith("head")) { if (param.getName().equalsIgnoreCase("content-type")) hasContentType = true; if (param.getName().equalsIgnoreCase("Content-Length")) { } else if (param.getName().equalsIgnoreCase("Accept-Encoding")) { acceptEncoding.append(HttpImpl.headerValue(param.getValueAsString())); acceptEncoding.append(", "); } else req.addHeader(param.getName(), HttpImpl.headerValue(param.getValueAsString())); } // Cookie else if (type.equals("cookie")) { HTTPEngineImpl.addCookie(cookieStore, host, param.getName(), param.getValueAsString(), "/", charset); } // File else if (type.equals("file")) { hasForm = true; if (this.method == METHOD_GET) throw new ApplicationException( "httpparam type file can't only be used, when method of the tag http equal post"); String strCT = HttpImpl.getContentType(param); ContentType ct = HTTPUtil.toContentType(strCT, null); String mt = "text/xml"; if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true)) mt = ct.getMimeType(); String cs = charset; if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true)) cs = ct.getCharset(); if (doMultiPart) { try { Resource res = param.getFile(); parts.add(new FormBodyPart(param.getName(), new ResourceBody(res, mt, res.getName(), cs))); //parts.add(new ResourcePart(param.getName(),new ResourcePartSource(param.getFile()),getContentType(param),_charset)); } catch (FileNotFoundException e) { throw new ApplicationException("can't upload file, path is invalid", e.getMessage()); } } } // XML else if (type.equals("xml")) { ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null); String mt = "text/xml"; if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true)) mt = ct.getMimeType(); String cs = charset; if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true)) cs = ct.getCharset(); hasBody = true; hasContentType = true; req.addHeader("Content-type", mt + "; charset=" + cs); if (eem == null) throw new ApplicationException("type xml is only supported for type post and put"); HTTPEngineImpl.setBody(eem, param.getValueAsString(), mt, cs); } // Body else if (type.equals("body")) { ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null); String mt = null; if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true)) mt = ct.getMimeType(); String cs = charset; if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true)) cs = ct.getCharset(); hasBody = true; if (eem == null) throw new ApplicationException("type body is only supported for type post and put"); HTTPEngineImpl.setBody(eem, param.getValue(), mt, cs); } else { throw new ApplicationException("invalid type [" + type + "]"); } } // post params if (postParam != null && postParam.size() > 0) post.setEntity(new org.apache.http.client.entity.UrlEncodedFormEntity(postParam, charset)); if (compression) { acceptEncoding.append("gzip"); } else { acceptEncoding.append("deflate;q=0"); req.setHeader("TE", "deflate;q=0"); } req.setHeader("Accept-Encoding", acceptEncoding.toString()); // multipart if (doMultiPart && eem != null) { hasContentType = true; boolean doIt = true; if (!this.multiPart && parts.size() == 1) { ContentBody body = parts.get(0).getBody(); if (body instanceof StringBody) { StringBody sb = (StringBody) body; try { org.apache.http.entity.ContentType ct = org.apache.http.entity.ContentType .create(sb.getMimeType(), sb.getCharset()); String str = IOUtil.toString(sb.getReader()); StringEntity entity = new StringEntity(str, ct); eem.setEntity(entity); } catch (IOException e) { throw Caster.toPageException(e); } doIt = false; } } if (doIt) { MultipartEntity mpe = new MultipartEntity(HttpMultipartMode.STRICT); Iterator<FormBodyPart> it = parts.iterator(); while (it.hasNext()) { FormBodyPart part = it.next(); mpe.addPart(part.getName(), part.getBody()); } eem.setEntity(mpe); } //eem.setRequestEntity(new MultipartRequestEntityFlex(parts.toArray(new Part[parts.size()]), eem.getParams(),http.multiPartType)); } if (hasBody && hasForm) throw new ApplicationException("mixing httpparam type file/formfield and body/XML is not allowed"); if (!hasContentType) { if (isBinary) { if (hasBody) req.addHeader("Content-type", "application/octet-stream"); else req.addHeader("Content-type", "application/x-www-form-urlencoded; charset=" + charset); } else { if (hasBody) req.addHeader("Content-type", "text/html; charset=" + charset); } } // set User Agent if (!HttpImpl.hasHeaderIgnoreCase(req, "User-Agent")) req.setHeader("User-Agent", this.useragent); // set timeout if (this.timeout > 0L) { builder.setConnectionTimeToLive(this.timeout, TimeUnit.MILLISECONDS); } // set Username and Password if (this.username != null) { if (this.password == null) this.password = ""; if (AUTH_TYPE_NTLM == this.authType) { if (StringUtil.isEmpty(this.workStation, true)) throw new ApplicationException( "attribute workstation is required when authentication type is [NTLM]"); if (StringUtil.isEmpty(this.domain, true)) throw new ApplicationException( "attribute domain is required when authentication type is [NTLM]"); HTTPEngineImpl.setNTCredentials(builder, this.username, this.password, this.workStation, this.domain); } else httpContext = HTTPEngineImpl.setCredentials(builder, httpHost, this.username, this.password, preauth); } // set Proxy ProxyData proxy = null; if (!StringUtil.isEmpty(this.proxyserver)) { proxy = ProxyDataImpl.getInstance(this.proxyserver, this.proxyport, this.proxyuser, this.proxypassword); } if (pageContext.getConfig().isProxyEnableFor(host)) { proxy = pageContext.getConfig().getProxyData(); } HTTPEngineImpl.setProxy(builder, req, proxy); } CloseableHttpClient client = null; try { if (httpContext == null) httpContext = new BasicHttpContext(); /////////////////////////////////////////// EXECUTE ///////////////////////////////////////////////// client = builder.build(); Executor41 e = new Executor41(this, client, httpContext, req, redirect); HTTPResponse4Impl rsp = null; if (timeout < 0) { try { rsp = e.execute(httpContext); } catch (Throwable t) { if (!throwonerror) { setUnknownHost(cfhttp, t); return; } throw toPageException(t); } } else { e.start(); try { synchronized (this) {//print.err(timeout); this.wait(timeout); } } catch (InterruptedException ie) { throw Caster.toPageException(ie); } if (e.t != null) { if (!throwonerror) { setUnknownHost(cfhttp, e.t); return; } throw toPageException(e.t); } rsp = e.response; if (!e.done) { req.abort(); if (throwonerror) throw new HTTPException("408 Request Time-out", "a timeout occurred in tag http", 408, "Time-out", rsp.getURL()); setRequestTimeout(cfhttp); return; //throw new ApplicationException("timeout"); } } /////////////////////////////////////////// EXECUTE ///////////////////////////////////////////////// Charset responseCharset = CharsetUtil.toCharset(rsp.getCharset()); // Write Response Scope //String rawHeader=httpMethod.getStatusLine().toString(); String mimetype = null; String contentEncoding = null; // status code cfhttp.set(STATUSCODE, ((rsp.getStatusCode() + " " + rsp.getStatusText()).trim())); cfhttp.set(STATUS_CODE, new Double(rsp.getStatusCode())); cfhttp.set(STATUS_TEXT, (rsp.getStatusText())); cfhttp.set(HTTP_VERSION, (rsp.getProtocolVersion())); //responseHeader lucee.commons.net.http.Header[] headers = rsp.getAllHeaders(); StringBuffer raw = new StringBuffer(rsp.getStatusLine() + " "); Struct responseHeader = new StructImpl(); Struct cookie; Array setCookie = new ArrayImpl(); Query cookies = new QueryImpl( new String[] { "name", "value", "path", "domain", "expires", "secure", "httpOnly" }, 0, "cookies"); for (int i = 0; i < headers.length; i++) { lucee.commons.net.http.Header header = headers[i]; //print.ln(header); raw.append(header.toString() + " "); if (header.getName().equalsIgnoreCase("Set-Cookie")) { setCookie.append(header.getValue()); parseCookie(cookies, header.getValue()); } else { //print.ln(header.getName()+"-"+header.getValue()); Object value = responseHeader.get(KeyImpl.getInstance(header.getName()), null); if (value == null) responseHeader.set(KeyImpl.getInstance(header.getName()), header.getValue()); else { Array arr = null; if (value instanceof Array) { arr = (Array) value; } else { arr = new ArrayImpl(); responseHeader.set(KeyImpl.getInstance(header.getName()), arr); arr.appendEL(value); } arr.appendEL(header.getValue()); } } // Content-Type if (header.getName().equalsIgnoreCase("Content-Type")) { mimetype = header.getValue(); if (mimetype == null) mimetype = NO_MIMETYPE; } // Content-Encoding if (header.getName().equalsIgnoreCase("Content-Encoding")) { contentEncoding = header.getValue(); } } cfhttp.set(RESPONSEHEADER, responseHeader); cfhttp.set(KeyConstants._cookies, cookies); responseHeader.set(STATUS_CODE, new Double(rsp.getStatusCode())); responseHeader.set(EXPLANATION, (rsp.getStatusText())); if (setCookie.size() > 0) responseHeader.set(SET_COOKIE, setCookie); // is text boolean isText = mimetype == null || mimetype == NO_MIMETYPE || HTTPUtil.isTextMimeType(mimetype); // is multipart boolean isMultipart = MultiPartResponseUtils.isMultipart(mimetype); cfhttp.set(KeyConstants._text, Caster.toBoolean(isText)); // mimetype charset //boolean responseProvideCharset=false; if (!StringUtil.isEmpty(mimetype, true)) { if (isText) { String[] types = HTTPUtil.splitMimeTypeAndCharset(mimetype, null); if (types[0] != null) cfhttp.set(KeyConstants._mimetype, types[0]); if (types[1] != null) cfhttp.set(CHARSET, types[1]); } else cfhttp.set(KeyConstants._mimetype, mimetype); } else cfhttp.set(KeyConstants._mimetype, NO_MIMETYPE); // File Resource file = null; if (strFile != null && strPath != null) { file = ResourceUtil.toResourceNotExisting(pageContext, strPath).getRealResource(strFile); } else if (strFile != null) { file = ResourceUtil.toResourceNotExisting(pageContext, strFile); } else if (strPath != null) { file = ResourceUtil.toResourceNotExisting(pageContext, strPath); //Resource dir = file.getParentResource(); if (file.isDirectory()) { file = file.getRealResource(req.getURI().getPath());// TODO was getName() ->http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/URI.html#getName() } } if (file != null) pageContext.getConfig().getSecurityManager().checkFileLocation(file); // filecontent InputStream is = null; if (isText && getAsBinary != GET_AS_BINARY_YES) { String str; try { // read content if (method != METHOD_HEAD) { is = rsp.getContentAsStream(); if (is != null && HttpImpl.isGzipEncoded(contentEncoding)) is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is) : new GZIPInputStream(is); } try { try { str = is == null ? "" : IOUtil.toString(is, responseCharset); } catch (EOFException eof) { if (is instanceof CachingGZIPInputStream) { str = IOUtil.toString(is = ((CachingGZIPInputStream) is).getRawData(), responseCharset); } else throw eof; } } catch (UnsupportedEncodingException uee) { str = IOUtil.toString(is, (Charset) null); } } catch (IOException ioe) { throw Caster.toPageException(ioe); } finally { IOUtil.closeEL(is); } if (str == null) str = ""; if (resolveurl) { //if(e.redirectURL!=null)url=e.redirectURL.toExternalForm(); str = new URLResolver().transform(str, e.response.getTargetURL(), false); } cfhttp.set(FILE_CONTENT, str); try { if (file != null) { IOUtil.write(file, str, ((PageContextImpl) pageContext).getWebCharset(), false); } } catch (IOException e1) { } if (name != null) { Query qry = CSVParser.toQuery(str, delimiter, textqualifier, columns, firstrowasheaders); pageContext.setVariable(name, qry); } } // Binary else { byte[] barr = null; if (HttpImpl.isGzipEncoded(contentEncoding)) { if (method != METHOD_HEAD) { is = rsp.getContentAsStream(); is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is) : new GZIPInputStream(is); } try { try { barr = is == null ? new byte[0] : IOUtil.toBytes(is); } catch (EOFException eof) { if (is instanceof CachingGZIPInputStream) barr = IOUtil.toBytes(((CachingGZIPInputStream) is).getRawData()); else throw eof; } } catch (IOException t) { throw Caster.toPageException(t); } finally { IOUtil.closeEL(is); } } else { try { if (method != METHOD_HEAD) barr = rsp.getContentAsByteArray(); else barr = new byte[0]; } catch (IOException t) { throw Caster.toPageException(t); } } //IF Multipart response get file content and parse parts if (barr != null) { if (isMultipart) { cfhttp.set(FILE_CONTENT, MultiPartResponseUtils.getParts(barr, mimetype)); } else { cfhttp.set(FILE_CONTENT, barr); } } else cfhttp.set(FILE_CONTENT, ""); if (file != null) { try { if (barr != null) IOUtil.copy(new ByteArrayInputStream(barr), file, true); } catch (IOException ioe) { throw Caster.toPageException(ioe); } } } // header cfhttp.set(KeyConstants._header, raw.toString()); if (!HttpImpl.isStatusOK(rsp.getStatusCode())) { String msg = rsp.getStatusCode() + " " + rsp.getStatusText(); cfhttp.setEL(ERROR_DETAIL, msg); if (throwonerror) { throw new HTTPException(msg, null, rsp.getStatusCode(), rsp.getStatusText(), rsp.getURL()); } } } finally { if (client != null) client.close(); } }
From source file:org.cloudifysource.restclient.GSRestClient.java
/** * This methods executes HTTP post over REST on the given (relative) URL with the given file and properties (also * sent as a separate file)./*from w w w . j a v a 2 s.c om*/ * * @param relativeUrl * The URL to post to. * @param additionalFiles * The files to send (example: <SOME PATH>/tomcat.zip). * @param props * The properties of this POST action (example: com.gs.service.type=WEB_SERVER) * @param params * as a map of names and values. * @return The response object from the REST server * @throws RestException * Reporting failure to post the file. */ public final Object postFiles(final String relativeUrl, final Properties props, final Map<String, String> params, final Map<String, File> additionalFiles) throws RestException { final MultipartEntity reqEntity = new MultipartEntity(); // It should be possible to dump the properties into a String entity, // but I can't get it to work. So using a temp file instead. // Idiotic, but works. // dump map into file File tempFile; try { tempFile = writeMapToFile(props); } catch (final IOException e) { throw new RestException(e); } final FileBody propsFile = new FileBody(tempFile); reqEntity.addPart("props", propsFile); if (params != null) { try { for (Map.Entry<String, String> param : params.entrySet()) { reqEntity.addPart(param.getKey(), new StringBody(param.getValue(), Charset.forName("UTF-8"))); } } catch (final IOException e) { throw new RestException(e); } } // add the rest of the files for (Entry<String, File> entry : additionalFiles.entrySet()) { final File file = entry.getValue(); if (file != null) { final FileBody bin = new FileBody(file); reqEntity.addPart(entry.getKey(), bin); } } final HttpPost httppost = new HttpPost(getFullUrl(relativeUrl)); httppost.setEntity(reqEntity); return executeHttpMethod(httppost); }
From source file:org.xmetdb.rest.protocol.CallableProtocolUpload.java
protected HttpEntity createPOSTEntity(DBAttachment attachment) throws Exception { Charset utf8 = Charset.forName("UTF-8"); if ("text/uri-list".equals(attachment.getFormat())) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("title", attachment.getProtocol().getIdentifier())); formparams.add(new BasicNameValuePair("dataset_uri", attachment.getDescription())); formparams.add(new BasicNameValuePair("folder", attachment_type.substrate.equals(attachment.getType()) ? "substrate" : "product")); return new UrlEncodedFormEntity(formparams, "UTF-8"); } else {/*from www . ja v a 2s .com*/ if (attachment.getResourceURL() == null) throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Attachment resource URL is null! "); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8); entity.addPart("title", new StringBody(attachment.getTitle(), utf8)); entity.addPart("seeAlso", new StringBody(attachment.getDescription(), utf8)); entity.addPart("license", new StringBody("XMETDB", utf8)); URI uri = attachment.getResourceURL().toURI(); entity.addPart("file", new FileBody(new File(uri))); return entity; } //match, seeAlso, license }