List of usage examples for org.apache.http.entity EntityTemplate EntityTemplate
public EntityTemplate(ContentProducer contentProducer)
From source file:ru.apertum.qsystem.reports.net.HttpQSystemReportsHandler.java
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); }/*w w w .j a v a 2 s .co m*/ // ?? ? Response result = QReportsList.getInstance().generate(request); // ? if (result == null) { String subject = NetUtil.getUrl(request); if ("/".equals(subject)) { subject = "/login.html"; } int dot = subject.lastIndexOf("."); final String ext = subject.substring(dot + 1); String contentType = "; charset=UTF-8"; if ("htm".equals(ext) || "html".equals(ext)) { contentType = "text/" + ext + contentType; } else { if ("pdf".equals(ext) || "rtf".equals(ext) || "doc".equals(ext) || "xlsx".equals(ext)) { contentType = "application/" + ext + contentType; } else { if ("gif".equals(ext) || "jpeg".equals(ext) || "jpg".equals(ext) || "ico".equals(ext) || "xpm".equals(ext)) { contentType = "image/" + ext + contentType; } } } // ?? "/ru/apertum/qsystem/reports/web/" final InputStream inStream = getClass() .getResourceAsStream("/ru/apertum/qsystem/reports/web" + subject); if (inStream == null) { QLog.l().logRep() .warn("?? : \"/ru/apertum/qsystem/reports/web" + subject + "\""); // ??, // subject = subject.substring(1); File anyFile = new File(subject); if (anyFile.exists()) { QLog.l().logRep().info(" : \"" + subject + "\""); FileInputStream fInStream = null; try { fInStream = new FileInputStream(anyFile); } catch (FileNotFoundException ex) { final String err = " \"" + subject + "\" "; QLog.l().logRep().error("err " + ex); result = new Response((err + ex).getBytes(), contentType); response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } try { result = new Response(Uses.readInputStream(fInStream), contentType); response.setStatusCode(HttpStatus.SC_OK); } catch (IOException ex) { final String err = " \"" + subject + "\" "; QLog.l().logRep().error("err " + ex); result = new Response((err + ex).getBytes(), contentType); response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } else { // anyFile = new File( Uses.TEMP_FOLDER + File.separator + "temphtml.html_files" + File.separator + subject); if (anyFile.exists()) { QLog.l().logRep().info(" : \"" + Uses.TEMP_FOLDER + File.separator + "temphtml.html_files" + File.separator + subject + "\""); FileInputStream fInStream = null; try { fInStream = new FileInputStream(anyFile); } catch (FileNotFoundException ex) { final String err = " \"" + Uses.TEMP_FOLDER + File.separator + "temphtml.html_files" + File.separator + subject + "\" "; QLog.l().logRep().error("err " + ex); result = new Response((err + ex).getBytes(), contentType); response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } try { result = new Response(Uses.readInputStream(fInStream), contentType); response.setStatusCode(HttpStatus.SC_OK); } catch (IOException ex) { final String err = " \"" + Uses.TEMP_FOLDER + File.separator + "temphtml.html_files" + File.separator + subject + "\" "; QLog.l().logRep().error("err " + ex); result = new Response((err + ex).getBytes(), contentType); response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } anyFile.delete(); } else { // . ? ?? ( ???) QLog.l().logRep() .error("?? : \"" + Uses.TEMP_FOLDER + File.separator + "temphtml.html_files" + File.separator + subject + "\""); final String s = "<html><head><meta http-equiv = \"Content-Type\" content = \"text/html; charset=utf-8\" ></head><p align=center>?? .</p></html>"; result = new Response(s.getBytes()); } } } else { QLog.l().logRep().info(" ??: \"" + subject + "\""); try { result = new Response(Uses.readInputStream(inStream)); if ("/login.html".equals(subject)) { result.setData( RepResBundle.getInstance().prepareString(new String(result.getData(), "UTF-8")) .replaceFirst(Uses.ANCHOR_USERS_FOR_REPORT, QReportsList.getInstance().getHtmlUsersList()) .replaceFirst(Uses.ANCHOR_PROJECT_NAME_FOR_REPORT, Uses.getLocaleMessage("project.name" + FAbout.getCMRC_SUFF())) .getBytes("UTF-8")); //"Cp1251" } } catch (IOException ex) { QLog.l().logRep().error(" ? ??. " + ex); result = new Response((" ? ??. " + ex).getBytes()); response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } response.setStatusCode(HttpStatus.SC_OK); } } // : QLog.l().logRep().trace(" " + result.getData().length + " ? \"" + request.getRequestLine().getUri() + "\"."); final byte[] result2 = result.getData(); final EntityTemplate body = new EntityTemplate((final OutputStream outstream) -> { outstream.write(result2); outstream.flush(); }); body.setContentType(result.getContentType()); response.setEntity(body); NetUtil.freeEntityContent(request); }
From source file:org.wso2.esb.integration.common.utils.clients.SimpleHttpClient.java
/** * Send a HTTP PUT request to the specified URL * * @param url Target endpoint URL * @param headers Any HTTP headers that should be added to the request * @param payload Content payload that should be sent * @param contentType Content-type of the request * @return Returned HTTP response//w ww. ja v a 2 s . c o m * @throws IOException If an error occurs while making the invocation */ public HttpResponse doPut(String url, final Map<String, String> headers, final String payload, String contentType) throws IOException { HttpUriRequest request = new HttpPut(url); setHeaders(headers, request); HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request; final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING)); EntityTemplate ent = new EntityTemplate(new ContentProducer() { public void writeTo(OutputStream outputStream) throws IOException { OutputStream out = outputStream; if (zip) { out = new GZIPOutputStream(outputStream); } out.write(payload.getBytes()); out.flush(); out.close(); } }); ent.setContentType(contentType); if (zip) { ent.setContentEncoding("gzip"); } entityEncReq.setEntity(ent); return client.execute(request); }
From source file:org.apache.jena.fuseki.embedded.TestEmbeddedFuseki.java
/** Create an HttpEntity for the graph */ protected static HttpEntity graphToHttpEntity(final Graph graph) { final RDFFormat syntax = RDFFormat.TURTLE_BLOCKS; ContentProducer producer = new ContentProducer() { @Override//from ww w.ja va 2s . c o m public void writeTo(OutputStream out) { RDFDataMgr.write(out, graph, syntax); } }; EntityTemplate entity = new EntityTemplate(producer); ContentType ct = syntax.getLang().getContentType(); entity.setContentType(ct.getContentType()); return entity; }
From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java
/** * Perform PUT request against an RTC server * @param serverURI The RTC server/*from ww w . j av a2 s.co m*/ * @param uri The relative URI for the PUT. It is expected that it is already encoded if necessary. * @param userId The userId to authenticate as * @param password The password to authenticate with * @param timeout The timeout period for the connection (in seconds) * @param json The JSON object to put to the RTC server * @param httpContext The context from the login if cycle is being managed by the caller * Otherwise <code>null</code> and this call will handle the login. * @param listener The listener to report errors to. * May be <code>null</code> if there is no listener. * @return The HttpContext for the request. May be reused in subsequent requests * for the same user * @throws IOException Thrown if things go wrong * @throws InvalidCredentialsException * @throws GeneralSecurityException */ public static HttpClientContext performPut(String serverURI, String uri, String userId, String password, int timeout, final JSONObject json, HttpClientContext httpContext, TaskListener listener) throws IOException, InvalidCredentialsException, GeneralSecurityException { CloseableHttpClient httpClient = getClient(); // How to fill the request body (Clone doesn't work) ContentProducer cp = new ContentProducer() { public void writeTo(OutputStream outstream) throws IOException { Writer writer = new OutputStreamWriter(outstream, UTF_8); json.write(writer); writer.flush(); } }; HttpEntity entity = new EntityTemplate(cp); String fullURI = getFullURI(serverURI, uri); HttpPut put = getPUT(fullURI, timeout); put.setEntity(entity); if (httpContext == null) { httpContext = createHttpContext(); } LOGGER.finer("PUT: " + put.getURI()); //$NON-NLS-1$ CloseableHttpResponse response = httpClient.execute(put, httpContext); try { // based on the response do any authentication. If authentication requires // the request to be performed again (i.e. Basic auth) re-issue request response = authenticateIfRequired(response, httpClient, httpContext, serverURI, userId, password, timeout, listener); // retry put request if we have to do authentication if (response == null) { put = getPUT(fullURI, timeout); put.setEntity(entity); response = httpClient.execute(put, httpContext); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // It is an unusual case to get here (in our current work flow) because it means // the user has become unauthenticated since the previous request // (i.e. the get of the value about to put back) throw new InvalidCredentialsException(Messages.HttpUtils_authentication_failed(userId, serverURI)); } else { int responseClass = statusCode / 100; if (responseClass != 2) { if (listener != null) { listener.fatalError(Messages.HttpUtils_PUT_failed(fullURI, statusCode)); } throw logError(fullURI, response, Messages.HttpUtils_PUT_failed(fullURI, statusCode)); } return httpContext; } } finally { closeResponse(response); } }
From source file:org.expath.httpclient.impl.ApacheHttpConnection.java
/** * Configure the request to get its entity body from the {@link HttpRequestBody}. *//*from w ww . j a v a2s . com*/ private void setRequestEntity(HttpRequestBody body) throws HttpClientException { if (body == null) { return; } // make the entity from a new producer HttpEntity entity; if (myVersion == HttpVersion.HTTP_1_1) { // Take advantage of HTTP 1.1 chunked encoding to stream the // payload directly to the request. ContentProducer producer = new RequestBodyProducer(body); EntityTemplate template = new EntityTemplate(producer); template.setContentType(body.getContentType()); entity = template; } else { // With HTTP 1.0, chunked encoding is not supported, so first // serialize into memory and use the resulting byte array as the // entity payload. ByteArrayOutputStream buffer = new ByteArrayOutputStream(); body.serialize(buffer); entity = new ByteArrayEntity(buffer.toByteArray()); } // cast the request HttpEntityEnclosingRequestBase req = null; if (!(myRequest instanceof HttpEntityEnclosingRequestBase)) { String msg = "Body not allowed on a " + myRequest.getMethod() + " request"; throw new HttpClientException(msg); } else { req = (HttpEntityEnclosingRequestBase) myRequest; } // set the entity on the request req.setEntity(entity); }
From source file:com.cellbots.httpserver.HttpCommandServer.java
public void handle(final HttpServerConnection conn, final HttpContext context) throws HttpException, IOException { HttpRequest request = conn.receiveRequestHeader(); HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"); String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST") && !method.equals("PUT")) { throw new MethodNotSupportedException(method + " method not supported"); }//from w w w.j av a 2s.com // Get the requested target. This is the string after the domain name in // the URL. If the full URL was http://mydomain.com/test.html, target // will be /test.html. String target = request.getRequestLine().getUri(); //Log.w(TAG, "*** Request target: " + target); // Gets the requested resource name. For example, if the full URL was // http://mydomain.com/test.html?x=1&y=2, resource name will be // test.html final String resName = getResourceNameFromTarget(target); UrlParams params = new UrlParams(target); //Log.w(TAG, "*** Request LINE: " + request.getRequestLine().toString()); //Log.w(TAG, "*** Request resource: " + resName); if (method.equals("POST") || method.equals("PUT")) { byte[] entityContent = null; // Gets the content if the request has an entity. if (request instanceof HttpEntityEnclosingRequest) { conn.receiveRequestEntity((HttpEntityEnclosingRequest) request); HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { entityContent = EntityUtils.toByteArray(entity); } } response.setStatusCode(HttpStatus.SC_OK); if (serverListener != null) { serverListener.onRequest(resName, params.keys, params.values, entityContent); } } else if (dataMap.containsKey(resName)) { // The requested resource is // a byte array response.setStatusCode(HttpStatus.SC_OK); response.setHeader("Content-Type", dataMap.get(resName).contentType); response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource)); } else { // Resource is a file recognized by the app String fileName = resourceMap.containsKey(resName) ? resourceMap.get(resName).resource : resName; String contentType = resourceMap.containsKey(resName) ? resourceMap.get(resName).contentType : "text/html"; Log.d(TAG, "*** mapped resource: " + fileName); Log.d(TAG, "*** checking for file: " + rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName); response.setStatusCode(HttpStatus.SC_OK); final File file = new File(rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName); if (file.exists() && !file.isDirectory()) { response.setStatusCode(HttpStatus.SC_OK); FileEntity body = new FileEntity(file, URLConnection.guessContentTypeFromName(fileName)); response.setHeader("Content-Type", URLConnection.guessContentTypeFromName(fileName)); response.setEntity(body); } else if (file.isDirectory()) { response.setStatusCode(HttpStatus.SC_OK); EntityTemplate body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); ArrayList<String> fileList = getDirListing(file); String resp = "{ \"list\": ["; for (String fl : fileList) { resp += "\"" + fl + "\","; } resp = resp.substring(0, resp.length() - 1); resp += "]}"; writer.write(resp); writer.flush(); } }); body.setContentType(contentType); response.setEntity(body); } else if (resourceMap.containsKey(resName)) { EntityTemplate body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write(resourceMap.get(resName).resource); writer.flush(); } }); body.setContentType(contentType); response.setEntity(body); } else { response.setStatusCode(HttpStatus.SC_NOT_FOUND); response.setEntity(new StringEntity("Not Found")); } } conn.sendResponseHeader(response); conn.sendResponseEntity(response); conn.flush(); conn.shutdown(); }
From source file:org.apache.marmotta.client.clients.ResourceClient.java
/** * Update the content of the resource identified by the URI given as argument. The resource has to exist before * content can be uploaded to it. Any existing content will be overridden. The stream of the content object * will be consumed by this method. Throws ContentFormatException if the content type is not supported, * NotFoundException if the resource does not exist. * @param uri// ww w . ja v a 2s.c o m * @param content * @throws IOException * @throws MarmottaClientException */ public void updateResourceContent(final String uri, final Content content) throws IOException, MarmottaClientException { HttpClient httpClient = HTTPUtil.createClient(config); HttpPut put = new HttpPut(getServiceUrl(uri)); put.setHeader("Content-Type", content.getMimeType() + "; rel=content"); ContentProducer cp = new ContentProducer() { @Override public void writeTo(OutputStream outstream) throws IOException { ByteStreams.copy(content.getStream(), outstream); } }; put.setEntity(new EntityTemplate(cp)); ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() { @Override public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException { EntityUtils.consume(response.getEntity()); switch (response.getStatusLine().getStatusCode()) { case 200: log.debug("content for resource {} updated", uri); return true; case 406: log.error("server does not support content type {} for resource {}, cannot update", content.getMimeType(), uri); return false; case 404: log.error("resource {} does not exist, cannot update", uri); return false; default: log.error("error updating resource {}: {} {}", new Object[] { uri, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase() }); return false; } } }; try { httpClient.execute(put, handler); } catch (IOException ex) { put.abort(); throw ex; } finally { put.releaseConnection(); } }
From source file:org.metaeffekt.dcc.controller.execution.RemoteExecutor.java
private HttpEntity createZipFileOfSolutionLocation() { final ContentProducer contentProducer = new ContentProducer() { @Override//from w w w .j a v a2 s . c o m public void writeTo(OutputStream outstream) throws IOException { try (ZipOutputStream zipFile = new ZipOutputStream(new BufferedOutputStream(outstream))) { Path solutionDirectory = Paths.get(getExecutionContext().getSolutionDir().getAbsolutePath()); addDirectoryContentsToZipFile(solutionDirectory, solutionDirectory, zipFile, INCLUDED_FOLDERS); zipFile.finish(); } outstream.flush(); } }; return new EntityTemplate(contentProducer); }
From source file:org.rundeck.api.ApiCall.java
private <T> T requestWithEntity(ApiPathBuilder apiPath, Handler<HttpResponse, T> handler, HttpEntityEnclosingRequestBase httpPost) { if (null != apiPath.getAccept()) { httpPost.setHeader("Accept", apiPath.getAccept()); }//w w w.jav a2 s.c o m // POST a multi-part request, with all attachments if (apiPath.getAttachments().size() > 0 || apiPath.getFileAttachments().size() > 0) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ArrayList<File> tempfiles = new ArrayList<>(); //attach streams for (Entry<String, InputStream> attachment : apiPath.getAttachments().entrySet()) { if (client.isUseIntermediateStreamFile()) { //transfer to file File f = copyToTempfile(attachment.getValue()); multipartEntityBuilder.addBinaryBody(attachment.getKey(), f); tempfiles.add(f); } else { multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue()); } } if (tempfiles.size() > 0) { handler = TempFileCleanupHandler.chain(handler, tempfiles); } //attach files for (Entry<String, File> attachment : apiPath.getFileAttachments().entrySet()) { multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue()); } httpPost.setEntity(multipartEntityBuilder.build()); } else if (apiPath.getForm().size() > 0) { try { httpPost.setEntity(new UrlEncodedFormEntity(apiPath.getForm(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RundeckApiException("Unsupported encoding: " + e.getMessage(), e); } } else if (apiPath.getContentStream() != null && apiPath.getContentType() != null) { if (client.isUseIntermediateStreamFile()) { ArrayList<File> tempfiles = new ArrayList<>(); File f = copyToTempfile(apiPath.getContentStream()); tempfiles.add(f); httpPost.setEntity(new FileEntity(f, ContentType.create(apiPath.getContentType()))); handler = TempFileCleanupHandler.chain(handler, tempfiles); } else { InputStreamEntity entity = new InputStreamEntity(apiPath.getContentStream(), ContentType.create(apiPath.getContentType())); httpPost.setEntity(entity); } } else if (apiPath.getContents() != null && apiPath.getContentType() != null) { ByteArrayEntity bae = new ByteArrayEntity(apiPath.getContents(), ContentType.create(apiPath.getContentType())); httpPost.setEntity(bae); } else if (apiPath.getContentFile() != null && apiPath.getContentType() != null) { httpPost.setEntity( new FileEntity(apiPath.getContentFile(), ContentType.create(apiPath.getContentType()))); } else if (apiPath.getXmlDocument() != null) { httpPost.setHeader("Content-Type", "application/xml"); httpPost.setEntity(new EntityTemplate(new DocumentContentProducer(apiPath.getXmlDocument()))); } else if (apiPath.isEmptyContent()) { //empty content } else { throw new IllegalArgumentException("No Form or Multipart entity for POST content-body"); } return execute(httpPost, handler); }
From source file:org.apache.jena.rdfconnection.RDFConnectionRemote.java
/** Create an HttpEntity for the graph */ protected HttpEntity graphToHttpEntity(Graph graph, RDFFormat syntax) { EntityTemplate entity = new EntityTemplate((out) -> RDFDataMgr.write(out, graph, syntax)); String ct = syntax.getLang().getContentType().getContentType(); entity.setContentType(ct);// w ww . j a v a 2 s . c o m return entity; }