List of usage examples for com.google.common.net MediaType charset
public Optional<Charset> charset()
From source file:org.mule.module.http.internal.listener.HttpRequestToMuleEvent.java
public static MuleEvent transform(final HttpRequestContext requestContext, final MuleContext muleContext, final FlowConstruct flowConstruct, Boolean parseRequest, ListenerPath listenerPath) throws HttpRequestParsingException { final HttpRequest request = requestContext.getRequest(); final Collection<String> headerNames = request.getHeaderNames(); Map<String, Object> inboundProperties = new HashMap<>(); Map<String, Object> outboundProperties = new HashMap<>(); for (String headerName : headerNames) { final Collection<String> values = request.getHeaderValues(headerName); if (values.size() == 1) { inboundProperties.put(headerName, values.iterator().next()); } else {/* w w w. j a v a 2 s. c o m*/ inboundProperties.put(headerName, values); } } new HttpMessagePropertiesResolver().setMethod(request.getMethod()) .setProtocol(request.getProtocol().asString()).setUri(request.getUri()) .setListenerPath(listenerPath).setRemoteHostAddress(resolveRemoteHostAddress(requestContext)) .setScheme(requestContext.getScheme()) .setClientCertificate(requestContext.getClientConnection().getClientCertificate()) .addPropertiesTo(inboundProperties); final Map<String, DataHandler> inboundAttachments = new HashMap<>(); Object payload = NullPayload.getInstance(); if (parseRequest) { final HttpEntity entity = request.getEntity(); if (entity != null && !(entity instanceof EmptyHttpEntity)) { if (entity instanceof MultipartHttpEntity) { inboundAttachments.putAll(createDataHandlerFrom(((MultipartHttpEntity) entity).getParts())); } else { final String contentTypeValue = request.getHeaderValue(HttpHeaders.Names.CONTENT_TYPE); if (contentTypeValue != null) { final MediaType mediaType = MediaType.parse(contentTypeValue); String encoding = mediaType.charset().isPresent() ? mediaType.charset().get().name() : Charset.defaultCharset().name(); outboundProperties.put(MULE_ENCODING_PROPERTY, encoding); if ((mediaType.type() + "/" + mediaType.subtype()) .equals(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED)) { try { payload = decodeUrlEncodedBody( IOUtils.toString(((InputStreamHttpEntity) entity).getInputStream()), encoding); } catch (IllegalArgumentException e) { throw new HttpRequestParsingException("Cannot decode x-www-form-urlencoded payload", e); } } else if (entity instanceof InputStreamHttpEntity) { payload = ((InputStreamHttpEntity) entity).getInputStream(); } } else if (entity instanceof InputStreamHttpEntity) { payload = ((InputStreamHttpEntity) entity).getInputStream(); } } } } else { final InputStreamHttpEntity inputStreamEntity = request.getInputStreamEntity(); if (inputStreamEntity != null) { payload = inputStreamEntity.getInputStream(); } } final DefaultMuleMessage defaultMuleMessage = new DefaultMuleMessage(payload, inboundProperties, outboundProperties, inboundAttachments, muleContext); return new DefaultMuleEvent(defaultMuleMessage, resolveUri(requestContext), REQUEST_RESPONSE, flowConstruct, new DefaultMuleSession()); }
From source file:com.google.devtools.build.lib.bazel.repository.downloader.HttpConnection.java
/** * Attempts to detect the encoding the HTTP reponse is using. * * <p>This attempts to read the Content-Encoding header, then the Content-Type header, * then just falls back to UTF-8.</p> * * @throws IOException If something goes wrong (the encoding isn't parsable or is, but isn't * supported by the system).//w w w. j ava 2 s. co m */ @VisibleForTesting static Charset getEncoding(HttpURLConnection connection) throws IOException { String encoding = connection.getContentEncoding(); if (encoding != null) { if (Charset.availableCharsets().containsKey(encoding)) { try { return Charset.forName(encoding); } catch (IllegalArgumentException | UnsupportedOperationException e) { throw new IOException("Got invalid encoding from " + connection.getURL() + ": " + encoding); } } else { throw new IOException("Got unavailable encoding from " + connection.getURL() + ": " + encoding); } } encoding = connection.getContentType(); if (encoding == null) { return StandardCharsets.UTF_8; } try { MediaType mediaType = MediaType.parse(encoding); if (mediaType == null) { return StandardCharsets.UTF_8; } Optional<Charset> charset = mediaType.charset(); if (charset.isPresent()) { return charset.get(); } } catch (IllegalArgumentException | IllegalStateException e) { throw new IOException("Got invalid encoding from " + connection.getURL() + ": " + encoding); } return StandardCharsets.UTF_8; }
From source file:com.buildria.mocking.builder.action.BodyAction.java
private Charset getCharsetOrUTF8(MediaType mediaType) { return mediaType.charset().or(StandardCharsets.UTF_8); }
From source file:com.outerspacecat.openid.rp.Provider.java
/** * Returns a well-known provider.//w ww .j a v a 2s . c o m * * @param metadata information about the provider. Must be non {@code null}. * @return a provider. Never {@code null}. * @throws IOException if a provider cannot be obtained */ public static Provider get(final WellKnown metadata) throws IOException { Preconditions.checkNotNull(metadata, "metadata required"); Provider cached = null; synchronized (wellKnownCache) { Optional<Provider> option = wellKnownCache.get(metadata.getUri()); if (option.isPresent()) cached = option.get(); } if (cached != null && !cached.isExpired()) return cached; HttpURLConnection conn = null; InputStream in = null; try { conn = (HttpURLConnection) metadata.getUri().toURL().openConnection(); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.addRequestProperty("Accept", "application/xrds+xml"); conn.addRequestProperty("Accept-Encoding", "gzip"); conn.connect(); int code = conn.getResponseCode(); if (code / 100 != 2) throw new IOException("unexpected response code: " + code); MediaType mt = null; try { if (conn.getContentType() != null) mt = MediaType.parse(conn.getContentType()); } catch (IllegalArgumentException e) { } Instant expirationDate = null; if (conn.getExpiration() > 0) { expirationDate = Instant.ofEpochMilli(conn.getExpiration()); } else { expirationDate = Instant.now(); } in = new BufferedInputStream(conn.getInputStream()); if ("gzip".equalsIgnoreCase(conn.getContentEncoding())) in = new GZIPInputStream(in); InputSource src = null; if (mt != null && mt.charset().isPresent()) { src = new InputSource(new InputStreamReader(in, mt.charset().get())); } else { src = new InputSource(in); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); Document doc = factory.newDocumentBuilder().parse(src); List<Service> services = new ArrayList<Service>(); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(NAMESPACE_CONTEXT); NodeList serviceNodes = (NodeList) xpath.evaluate("/xrds:XRDS/xrd:XRD/xrd:Service", doc, XPathConstants.NODESET); for (int i = 0; i < serviceNodes.getLength(); ++i) { Node serviceNode = serviceNodes.item(i); Set<String> types = new HashSet<String>(); NodeList typeNodes = (NodeList) xpath.evaluate("xrd:Type", serviceNode, XPathConstants.NODESET); for (int j = 0; j < typeNodes.getLength(); ++j) types.add(typeNodes.item(j).getTextContent()); if (!types.contains("http://specs.openid.net/auth/2.0/server")) continue; int servicePriority = 0; Double servicePriorityNode = (Double) xpath.evaluate("@priority", serviceNode, XPathConstants.NUMBER); if (servicePriorityNode != null && servicePriorityNode >= 0) servicePriority = servicePriorityNode.intValue(); List<Endpoint> endpoints = new ArrayList<Endpoint>(); NodeList uriNodes = (NodeList) xpath.evaluate("xrd:URI", serviceNode, XPathConstants.NODESET); for (int j = 0; j < uriNodes.getLength(); ++j) { Node uriNode = uriNodes.item(j); int uriPriority = 0; Double uriPriorityNode = (Double) xpath.evaluate("@priority", uriNode, XPathConstants.NUMBER); if (uriPriorityNode != null && uriPriorityNode >= 0) uriPriority = uriPriorityNode.intValue(); try { URI uri = new URI(uriNode.getTextContent()); if (uri.getScheme().equals("http") || uri.getScheme().equals("https")) endpoints.add(new Endpoint(uriPriority, uri)); } catch (URISyntaxException e) { } } if (!endpoints.isEmpty()) { Collections.shuffle(endpoints); services.add(new Service(servicePriority, endpoints)); } } if (services.isEmpty()) throw new IOException("could not perform discovery on well-known URI: " + metadata.getUri()); Collections.shuffle(services); Provider ret = new Provider(services, expirationDate); if (!ret.isExpired()) { synchronized (wellKnownCache) { wellKnownCache.put(metadata.getUri(), ret); } } return ret; } catch (XPathException e) { throw new IOException(e); } catch (FactoryConfigurationError e) { throw new RuntimeException(e); } catch (SAXException e) { throw new IOException(e); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } finally { if (in != null) in.close(); } }
From source file:com.bennavetta.appsite.processor.scripting.ScriptingProcessor.java
@Override public void process(String path, MediaType type, InputStream in, OutputStream out, Request request, Response response) throws Exception { Charset encoding = (type.charset().isPresent() ? type.charset().get() : Charsets.UTF_8); String scriptText = null;//from ww w . j a v a 2s .co m try (Reader reader = new InputStreamReader(in, encoding)) { scriptText = CharStreams.toString(reader); } Script script = factory.getScript(scriptText); script.run(request, response, out); }
From source file:org.openqa.selenium.remote.http.HttpMessage.java
public String getContentString() { Charset charset = UTF_8;/* w w w. j a va2 s.co m*/ try { String contentType = getHeader(CONTENT_TYPE); if (contentType != null) { MediaType mediaType = MediaType.parse(contentType); charset = mediaType.charset().or(UTF_8); } } catch (IllegalArgumentException ignored) { // Do nothing. } return new String(content, charset); }
From source file:org.mule.module.http.internal.request.HttpResponseToMuleEvent.java
private String getEncoding(String responseContentType) { String encoding = Charset.defaultCharset().name(); if (responseContentType != null) { MediaType mediaType = MediaType.parse(responseContentType); if (mediaType.charset().isPresent()) { encoding = mediaType.charset().get().name(); }//from w w w. j a v a2 s .com } return encoding; }
From source file:com.buildria.mocking.builder.rule.BodyRule.java
@Override public boolean apply(@Nonnull Call call) { Objects.requireNonNull(call); byte[] body = call.getBody(); if (body == null || body.length == 0) { return matcher.matches(body); }/* w w w .j a va 2 s . c om*/ MediaType contentType = call.getContentType(); if (contentType == null) { throw new MockingException("No Content-Type header."); } Charset charset = contentType.charset().or(StandardCharsets.UTF_8); String content = new String(body, charset); Object obj = convertContent(contentType.subtype(), content, path); return matcher.matches(obj); }
From source file:jp.opencollector.guacamole.auth.delegated.DelegatedAuthenticationProvider.java
private static Optional<GuacamoleConfiguration> buildConfigurationFromRequest(HttpServletRequest req) throws GuacamoleException { try {/* w w w .ja v a 2 s . c o m*/ if (req.getClass().getName().equals("org.glyptodon.guacamole.net.basic.rest.APIRequest")) { final GuacamoleConfiguration config = new GuacamoleConfiguration(); final String protocol = req.getParameter("protocol"); if (protocol == null) throw new GuacamoleException("required parameter \"protocol\" is missing"); config.setProtocol(protocol); for (Map.Entry<String, String[]> param : req.getParameterMap().entrySet()) { String[] values = param.getValue(); if (values.length > 0) config.setParameter(param.getKey(), values[0]); } return Optional.of(config); } else { final ServletInputStream is = req.getInputStream(); if (!is.isReady()) { MediaType contentType = MediaType.parse(req.getContentType()); boolean invalidContentType = true; if (contentType.type().equals("application")) { if (contentType.subtype().equals("json")) { invalidContentType = false; } else if (contentType.subtype().equals("x-www-form-urlencoded") && req.getParameter("token") != null) { return Optional.<GuacamoleConfiguration>absent(); } } if (invalidContentType) throw new GuacamoleException(String.format("expecting application/json, got %s", contentType.withoutParameters())); final GuacamoleConfiguration config = new GuacamoleConfiguration(); try { final ObjectMapper mapper = new ObjectMapper(); JsonNode root = (JsonNode) mapper.readTree( createJsonParser(req.getInputStream(), contentType.charset().or(UTF_8), mapper)); { final JsonNode protocol = root.get("protocol"); if (protocol == null) throw new GuacamoleException("required parameter \"protocol\" is missing"); final JsonNode parameters = root.get("parameters"); if (parameters == null) throw new GuacamoleException("required parameter \"parameters\" is missing"); config.setProtocol(protocol.asText()); { for (Iterator<Entry<String, JsonNode>> i = parameters.fields(); i.hasNext();) { Entry<String, JsonNode> member = i.next(); config.setParameter(member.getKey(), member.getValue().asText()); } } } } catch (ClassCastException e) { throw new GuacamoleException("error occurred during parsing configuration", e); } return Optional.of(config); } else { return Optional.<GuacamoleConfiguration>absent(); } } } catch (IOException e) { throw new GuacamoleException("error occurred during retrieving configuration from the request body", e); } }
From source file:com.mastfrog.acteur.ContentConverter.java
private Charset findCharset(MediaType mt) { if (mt == null) { return charset.get(); }//from www. j a v a2 s . co m if (mt.charset().isPresent()) { return mt.charset().get(); } return charset.get(); }