List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity
public InputStreamEntity(InputStream inputStream, ContentType contentType)
From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.java
@SuppressWarnings("deprecation") private void doProxy(String remoteUrl, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible try {/*from www.j ava 2 s. c o m*/ this.targetUri = new URI(remoteUrl); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Need to handle https, but think about "restricted" layers for now. Some institutions don't really have good protection for restricted layers. Does this open up potential for security //problems for those folks? if (servletRequest.getScheme().equals("https")) { //actually, what matters the most is if the remote url is https } BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest( servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest)); //HttpGet httpget = new HttpGet(rewriteUrlFromRequest(servletRequest)); copyRequestHeaders(servletRequest, proxyRequest); // Add the input entity (streamed) then execute the request. HttpResponse proxyResponse = null; InputStream servletRequestInputStream = servletRequest.getInputStream(); CloseableHttpClient proxyClient = ogpHttpClient.getCloseableHttpClient(); try { try { //proxyRequest.setEntity(new InputStreamEntity(servletRequestInputStream)); proxyRequest.setEntity( new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength())); // Execute the request logger.debug("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); } finally { IOUtils.closeQuietly(servletRequestInputStream); } // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); logger.info("Status from remote server: " + Integer.toString(statusCode)); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; throw new RuntimeException(e); } }
From source file:project.cs.lisa.netinf.node.resolution.NameResolutionService.java
/** * Creates an HTTP Post request to get an IO from the NRS. * @param uri the NetInf format URI for getting IOs * @return The HTTP Post request * @throws UnsupportedEncodingException In case UTF-8 is not supported *//* ww w . ja v a 2s . c o m*/ private HttpPost createGet(String uri) throws UnsupportedEncodingException { HttpPost post = new HttpPost(mHost + ":" + mPort + "/netinfproto/get"); String msgid = Integer.toString(mRandomGenerator.nextInt(MSG_ID_MAX)); String ext = "no extension"; String completeUri = "URI=" + uri + "&msgid=" + msgid + "&ext=" + ext; String encodeUrl = null; encodeUrl = URLEncoder.encode(completeUri, "UTF-8"); HttpEntity newEntity = new InputStreamEntity(fromString(encodeUrl), encodeUrl.getBytes().length); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(newEntity); return post; }
From source file:org.apache.solr.servlet.HttpSolrCall.java
private void remoteQuery(String coreUrl, HttpServletResponse resp) throws IOException { HttpRequestBase method = null;/*from w w w. j ava2 s . com*/ HttpEntity httpEntity = null; try { String urlstr = coreUrl + queryParams.toQueryString(); boolean isPostOrPutRequest = "POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()); if ("GET".equals(req.getMethod())) { method = new HttpGet(urlstr); } else if ("HEAD".equals(req.getMethod())) { method = new HttpHead(urlstr); } else if (isPostOrPutRequest) { HttpEntityEnclosingRequestBase entityRequest = "POST".equals(req.getMethod()) ? new HttpPost(urlstr) : new HttpPut(urlstr); InputStream in = new CloseShieldInputStream(req.getInputStream()); // Prevent close of container streams HttpEntity entity = new InputStreamEntity(in, req.getContentLength()); entityRequest.setEntity(entity); method = entityRequest; } else if ("DELETE".equals(req.getMethod())) { method = new HttpDelete(urlstr); } else { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unexpected method type: " + req.getMethod()); } for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements();) { String headerName = e.nextElement(); if (!"host".equalsIgnoreCase(headerName) && !"authorization".equalsIgnoreCase(headerName) && !"accept".equalsIgnoreCase(headerName)) { method.addHeader(headerName, req.getHeader(headerName)); } } // These headers not supported for HttpEntityEnclosingRequests if (method instanceof HttpEntityEnclosingRequest) { method.removeHeaders(TRANSFER_ENCODING_HEADER); method.removeHeaders(CONTENT_LENGTH_HEADER); } final HttpResponse response = solrDispatchFilter.httpClient.execute(method, HttpClientUtil.createNewHttpClientRequestContext()); int httpStatus = response.getStatusLine().getStatusCode(); httpEntity = response.getEntity(); resp.setStatus(httpStatus); for (HeaderIterator responseHeaders = response.headerIterator(); responseHeaders.hasNext();) { Header header = responseHeaders.nextHeader(); // We pull out these two headers below because they can cause chunked // encoding issues with Tomcat if (header != null && !header.getName().equalsIgnoreCase(TRANSFER_ENCODING_HEADER) && !header.getName().equalsIgnoreCase(CONNECTION_HEADER)) { resp.addHeader(header.getName(), header.getValue()); } } if (httpEntity != null) { if (httpEntity.getContentEncoding() != null) resp.setCharacterEncoding(httpEntity.getContentEncoding().getValue()); if (httpEntity.getContentType() != null) resp.setContentType(httpEntity.getContentType().getValue()); InputStream is = httpEntity.getContent(); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(is, os); } } catch (IOException e) { sendError(new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error trying to proxy request for url: " + coreUrl, e)); } finally { Utils.consumeFully(httpEntity); } }
From source file:ingestor.SingleFileProcessor.java
/** * Writes custom-metadata ONLY to an already existing object in HCP. * * @param encodedPathURL/*from ww w . ja va2 s . c o m*/ * @param inSourceFile * @throws Exception */ //TODO: consider moving this function into HCPClient private Boolean WriteAnnotationsToHCP(URL encodedPathURL, File inSourceFile) throws Exception { annotations = mCustomMetadataGenerator.generateAnnotations(inSourceFile); HCPClient client = new HCPClient(CometProperties.getInstance()); client.setRootpath(CometProperties.getInstance().getDestinationRootPath(pathPrefix)); ThreadTrackerDB.updateDBOverHTTP(mCurrentFile.getAbsolutePath() + "-writing-metadata", threadID, mCurrentFile.length()); for (String key : annotations.keySet()) { if (key.equals("") || annotations.get(key).equals("") || annotations.get(key).contains("ignore")) { //annotations.remove(key); logger.fine("annotation " + key + " was blank or marked to be ignored, skipping"); ScreenLog.out("\tannotation " + key + " was either blank or marked to be ignored, don't ingest"); annotations.put(key, ""); continue; } else { ScreenLog.out("\tannotation " + key + " was neither blank nor marked to be ignored, ingesting..."); } String currentAnnotation = key; logger.info("Sending PUT Custom Metadata to URL: " + encodedPathURL + " for annotation " + currentAnnotation); if (annotations.containsKey(key) && !annotations.get(key).equals("")) client.HttpPutHCPContent( new InputStreamEntity(new ByteArrayInputStream(annotations.get(key).getBytes()), -1), new URL(encodedPathURL + "?type=custom-metadata&annotation=" + currentAnnotation)); if (client.getStatusCode() / 100 == 2) eCustomMetadataStatus = WriteStatus.WRITE_SUCCESS; } //end for loop return eCustomMetadataStatus == WriteStatus.WRITE_SUCCESS; }
From source file:com.github.sardine.impl.SardineImpl.java
@Override public void put(String url, InputStream dataStream, String contentType, boolean expectContinue, long contentLength) throws IOException { InputStreamEntity entity = new InputStreamEntity(dataStream, contentLength); this.put(url, entity, contentType, expectContinue); }
From source file:com.sangupta.jerry.http.WebRequest.java
/** * Set the body stream from given input stream. * * @param instream/*from ww w . j a v a2s . co m*/ * the {@link InputStream} to read from * * @return this very {@link WebRequest} */ public WebRequest bodyStream(final InputStream instream) { return body(new InputStreamEntity(instream, -1)); }
From source file:com.github.sardine.impl.SardineImpl.java
@Override public void put(String url, InputStream dataStream, Map<String, String> headers) throws IOException { // A length of -1 means "go until end of stream" InputStreamEntity entity = new InputStreamEntity(dataStream, -1); this.put(url, entity, headers); }
From source file:android.webkit.cts.CtsTestServer.java
/** * Generate a response to the given request. * @throws InterruptedException/*from ww w. j a v a 2s. c om*/ * @throws IOException */ private HttpResponse getResponse(HttpRequest request) throws Exception { RequestLine requestLine = request.getRequestLine(); HttpResponse response = null; String uriString = requestLine.getUri(); Log.i(TAG, requestLine.getMethod() + ": " + uriString); synchronized (this) { mQueries.add(uriString); mLastRequestMap.put(uriString, request); if (request instanceof HttpEntityEnclosingRequest) { mRequestEntities.add(((HttpEntityEnclosingRequest) request).getEntity()); } } if (requestLine.getMethod().equals("POST")) { HttpResponse responseOnPost = onPost(request); if (responseOnPost != null) { return responseOnPost; } } URI uri = URI.create(uriString); String path = uri.getPath(); String query = uri.getQuery(); if (path.equals(FAVICON_PATH)) { path = FAVICON_ASSET_PATH; } if (path.startsWith(DELAY_PREFIX)) { String delayPath = path.substring(DELAY_PREFIX.length() + 1); String delay = delayPath.substring(0, delayPath.indexOf('/')); path = delayPath.substring(delay.length()); try { Thread.sleep(Integer.valueOf(delay)); } catch (InterruptedException ignored) { // ignore } } if (path.startsWith(AUTH_PREFIX)) { // authentication required Header[] auth = request.getHeaders("Authorization"); if ((auth.length > 0 && auth[0].getValue().equals(AUTH_CREDENTIALS)) // This is a hack to make sure that loads to this url's will always // ask for authentication. This is what the test expects. && !path.endsWith("embedded_image.html")) { // fall through and serve content path = path.substring(AUTH_PREFIX.length()); } else { // request authorization response = createResponse(HttpStatus.SC_UNAUTHORIZED); response.addHeader("WWW-Authenticate", "Basic realm=\"" + AUTH_REALM + "\""); } } if (path.startsWith(BINARY_PREFIX)) { List<NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8"); int length = 0; String mimeType = null; try { for (NameValuePair pair : args) { String name = pair.getName(); if (name.equals("type")) { mimeType = pair.getValue(); } else if (name.equals("length")) { length = Integer.parseInt(pair.getValue()); } } if (length > 0 && mimeType != null) { ByteArrayEntity entity = new ByteArrayEntity(new byte[length]); entity.setContentType(mimeType); response = createResponse(HttpStatus.SC_OK); response.setEntity(entity); response.addHeader("Content-Disposition", "attachment; filename=test.bin"); response.addHeader("Content-Type", mimeType); response.addHeader("Content-Length", "" + length); } else { // fall through, return 404 at the end } } catch (Exception e) { // fall through, return 404 at the end Log.w(TAG, e); } } else if (path.startsWith(ASSET_PREFIX)) { path = path.substring(ASSET_PREFIX.length()); // request for an asset file try { InputStream in; if (path.startsWith(RAW_PREFIX)) { String resourceName = path.substring(RAW_PREFIX.length()); int id = mResources.getIdentifier(resourceName, "raw", mContext.getPackageName()); if (id == 0) { Log.w(TAG, "Can't find raw resource " + resourceName); throw new IOException(); } in = mResources.openRawResource(id); } else { in = mAssets.open(path); } response = createResponse(HttpStatus.SC_OK); InputStreamEntity entity = new InputStreamEntity(in, in.available()); String mimeType = mMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path)); if (mimeType == null) { mimeType = "text/html"; } entity.setContentType(mimeType); response.setEntity(entity); if (query == null || !query.contains(NOLENGTH_POSTFIX)) { response.setHeader("Content-Length", "" + entity.getContentLength()); } } catch (IOException e) { response = null; // fall through, return 404 at the end } } else if (path.startsWith(REDIRECT_PREFIX)) { response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY); String location = getBaseUri() + path.substring(REDIRECT_PREFIX.length()); Log.i(TAG, "Redirecting to: " + location); response.addHeader("Location", location); } else if (path.equals(QUERY_REDIRECT_PATH)) { String location = Uri.parse(uriString).getQueryParameter("dest"); if (location != null) { Log.i(TAG, "Redirecting to: " + location); response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader("Location", location); } } else if (path.startsWith(COOKIE_PREFIX)) { /* * Return a page with a title containing a list of all incoming cookies, * separated by '|' characters. If a numeric 'count' value is passed in a cookie, * return a cookie with the value incremented by 1. Otherwise, return a cookie * setting 'count' to 0. */ response = createResponse(HttpStatus.SC_OK); Header[] cookies = request.getHeaders("Cookie"); Pattern p = Pattern.compile("count=(\\d+)"); StringBuilder cookieString = new StringBuilder(100); cookieString.append(cookies.length); int count = 0; for (Header cookie : cookies) { cookieString.append("|"); String value = cookie.getValue(); cookieString.append(value); Matcher m = p.matcher(value); if (m.find()) { count = Integer.parseInt(m.group(1)) + 1; } } response.addHeader("Set-Cookie", "count=" + count + "; path=" + COOKIE_PREFIX); response.setEntity(createPage(cookieString.toString(), cookieString.toString())); } else if (path.startsWith(SET_COOKIE_PREFIX)) { response = createResponse(HttpStatus.SC_OK); Uri parsedUri = Uri.parse(uriString); String key = parsedUri.getQueryParameter("key"); String value = parsedUri.getQueryParameter("value"); String cookie = key + "=" + value; response.addHeader("Set-Cookie", cookie); response.setEntity(createPage(cookie, cookie)); } else if (path.startsWith(LINKED_SCRIPT_PREFIX)) { response = createResponse(HttpStatus.SC_OK); String src = Uri.parse(uriString).getQueryParameter("url"); String scriptTag = "<script src=\"" + src + "\"></script>"; response.setEntity(createPage("LinkedScript", scriptTag)); } else if (path.equals(USERAGENT_PATH)) { response = createResponse(HttpStatus.SC_OK); Header agentHeader = request.getFirstHeader("User-Agent"); String agent = ""; if (agentHeader != null) { agent = agentHeader.getValue(); } response.setEntity(createPage(agent, agent)); } else if (path.equals(TEST_DOWNLOAD_PATH)) { response = createTestDownloadResponse(Uri.parse(uriString)); } else if (path.equals(SHUTDOWN_PREFIX)) { response = createResponse(HttpStatus.SC_OK); // We cannot close the socket here, because we need to respond. // Status must be set to OK, or else the test will fail due to // a RunTimeException. } else if (path.equals(APPCACHE_PATH)) { response = createResponse(HttpStatus.SC_OK); response.setEntity(createEntity("<!DOCTYPE HTML>" + "<html manifest=\"appcache.manifest\">" + " <head>" + " <title>Waiting</title>" + " <script>" + " function updateTitle(x) { document.title = x; }" + " window.applicationCache.onnoupdate = " + " function() { updateTitle(\"onnoupdate Callback\"); };" + " window.applicationCache.oncached = " + " function() { updateTitle(\"oncached Callback\"); };" + " window.applicationCache.onupdateready = " + " function() { updateTitle(\"onupdateready Callback\"); };" + " window.applicationCache.onobsolete = " + " function() { updateTitle(\"onobsolete Callback\"); };" + " window.applicationCache.onerror = " + " function() { updateTitle(\"onerror Callback\"); };" + " </script>" + " </head>" + " <body onload=\"updateTitle('Loaded');\">AppCache test</body>" + "</html>")); } else if (path.equals(APPCACHE_MANIFEST_PATH)) { response = createResponse(HttpStatus.SC_OK); try { StringEntity entity = new StringEntity("CACHE MANIFEST"); // This entity property is not used when constructing the response, (See // AbstractMessageWriter.write(), which is called by // AbstractHttpServerConnection.sendResponseHeader()) so we have to set this header // manually. // TODO: Should we do this for all responses from this server? entity.setContentType("text/cache-manifest"); response.setEntity(entity); response.setHeader("Content-Type", "text/cache-manifest"); } catch (UnsupportedEncodingException e) { Log.w(TAG, "Unexpected UnsupportedEncodingException"); } } if (response == null) { response = createResponse(HttpStatus.SC_NOT_FOUND); } StatusLine sl = response.getStatusLine(); Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")"); setDateHeaders(response); return response; }
From source file:edu.mit.mobile.android.locast.net.NetworkClient.java
protected synchronized HttpResponse put(String path, String contentType, InputStream is) throws IOException, NetworkProtocolException { final String fullUri = getFullUrlAsString(path); final HttpPut r = new HttpPut(fullUri); if (DEBUG) {//from w ww . j a v a 2s . c om Log.d("NetworkClient", "PUT " + fullUri); } r.setEntity(new InputStreamEntity(is, 0)); r.setHeader("Content-Type", contentType); final HttpResponse c = this.execute(r); checkStatusCode(c, true); return c; }