List of usage examples for org.apache.http.entity.mime.content InputStreamBody InputStreamBody
public InputStreamBody(final InputStream in, final String filename)
From source file:com.cellbots.eyes.EyesActivity.java
private void appEngineUploadImage(byte[] imageData) { Log.e("app engine remote eyes", "called"); try {/*from www . ja v a 2 s . com*/ YuvImage yuvImage = new YuvImage(imageData, previewFormat, previewWidth, previewHeight, null); yuvImage.compressToJpeg(r, 20, out); // Tweak the quality here - 20 // seems pretty decent for // quality + size. Log.e("app engine remote eyes", "upload starting"); HttpPost httpPost = new HttpPost(postUrl); Log.e("app engine perf", "0"); MultipartEntity entity = new MultipartEntity(); Log.e("app engine perf", "1"); entity.addPart("img", new InputStreamBody(new ByteArrayInputStream(out.toByteArray()), "video.jpg")); Log.e("app engine perf", "2"); httpPost.setEntity(entity); Log.e("app engine perf", "3"); HttpResponse response = httpclient.execute(httpPost); Log.e("app engine remote eyes", "result: " + response.getStatusLine()); Log.e("app engine remote eyes", "upload complete"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); resetAppEngineConnection(); } catch (ClientProtocolException e) { e.printStackTrace(); resetAppEngineConnection(); } catch (IOException e) { e.printStackTrace(); resetAppEngineConnection(); } finally { out.reset(); if (mCamera != null) { mCamera.addCallbackBuffer(mCallbackBuffer); } isUploading = false; Log.e("app engine remote eyes", "finished"); } }
From source file:com.su.search.client.solrj.PaHttpSolrServer.java
public NamedList<Object> request(final SolrRequest request, final ResponseParser processor) throws SolrServerException, IOException { HttpRequestBase method = null;/*from w w w.j a v a 2 s . c om*/ InputStream is = null; SolrParams params = request.getParams(); // modified by wangqiang406 2012-07-27 // ?? if (null != password) { ModifiableSolrParams wparams = new ModifiableSolrParams(params); wparams.set(SimpleIndexClient.KEY_PA_AUTH, password); params = wparams; } Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = this.parser; } // The parser 'wt=' and 'version=' params are used instead of the original // params ModifiableSolrParams wparams = new ModifiableSolrParams(params); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (invariantParams != null) { wparams.add(invariantParams); } params = wparams; 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 HttpGet(baseUrl + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = baseUrl + path; boolean isMultipart = (streams != null && streams.size() > 1); LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>(); if (streams == null || isMultipart) { HttpPost post = new HttpPost(url); post.setHeader("Content-Charset", "UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<FormBodyPart> parts = new LinkedList<FormBodyPart>(); 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 FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8")))); } else { postParams.add(new BasicNameValuePair(p, v)); } } } } if (isMultipart) { for (ContentStream content : streams) { parts.add(new FormBodyPart(content.getName(), new InputStreamBody(content.getStream(), content.getName()))); } } if (parts.size() > 0) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); for (FormBodyPart p : parts) { entity.addPart(p); } post.setEntity(entity); } else { //not using multipart HttpEntity e; post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8")); } 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); HttpPost post = new HttpPost(url + pstr); // 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.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if (tries < 1) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } // TODO: move to a interceptor? method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects); method.addHeader("User-Agent", AGENT); InputStream respBody = null; try { // Execute the method. final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents String charset = EntityUtils.getContentCharSet(response.getEntity()); respBody = response.getEntity().getContent(); // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: break; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: if (!followRedirects) { throw new SolrServerException( "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ")."); } break; case HttpStatus.SC_NOT_FOUND: throw new SolrServerException("Server at " + getBaseURL() + " was not found (404)."); default: throw new SolrServerException("Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase()); } NamedList<Object> rsp = processor.processResponse(respBody, charset); if (httpStatus != HttpStatus.SC_OK) { String reason = null; try { NamedList err = (NamedList) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); // TODO? get the trace? } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append("request: " + method.getURI()); reason = java.net.URLDecoder.decode(msg.toString(), UTF_8); } throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), reason); } return rsp; } catch (ConnectException e) { throw new SolrServerException("Server refused connection at: " + getBaseURL(), e); } catch (SocketTimeoutException e) { throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e); } catch (IOException e) { throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e); } finally { if (respBody != null) { try { respBody.close(); } catch (Throwable t) { } // ignore } } }
From source file:org.openremote.modeler.beehive.Beehive30API.java
/** * Uploads resources from the given input stream to Beehive server. The Beehive REST API * used assumes a zip compressed stream including all relevant resources. The input stream * parameter must match these expectations. <p> * * The access to Beehive is authenticated using the given user's credentials. * * @param archive zip compressed byte stream containing all the resources to upload * to Beehive// w w w . j a va 2 s .c om * @param currentUserAccount The user to authenticate in Beehive, along with account information * * * @throws ConfigurationException * If the Beehive REST URL has been incorrectly configured. Will require * reconfiguration and re-deployment of the application. * * @throws NetworkException * If there's an I/O error on the upload stream or the Beehive server * returns an error status * */ @Override public void uploadResources(InputStream archive, UserAccount currentUserAccount) throws ConfigurationException, NetworkException { final String ARCHIVE_NAME = "openremote.zip"; // TODO : must be HTTPS Account acct = currentUserAccount.getAccount(); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(); addHTTPAuthenticationHeader(httpPost, currentUserAccount.getUsernamePassword().getUsername(), currentUserAccount.getUsernamePassword().getPassword()); String beehiveRootRestURL = config.getBeehiveRESTRootUrl(); String url = beehiveRootRestURL + "account/" + acct.getOid() + "/" + ARCHIVE_NAME; try { httpPost.setURI(new URI(url)); } catch (URISyntaxException e) { throw new ConfigurationException("Incorrectly configured Beehive REST URL ''{0}'' : {1}", e, beehiveRootRestURL, e.getMessage()); } InputStreamBody resource = new InputStreamBody(archive, ARCHIVE_NAME); MultipartEntity entity = new MultipartEntity(); entity.addPart("resource", resource); httpPost.setEntity(entity); HttpResponse response; try { response = httpClient.execute(httpPost); } catch (IOException e) { throw new NetworkException("Network I/O error while uploading resource artifacts to Beehive : {0}", e, e.getMessage()); } if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { throw new NetworkException("Failed to save resources to Beehive, status code: {0}", response.getStatusLine().getStatusCode()); } // TODO : // - should probably check other return codes explicitly here too, such as // authentication errors (which is most likely not recoverable whereas // a regular network connection glitch might well be)... }
From source file:com.atlassian.jira.rest.client.internal.async.AsynchronousIssueRestClient.java
@Override public Promise<Void> addAttachment(final URI attachmentsUri, final InputStream inputStream, final String filename) { final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.defaultCharset()); entity.addPart(FILE_BODY_TYPE, new InputStreamBody(inputStream, filename)); return postAttachments(attachmentsUri, entity); }
From source file:com.parworks.androidlibrary.ar.ARSiteImpl.java
@Override public BaseImage addBaseImage(String filename, InputStream image) { // handleStateSync(mId, State.NEEDS_MORE_BASE_IMAGES, // State.NEEDS_BASE_IMAGE_PROCESSING); // make httputils HttpUtils httpUtils = new HttpUtils(mApiKey, mTime, mSignature); // make query string Map<String, String> params = new HashMap<String, String>(); params.put("site", mId); params.put("filename", filename); // make entity MultipartEntity imageEntity = new MultipartEntity(); InputStreamBody imageInputStreamBody = new InputStreamBody(image, filename); imageEntity.addPart("image", imageInputStreamBody); // do post/*from www . j a v a 2 s. co m*/ HttpResponse serverResponse = httpUtils .doPost(HttpUtils.PARWORKS_API_BASE_URL + HttpUtils.ADD_BASE_IMAGE_PATH, imageEntity, params); // handle status code HttpUtils.handleStatusCode(serverResponse.getStatusLine().getStatusCode()); // parse response ARResponseHandler responseHandler = new ARResponseHandlerImpl(); AddBaseImageResponse addBaseImageResponse = responseHandler.handleResponse(serverResponse, AddBaseImageResponse.class); // return baseimageinfo if (addBaseImageResponse.getSuccess() == true) { return new BaseImage(addBaseImageResponse.getId()); } else { throw new ARException( "Successfully communicated with the server but failed to add the base image. Perhaps the site does not exist, or there is a problem with the image."); } }
From source file:com.atlassian.jira.rest.client.internal.async.AsynchronousIssueRestClient.java
@Override public Promise<Void> addAttachments(final URI attachmentsUri, final AttachmentInput... attachments) { final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.defaultCharset()); for (final AttachmentInput attachmentInput : attachments) { entity.addPart(FILE_BODY_TYPE,/* w w w. j av a 2 s . c o m*/ new InputStreamBody(attachmentInput.getInputStream(), attachmentInput.getFilename())); } return postAttachments(attachmentsUri, entity); }
From source file:org.apache.stanbol.workflow.jersey.writers.ContentItemWriter.java
@Override public void writeTo(ContentItem ci, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { //(0) handle default dataType Map<String, Object> reqProp = ContentItemHelper.getRequestPropertiesContentPart(ci); boolean omitMetadata = isOmitMetadata(reqProp); if (!MULTIPART.isCompatible(mediaType)) { //two possible cases if (!omitMetadata) { // (1) just return the RDF data //(1.a) Backward support for default dataType if no Accept header is set StringBuilder ctb = new StringBuilder(); if (mediaType.isWildcardType() || TEXT_PLAIN_TYPE.isCompatible(mediaType) || APPLICATION_OCTET_STREAM_TYPE.isCompatible(mediaType)) { ctb.append(APPLICATION_LD_JSON); } else { ctb.append(mediaType.getType()).append('/').append(mediaType.getSubtype()); }//w w w .ja va 2 s . co m ctb.append(";charset=").append(UTF8.name()); String contentType = ctb.toString(); httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType); try { serializer.serialize(entityStream, ci.getMetadata(), contentType); } catch (UnsupportedSerializationFormatException e) { throw new WebApplicationException("The enhancement results " + "cannot be serialized in the requested media type: " + mediaType.toString(), Response.Status.NOT_ACCEPTABLE); } } else { // (2) return a single content part Entry<UriRef, Blob> contentPart = getBlob(ci, Collections.singleton(mediaType.toString())); if (contentPart == null) { //no alternate content with the requeste media type throw new WebApplicationException("The requested enhancement chain has not created an " + "version of the parsed content in the reuqest media type " + mediaType.toString(), Response.Status.UNSUPPORTED_MEDIA_TYPE); } else { //found -> stream the content to the client //NOTE: This assumes that the presence of a charset // implies reading/writing character streams String requestedCharset = mediaType.getParameters().get("charset"); String blobCharset = contentPart.getValue().getParameter().get("charset"); Charset readerCharset = blobCharset == null ? UTF8 : Charset.forName(blobCharset); Charset writerCharset = requestedCharset == null ? null : Charset.forName(requestedCharset); if (writerCharset != null && !writerCharset.equals(readerCharset)) { //we need to transcode Reader reader = new InputStreamReader(contentPart.getValue().getStream(), readerCharset); Writer writer = new OutputStreamWriter(entityStream, writerCharset); IOUtils.copy(reader, writer); IOUtils.closeQuietly(reader); } else { //no transcoding if (requestedCharset == null && blobCharset != null) { httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString() + "; charset=" + blobCharset); } InputStream in = contentPart.getValue().getStream(); IOUtils.copy(in, entityStream); IOUtils.closeQuietly(in); } } } } else { // multipart mime requested! final String charsetName = mediaType.getParameters().get("charset"); final Charset charset = charsetName != null ? Charset.forName(charsetName) : UTF8; MediaType rdfFormat; String rdfFormatString = getRdfFormat(reqProp); if (rdfFormatString == null || rdfFormatString.isEmpty()) { rdfFormat = DEFAULT_RDF_FORMAT; } else { try { rdfFormat = MediaType.valueOf(rdfFormatString); if (rdfFormat.getParameters().get("charset") == null) { //use the charset of the default RDF format rdfFormat = new MediaType(rdfFormat.getType(), rdfFormat.getSubtype(), DEFAULT_RDF_FORMAT.getParameters()); } } catch (IllegalArgumentException e) { throw new WebApplicationException( "The specified RDF format '" + rdfFormatString + "' (used to serialize all RDF parts of " + "multipart MIME responses) is not a well formated MIME type", Response.Status.BAD_REQUEST); } } //(1) setting the correct header String contentType = String.format("%s/%s; charset=%s; boundary=%s", mediaType.getType(), mediaType.getSubtype(), charset.toString(), CONTENT_ITEM_BOUNDARY); httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setBoundary(CONTENT_ITEM_BOUNDARY); //HttpMultipart entity = new HttpMultipart("from-data", charset ,CONTENT_ITEM_BOUNDARY); //(2) serialising the metadata if (!isOmitMetadata(reqProp)) { entityBuilder.addPart("metadata", new ClerezzaContentBody(ci.getUri().getUnicodeString(), ci.getMetadata(), rdfFormat)); // entity.addBodyPart(new FormBodyPart("metadata", new ClerezzaContentBody( // ci.getUri().getUnicodeString(), ci.getMetadata(), // rdfFormat))); } //(3) serialising the Content (Bloby) //(3.a) Filter based on parameter List<Entry<UriRef, Blob>> includedBlobs = filterBlobs(ci, reqProp); //(3.b) Serialise the filtered if (!includedBlobs.isEmpty()) { Map<String, ContentBody> contentParts = new LinkedHashMap<String, ContentBody>(); for (Entry<UriRef, Blob> entry : includedBlobs) { Blob blob = entry.getValue(); ContentType ct = ContentType.create(blob.getMimeType()); String cs = blob.getParameter().get("charset"); if (StringUtils.isNotBlank(cs)) { ct = ct.withCharset(cs); } contentParts.put(entry.getKey().getUnicodeString(), new InputStreamBody(blob.getStream(), ct)); } //add all the blobs entityBuilder.addPart("content", new MultipartContentBody(contentParts, CONTENT_PARTS_BOUNDERY, MULTIPART_ALTERNATE)); } //else no content to include Set<String> includeContentParts = getIncludedContentPartURIs(reqProp); if (includeContentParts != null) { //(4) serialise the Request Properties if (includeContentParts.isEmpty() || includeContentParts.contains(REQUEST_PROPERTIES_URI.getUnicodeString())) { JSONObject object; try { object = toJson(reqProp); } catch (JSONException e) { String message = "Unable to convert Request Properties " + "to JSON (values : " + reqProp + ")!"; log.error(message, e); throw new WebApplicationException(message, Response.Status.INTERNAL_SERVER_ERROR); } entityBuilder.addTextBody(REQUEST_PROPERTIES_URI.getUnicodeString(), object.toString(), ContentType.APPLICATION_JSON.withCharset(UTF8)); } //(5) additional RDF metadata stored in contentParts for (Entry<UriRef, TripleCollection> entry : getContentParts(ci, TripleCollection.class) .entrySet()) { if (includeContentParts.isEmpty() || includeContentParts.contains(entry.getKey())) { entityBuilder.addPart(entry.getKey().getUnicodeString(), new ClerezzaContentBody(null, //no file name entry.getValue(), rdfFormat)); } // else ignore this content part } } entityBuilder.build().writeTo(entityStream); } }
From source file:org.opencastproject.workingfilerepository.remote.WorkingFileRepositoryRemoteImpl.java
/** * {@inheritDoc}/* w w w.j a va 2s. co m*/ * * @see org.opencastproject.workingfilerepository.api.WorkingFileRepository#put(java.lang.String, java.lang.String, * java.lang.String, java.io.InputStream) */ @Override public URI put(String mediaPackageID, String mediaPackageElementID, String filename, InputStream in) { String url = UrlSupport .concat(new String[] { MEDIAPACKAGE_PATH_PREFIX, mediaPackageID, mediaPackageElementID }); HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(); ContentBody body = new InputStreamBody(in, filename); entity.addPart("file", body); post.setEntity(entity); HttpResponse response = getResponse(post); try { if (response != null) { String content = EntityUtils.toString(response.getEntity()); return new URI(content); } } catch (Exception e) { throw new RuntimeException(e); } finally { closeConnection(response); } throw new RuntimeException("Unable to put file"); }
From source file:org.opencastproject.workingfilerepository.remote.WorkingFileRepositoryRemoteImpl.java
/** * {@inheritDoc}/* www .j ava 2 s . com*/ * * @see org.opencastproject.workingfilerepository.api.WorkingFileRepository#putInCollection(java.lang.String, * java.lang.String, java.io.InputStream) */ @Override public URI putInCollection(String collectionId, String fileName, InputStream in) { String url = UrlSupport.concat(new String[] { COLLECTION_PATH_PREFIX, collectionId }); HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(); ContentBody body = new InputStreamBody(in, fileName); entity.addPart("file", body); post.setEntity(entity); HttpResponse response = getResponse(post); try { if (response != null) { String content = EntityUtils.toString(response.getEntity()); return new URI(content); } } catch (Exception e) { throw new RuntimeException(e); } finally { closeConnection(response); } throw new RuntimeException("Unable to put file in collection"); }
From source file:org.brutusin.rpc.client.http.HttpEndpoint.java
private CloseableHttpResponse doExec(String serviceId, JsonNode input, HttpMethod httpMethod, final ProgressCallback progressCallback) throws IOException { RpcRequest request = new RpcRequest(); request.setJsonrpc("2.0"); request.setMethod(serviceId);/*from ww w .ja v a 2 s. com*/ request.setParams(input); final String payload = JsonCodec.getInstance().transform(request); final HttpUriRequest req; if (httpMethod == HttpMethod.GET) { String urlparam = URLEncoder.encode(payload, "UTF-8"); req = new HttpGet(this.endpoint + "?jsonrpc=" + urlparam); } else { HttpEntityEnclosingRequestBase reqBase; if (httpMethod == HttpMethod.POST) { reqBase = new HttpPost(this.endpoint); } else if (httpMethod == HttpMethod.PUT) { reqBase = new HttpPut(this.endpoint); } else { throw new AssertionError(); } req = reqBase; HttpEntity entity; Map<String, InputStream> files = JsonCodec.getInstance().getStreams(input); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.STRICT); builder.addPart("jsonrpc", new StringBody(payload, ContentType.APPLICATION_JSON)); if (files != null && !files.isEmpty()) { files = sortFiles(files); for (Map.Entry<String, InputStream> entrySet : files.entrySet()) { String key = entrySet.getKey(); InputStream is = entrySet.getValue(); if (is instanceof MetaDataInputStream) { MetaDataInputStream mis = (MetaDataInputStream) is; builder.addPart(key, new InputStreamBody(mis, mis.getName())); } else { builder.addPart(key, new InputStreamBody(is, key)); } } } entity = builder.build(); if (progressCallback != null) { entity = new ProgressHttpEntityWrapper(entity, progressCallback); } reqBase.setEntity(entity); } HttpClientContext context = contexts.get(); if (this.clientContextFactory != null && context == null) { context = clientContextFactory.create(); contexts.set(context); } return this.httpClient.execute(req, context); }