List of usage examples for org.apache.http.entity ContentType get
public static ContentType get(HttpEntity httpEntity) throws ParseException, UnsupportedCharsetException
From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java
private File getWsdl(CloseableHttpClient client, HttpContext context, DispatchContainer dispatchContainer, Map<String, File> visitedUrls, String wsdlUrl) throws Exception { if (visitedUrls.containsKey(wsdlUrl)) { return visitedUrls.get(wsdlUrl); }//from w ww . j a v a 2 s. c o m String wsdl = null; StatusLine responseStatusLine = null; CloseableHttpResponse response = client.execute(new HttpGet(wsdlUrl), context); try { responseStatusLine = response.getStatusLine(); if (responseStatusLine.getStatusCode() == HttpStatus.SC_OK) { ContentType responseContentType = ContentType.get(response.getEntity()); if (responseContentType == null) { responseContentType = ContentType.TEXT_XML; } Charset responseCharset = responseContentType.getCharset(); if (responseContentType.getCharset() == null) { responseCharset = ContentType.TEXT_XML.getCharset(); } wsdl = IOUtils.toString(response.getEntity().getContent(), responseCharset); } } finally { HttpClientUtils.closeQuietly(response); } if (StringUtils.isNotBlank(wsdl)) { File tempFile = File.createTempFile("WebServiceSender", ".wsdl"); tempFile.deleteOnExit(); visitedUrls.put(wsdlUrl, tempFile); try { DonkeyElement element = new DonkeyElement(wsdl); for (DonkeyElement child : element.getChildElements()) { if (child.getLocalName().equals("import") && child.hasAttribute("location")) { String location = new URI(wsdlUrl).resolve(child.getAttribute("location")).toString(); child.setAttribute("location", getWsdl(client, context, dispatchContainer, visitedUrls, location).toURI().toURL() .toString()); } } wsdl = element.toXml(); } catch (Exception e) { logger.warn("Unable to cache imports for WSDL at URL: " + wsdlUrl, e); } FileUtils.writeStringToFile(tempFile, wsdl); dispatchContainer.getTempFiles().add(tempFile); return tempFile; } else { throw new Exception( "Unable to load WSDL at URL \"" + wsdlUrl + "\": " + String.valueOf(responseStatusLine)); } }
From source file:org.apache.manifoldcf.scriptengine.ScriptParser.java
public static String convertToString(HttpResponse httpResponse) throws IOException { HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream is = entity.getContent(); try {// w ww . j a v a 2s . c om Charset charSet; try { ContentType ct = ContentType.get(entity); if (ct == null) charSet = StandardCharsets.UTF_8; else charSet = ct.getCharset(); } catch (ParseException e) { charSet = StandardCharsets.UTF_8; } char[] buffer = new char[65536]; Reader r = new InputStreamReader(is, charSet); Writer w = new StringWriter(); try { while (true) { int amt = r.read(buffer); if (amt == -1) break; w.write(buffer, 0, amt); } } finally { w.flush(); } return w.toString(); } finally { is.close(); } } return ""; }
From source file:org.apache.manifoldcf.crawler.connectors.wiki.WikiConnector.java
protected static String readResponseAsString(HttpResponse httpResponse) throws IOException { HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream is = entity.getContent(); try {//from w w w. j a v a2s .c o m Charset charSet; try { ContentType ct = ContentType.get(entity); if (ct == null) charSet = StandardCharsets.UTF_8; else charSet = ct.getCharset(); } catch (ParseException e) { charSet = StandardCharsets.UTF_8; } char[] buffer = new char[65536]; Reader r = new InputStreamReader(is, charSet); Writer w = new StringWriter(); try { while (true) { int amt = r.read(buffer); if (amt == -1) break; w.write(buffer, 0, amt); } } finally { w.flush(); } return w.toString(); } finally { is.close(); } } return ""; }
From source file:org.eclipse.californium.proxy.HttpTranslator.java
/** * Gets the coap media type associated to the http entity. Firstly, it looks * for a valid mapping in the property file. If this step fails, then it * tries to explicitly map/parse the declared mime/type by the http entity. * If even this step fails, it sets application/octet-stream as * content-type./*from ww w . j a v a2 s . co m*/ * * @param httpMessage * * * @return the coap media code associated to the http message entity. * @see * HttpHeader, ContentType, MediaTypeRegistry */ public static int getCoapMediaType(HttpMessage httpMessage) { if (httpMessage == null) { throw new IllegalArgumentException("httpMessage == null"); } // get the entity HttpEntity httpEntity = null; if (httpMessage instanceof HttpResponse) { httpEntity = ((HttpResponse) httpMessage).getEntity(); } else if (httpMessage instanceof HttpEntityEnclosingRequest) { httpEntity = ((HttpEntityEnclosingRequest) httpMessage).getEntity(); } // check that the entity is actually present in the http message if (httpEntity == null) { throw new IllegalArgumentException("The http message does not contain any httpEntity."); } // set the content-type with a default value int coapContentType = MediaTypeRegistry.UNDEFINED; // get the content-type from the entity ContentType contentType = ContentType.get(httpEntity); if (contentType == null) { // if the content-type is not set, search in the headers Header contentTypeHeader = httpMessage.getFirstHeader("content-type"); if (contentTypeHeader != null) { String contentTypeString = contentTypeHeader.getValue(); contentType = ContentType.parse(contentTypeString); } } // check if there is an associated content-type with the current http // message if (contentType != null) { // get the value of the content-type String httpContentTypeString = contentType.getMimeType(); // delete the last part (if any) httpContentTypeString = httpContentTypeString.split(";")[0]; // retrieve the mapping from the property file String coapContentTypeString = HTTP_TRANSLATION_PROPERTIES .getProperty(KEY_HTTP_CONTENT_TYPE + httpContentTypeString); if (coapContentTypeString != null) { coapContentType = Integer.parseInt(coapContentTypeString); } else { // try to parse the media type if the property file has given to // mapping coapContentType = MediaTypeRegistry.parse(httpContentTypeString); } } // if not recognized, the content-type should be // application/octet-stream (draft-castellani-core-http-mapping 6.2) if (coapContentType == MediaTypeRegistry.UNDEFINED) { coapContentType = MediaTypeRegistry.APPLICATION_OCTET_STREAM; } return coapContentType; }
From source file:org.eclipse.californium.proxy.HttpTranslator.java
/** * Gets the http request starting from a CoAP request. The method creates * the HTTP request through its request line. The request line is built with * the uri coming from the string representing the CoAP method and the uri * obtained from the proxy-uri option. If a payload is provided, the HTTP * request encloses an HTTP entity and consequently the content-type is set. * Finally, the CoAP options are mapped to the HTTP headers. * /*from www .jav a2 s . c om*/ * @param coapRequest * the coap request * * * * @return the http request * @throws TranslationException the translation * exception * @throws URISyntaxException the uRI syntax exception */ public static HttpRequest getHttpRequest(Request coapRequest) throws TranslationException { if (coapRequest == null) { throw new IllegalArgumentException("coapRequest == null"); } HttpRequest httpRequest = null; String coapMethod = null; switch (coapRequest.getCode()) { case GET: coapMethod = "GET"; break; case POST: coapMethod = "POST"; break; case PUT: coapMethod = "PUT"; break; case DELETE: coapMethod = "DELETE"; break; } // get the proxy-uri URI proxyUri; try { /* * The new draft (14) only allows one proxy-uri option. Thus, this * code segment has changed. */ String proxyUriString = URLDecoder.decode(coapRequest.getOptions().getProxyUri(), "UTF-8"); proxyUri = new URI(proxyUriString); } catch (UnsupportedEncodingException e) { LOGGER.warning("UTF-8 do not support this encoding: " + e); throw new TranslationException("UTF-8 do not support this encoding", e); } catch (URISyntaxException e) { LOGGER.warning("Cannot translate the server uri" + e); throw new InvalidFieldException("Cannot get the proxy-uri from the coap message", e); } // create the requestLine RequestLine requestLine = new BasicRequestLine(coapMethod, proxyUri.toString(), HttpVersion.HTTP_1_1); // get the http entity HttpEntity httpEntity = getHttpEntity(coapRequest); // create the http request if (httpEntity == null) { httpRequest = new BasicHttpRequest(requestLine); } else { httpRequest = new BasicHttpEntityEnclosingRequest(requestLine); ((HttpEntityEnclosingRequest) httpRequest).setEntity(httpEntity); // get the content-type from the entity and set the header ContentType contentType = ContentType.get(httpEntity); httpRequest.setHeader("content-type", contentType.toString()); } // set the headers Header[] headers = getHttpHeaders(coapRequest.getOptions().asSortedList(), ""); for (Header header : headers) { httpRequest.addHeader(header); } return httpRequest; }
From source file:org.eclipse.californium.proxy.HttpTranslator.java
/** * Sets the parameters of the incoming http response from a CoAP response. * The status code is mapped through the properties file and is set through * the StatusLine. The options are translated to the corresponding headers * and the max-age (in the header cache-control) is set to the default value * (60 seconds) if not already present. If the request method was not HEAD * and the coap response has a payload, the entity and the content-type are * set in the http response./*from w ww . ja v a 2 s . co m*/ * * @param coapResponse * the coap response * @param httpResponse * * * * @param httpRequest * HttpRequest * @throws TranslationException * the translation exception */ public static void getHttpResponse(HttpRequest httpRequest, Response coapResponse, HttpResponse httpResponse) throws TranslationException { if (httpRequest == null) { throw new IllegalArgumentException("httpRequest == null"); } if (coapResponse == null) { throw new IllegalArgumentException("coapResponse == null"); } if (httpResponse == null) { throw new IllegalArgumentException("httpResponse == null"); } // get/set the response code ResponseCode coapCode = coapResponse.getCode(); String httpCodeString = HTTP_TRANSLATION_PROPERTIES.getProperty(KEY_COAP_CODE + coapCode.value); if (httpCodeString == null || httpCodeString.isEmpty()) { LOGGER.warning("httpCodeString == null"); throw new TranslationException("httpCodeString == null"); } int httpCode = 0; try { httpCode = Integer.parseInt(httpCodeString.trim()); } catch (NumberFormatException e) { LOGGER.warning("Cannot convert the coap code in http status code" + e); throw new TranslationException("Cannot convert the coap code in http status code", e); } // create the http response and set the status line String reason = EnglishReasonPhraseCatalog.INSTANCE.getReason(httpCode, Locale.ENGLISH); StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, httpCode, reason); httpResponse.setStatusLine(statusLine); String uriString = httpRequest.getRequestLine().getUri(); int index_query = uriString.indexOf("//"); String query = uriString.substring(index_query + 2); int index_host = query.indexOf("/"); String host = query.substring(0, index_host); // set the headers Header[] headers = getHttpHeaders(coapResponse.getOptions().asSortedList(), host); httpResponse.setHeaders(headers); // set max-age if not already set if (!httpResponse.containsHeader("cache-control")) { httpResponse.setHeader("cache-control", "max-age=" + Long.toString(OptionNumberRegistry.Defaults.MAX_AGE)); } // get the http entity if the request was not HEAD if (!httpRequest.getRequestLine().getMethod().equalsIgnoreCase("head")) { if ((httpRequest.getRequestLine().getMethod().equalsIgnoreCase("put")) && (coapCode.value == 131)) { String linkPut = getLinkPut(coapResponse); Header link = new BasicHeader("Link", linkPut); httpResponse.addHeader(link); } // if the content-type is not set in the coap response and if the // response contains an error, then the content-type should set to // text-plain if (coapResponse.getOptions().getContentFormat() == MediaTypeRegistry.UNDEFINED && (ResponseCode.isClientError(coapCode) || ResponseCode.isServerError(coapCode))) { LOGGER.info("Set contenttype to TEXT_PLAIN"); coapResponse.getOptions().setContentFormat(MediaTypeRegistry.TEXT_PLAIN); } HttpEntity httpEntity = getHttpEntity(coapResponse); if (httpEntity != null) { httpResponse.setEntity(httpEntity); // get the content-type from the entity and set the header ContentType contentType = ContentType.get(httpEntity); httpResponse.setHeader("content-type", contentType.toString()); } } }
From source file:org.elasticsearch.client.RequestLogger.java
/** * Creates curl output for given response *//*from www . ja v a 2s . co m*/ static String buildTraceResponse(HttpResponse httpResponse) throws IOException { StringBuilder responseLine = new StringBuilder(); responseLine.append("# ").append(httpResponse.getStatusLine()); for (Header header : httpResponse.getAllHeaders()) { responseLine.append("\n# ").append(header.getName()).append(": ").append(header.getValue()); } responseLine.append("\n#"); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { if (entity.isRepeatable() == false) { entity = new BufferedHttpEntity(entity); } httpResponse.setEntity(entity); ContentType contentType = ContentType.get(entity); Charset charset = StandardCharsets.UTF_8; if (contentType != null && contentType.getCharset() != null) { charset = contentType.getCharset(); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset))) { String line; while ((line = reader.readLine()) != null) { responseLine.append("\n# ").append(line); } } } return responseLine.toString(); }
From source file:org.structr.rest.common.HttpHelper.java
public static String charset(final HttpResponse response) { final ContentType contentType = ContentType.get(response.getEntity()); String charset = "UTF-8"; if (contentType != null && contentType.getCharset() != null) { charset = contentType.getCharset().toString(); }// w w w. java 2s . c o m return charset; }