List of usage examples for org.apache.commons.httpclient.methods.multipart PartSource PartSource
PartSource
From source file:org.activiti.rest.HttpMultipartRepresentation.java
public void processStreamAndSetMediaType(final String fileName, InputStream fileStream, Map<String, String> additionalFormFields) throws IOException { // Copy the stream in a bytearray to get the length ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(fileStream, output);/*from w ww .j a v a 2s.c o m*/ final int length = output.toByteArray().length; final InputStream stream = new ByteArrayInputStream(output.toByteArray()); List<Part> parts = new ArrayList<Part>(); // Filepart is based on in-memory stream an file-name rather than an actual file FilePart filePart = new FilePart(fileName, new PartSource() { @Override public long getLength() { return length; } @Override public String getFileName() { return fileName; } @Override public InputStream createInputStream() throws IOException { return stream; } }); parts.add(filePart); if (additionalFormFields != null && !additionalFormFields.isEmpty()) { for (Entry<String, String> field : additionalFormFields.entrySet()) { parts.add(new StringPart(field.getKey(), field.getValue())); } } MultipartRequestEntity entity = new MultipartRequestEntity(parts.toArray(new Part[] {}), new HttpMethodParams()); // Let the entity write the raw multipart to a bytearray, which is used as a source // for the input-stream returned by this Representation ByteArrayOutputStream os = new ByteArrayOutputStream(); entity.writeRequest(os); setMediaType(new MediaType(entity.getContentType())); setStream(new ByteArrayInputStream(os.toByteArray())); }
From source file:org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.java
public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException { HttpMethod method = null;//from ww w.j av a2 s.c o m InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = "/select"; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = _parser; } // The parser 'wt=' and 'version=' params are used instead of the original params ModifiableSolrParams wparams = new ModifiableSolrParams(); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (params == null) { params = wparams; } else { params = new DefaultSolrParams(wparams, params); } if (_invariantParams != null) { params = new DefaultSolrParams(_invariantParams, params); } int tries = _maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = _baseURL + path; boolean isMultipart = (streams != null && streams.size() > 1); if (streams == null || isMultipart) { PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new StringPart(p, v, "UTF-8")); } else { post.addParameter(p, v); } } } } if (isMultipart) { int i = 0; for (ContentStream content : streams) { final ContentStream c = content; String charSet = null; PartSource source = new PartSource() { public long getLength() { return c.getSize(); } public String getFileName() { return c.getName(); } public InputStream createInputStream() throws IOException { return c.getStream(); } }; parts.add(new FilePart(c.getName(), source, c.getContentType(), charSet)); } } if (parts.size() > 0) { post.setRequestEntity(new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), post.getParams())); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(params, false); PostMethod post = new PostMethod(url + pstr); // post.setRequestHeader("connection", "close"); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return contentStream[0].getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream outputStream) throws IOException { ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream); } }); } else { is = contentStream[0].getStream(); post.setRequestEntity( new InputStreamRequestEntity(is, contentStream[0].getContentType())); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { // This is generally safe to retry on method.releaseConnection(); method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if ((tries < 1)) { throw r; } //log.warn( "Caught: " + r + ". Retrying..." ); } } } catch (IOException ex) { log.error("####request####", ex); throw new SolrServerException("error reading streams", ex); } method.setFollowRedirects(_followRedirects); method.addRequestHeader("User-Agent", AGENT); if (_allowCompression) { method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate")); } // method.setRequestHeader("connection", "close"); try { // Execute the method. //System.out.println( "EXECUTE:"+method.getURI() ); int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { StringBuilder msg = new StringBuilder(); msg.append(method.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append(method.getStatusText()); msg.append("\n\n"); msg.append("request: " + method.getURI()); throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8")); } // Read the contents String charset = "UTF-8"; if (method instanceof HttpMethodBase) { charset = ((HttpMethodBase) method).getResponseCharSet(); } InputStream respBody = method.getResponseBodyAsStream(); // Jakarta Commons HTTPClient doesn't handle any // compression natively. Handle gzip or deflate // here if applicable. if (_allowCompression) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); if (contentEncodingHeader != null) { String contentEncoding = contentEncodingHeader.getValue(); if (contentEncoding.contains("gzip")) { //log.debug( "wrapping response in GZIPInputStream" ); respBody = new GZIPInputStream(respBody); } else if (contentEncoding.contains("deflate")) { //log.debug( "wrapping response in InflaterInputStream" ); respBody = new InflaterInputStream(respBody); } } else { Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader.getValue(); if (contentType != null) { if (contentType.startsWith("application/x-gzip-compressed")) { //log.debug( "wrapping response in GZIPInputStream" ); respBody = new GZIPInputStream(respBody); } else if (contentType.startsWith("application/x-deflate")) { //log.debug( "wrapping response in InflaterInputStream" ); respBody = new InflaterInputStream(respBody); } } } } } return processor.processResponse(respBody, charset); } catch (HttpException e) { throw new SolrServerException(e); } catch (IOException e) { throw new SolrServerException(e); } finally { method.releaseConnection(); if (is != null) { is.close(); } } }
From source file:org.ramadda.util.HttpFormField.java
/** * Create an entry that already holds the byte contents of a file. * Having an entry like this will result in a multi-part post * * @param name The name of the file//from w w w.j a va 2 s . c o m * @param fileName filename - this is the name that is posted * @param bytes the bytes */ public HttpFormField(String name, final String fileName, final byte[] bytes) { this.name = name; type = TYPE_FILE; this.filePartSource = new PartSource() { public InputStream createInputStream() { return new ByteArrayInputStream(bytes); } public String getFileName() { return fileName; } public long getLength() { return bytes.length; } }; }
From source file:org.ramadda.util.HttpFormField.java
/** * Get the file part/*from w w w.j a v a 2 s .c om*/ * * @return the file part */ private FilePart getFilePart() { if (filePartSource == null) { final String file = getValue(); return new FilePart(getName(), new PartSource() { public InputStream createInputStream() { try { return IOUtil.getInputStream(file); } catch (Exception exc) { throw new WrapperException("Reading file:" + file, exc); } } public String getFileName() { return new File(file).getName(); } public long getLength() { return new File(file).length(); } }); } return new FilePart(getName(), filePartSource); }
From source file:ucar.unidata.ui.HttpFormEntry.java
/** * Create an entry that already holds the byte contents of a file. * Having an entry like this will result in a multi-part post * * @param name The name of the file/* w ww .j a v a 2s . c o m*/ * @param fileName filename - this is the name that is posted * @param bytes the bytes */ public HttpFormEntry(String name, final String fileName, final byte[] bytes) { this.name = name; type = TYPE_FILE; this.filePartSource = new PartSource() { public InputStream createInputStream() { return new ByteArrayInputStream(bytes); } public String getFileName() { return fileName; } public long getLength() { return bytes.length; } }; }
From source file:ucar.unidata.ui.HttpFormEntry.java
/** * Get the file part// w w w .j a v a 2s . co m * * @return the file part */ private FilePart getFilePart() { if (filePartSource == null) { final String file = getValue(); return new FilePart(getName(), new PartSource() { public InputStream createInputStream() { try { return IOUtil.getInputStream(file); } catch (Exception exc) { throw new WrapperException("Reading file:" + file, exc); } } public String getFileName() { return new File(file).getName(); } public long getLength() { return new File(file).length(); } }); } return new FilePart(getName(), filePartSource); }