List of usage examples for com.google.common.net MediaType parse
public static MediaType parse(String input)
From source file:com.outerspacecat.openid.rp.Endpoint.java
/** * Requests an association from this endpoint. * /*from w w w .j a v a2s . c o m*/ * @param associationType the association type. Must be non {@code null}. * @param sessionType the session type. Must be non {@code null}. * @return an association. Never {@code null}. * @throws IOException if an association cannot be created */ Association requestAssociation(final AssociationType associationType, final SessionType sessionType) throws IOException { Preconditions.checkNotNull(associationType, "associationType required"); Preconditions.checkNotNull(sessionType, "sessionType required"); StringBuilder sb = new StringBuilder(); sb.append(getUri()).append("?openid.ns="); sb.append(URLEncoder.encode("http://specs.openid.net/auth/2.0", "UTF-8")); sb.append("&openid.mode=associate&openid.assoc_type="); sb.append(URLEncoder.encode(associationType.getValue(), "UTF-8")); sb.append("&openid.session_type="); sb.append(URLEncoder.encode(sessionType.getValue(), "UTF-8")); DhSession dhSession = null; if (sessionType == SessionType.DH_SHA1 || sessionType == SessionType.DH_SHA256) { dhSession = DhSession.get(sessionType.getAlgorithm()); sb.append("&openid.dh_modulus="); sb.append(URLEncoder.encode(dhSession.getBase64Modulus(), "UTF-8")); sb.append("&openid.dh_gen="); sb.append(URLEncoder.encode(dhSession.getBase64Generator(), "UTF-8")); sb.append("&openid.dh_consumer_public="); sb.append(URLEncoder.encode(dhSession.getBase64PublicKey(), "UTF-8")); } HttpURLConnection conn = null; BufferedReader r = null; try { conn = (HttpURLConnection) new URL(sb.toString()).openConnection(); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setConnectTimeout(2000); conn.setReadTimeout(5000); conn.addRequestProperty("Accept", "text/plain"); conn.addRequestProperty("Accept-Encoding", "gzip"); conn.connect(); int code = conn.getResponseCode(); InputStream in = null; if (code / 100 == 5) { throw new ServerErrorException(null, code); } else if (code == 400) { in = conn.getErrorStream(); } else if (code == 200) { in = conn.getInputStream(); } else { throw new IOException("unexpected response code: " + code); } in = new BufferedInputStream(in); MediaType mt = null; try { if (conn.getContentType() != null) mt = MediaType.parse(conn.getContentType()); } catch (IllegalArgumentException e) { } if ("gzip".equalsIgnoreCase(conn.getContentEncoding())) in = new GZIPInputStream(in); Charset cs = Charsets.UTF_8; if (mt != null && mt.charset().isPresent()) cs = mt.charset().get(); r = new BufferedReader(new InputStreamReader(in, cs)); Map<String, String> params = new HashMap<String, String>(); for (String l = r.readLine(); l != null; l = r.readLine()) { String[] parts = l.split(":", 2); if (parts.length != 2) throw new IOException("invalid line: " + l); params.put(parts[0], parts[1]); } if (code == 400) { String errorParam = params.get("error"); String errorCodeParam = params.get("error_code"); String assocTypeParam = params.get("assoc_type"); String sessionTypeParam = params.get("session_type"); if (!errorCodeParam.equals("unsupported-type")) throw new IOException("bad request, error=" + errorParam + ",error_code=" + errorCodeParam + "session_type=" + sessionTypeParam + ",assoc_type=" + assocTypeParam); AssociationType supportedAssociationType = null; if (assocTypeParam != null && AssociationType.isValidValue(assocTypeParam)) supportedAssociationType = AssociationType.valueOf(assocTypeParam); SessionType supportedSessionType = null; if (sessionTypeParam != null && SessionType.isValidValue(sessionTypeParam)) supportedSessionType = SessionType.valueOf(sessionTypeParam); throw new UnsupportedTypeException(errorParam, supportedAssociationType, supportedSessionType); } return Association.create(this, associationType, sessionType, dhSession, params); } finally { if (r != null) r.close(); } }
From source file:org.wisdom.api.utils.KnownMimeTypes.java
/** * Gets a {@link MediaType} for the extension of a file or url. * * @param extension the extension, without the "." * @return the parsed media type if known, {@literal null} otherwise. * @since 0.8.1/*from w w w . j a va 2s . c o m*/ */ public static MediaType getMediaTypeByExtension(String extension) { final String input = EXTENSIONS.get(extension); if (input == null) { return null; } return MediaType.parse(input); }
From source file:org.sonatype.nexus.repository.storage.DefaultContentValidator.java
/** * Removes any parameter (like charset) for simpler matching. */// w w w . ja va 2 s . c o m @Nullable private String mediaTypeWithoutParameters(final String declaredMediaType) { if (Strings.isNullOrEmpty(declaredMediaType)) { return null; } try { MediaType mediaType = MediaType.parse(declaredMediaType); return mediaType.withoutParameters().toString(); } catch (IllegalArgumentException e) { throw new InvalidContentException("Invalid declared contentType: " + declaredMediaType, e); } }
From source file:org.wisdom.api.router.Route.java
/** * Sets the set of media types accepted by the route. * * @param types the set of type// w w w .j a va2s . com * @return the current route */ public Route accepts(String... types) { Preconditions.checkNotNull(types); final ImmutableSet.Builder<MediaType> builder = new ImmutableSet.Builder<>(); builder.addAll(this.acceptedMediaTypes); for (String s : types) { builder.add(MediaType.parse(s)); } this.acceptedMediaTypes = builder.build(); return this; }
From source file:com.amazon.blueshift.bluefront.android.audio.encoder.OpusEncoder.java
/** * Create a new Opus encoder with the following settings. * @param frameSizeMillis the frame size in milliseconds, must be 5, 10, 20, 40, or 60. * @param sampleRate the sample rate of the PCM audio in Hz, must be one of 8000, 12000, 16000, * 24000, or 48000.// ww w. j a va 2s . com * @param channels the number of channels of audio, can be 1 or 2. * @param bitrate the Opus bitrate, can be between 6000 and 512000 in increments of 400. * @param complexity the complexity of the Opus audio, should be an integer between 1 and 10. * @throws AudioEncoderException when there's an error initializing the encoder. */ public OpusEncoder(final int frameSizeMillis, final int sampleRate, final int channels, final int bitrate, final int complexity) throws AudioEncoderException { Preconditions.checkArgument(VALID_FRAME_SIZE_MILLIS.contains(frameSizeMillis), "Frame size is invalid"); Preconditions.checkArgument(VALID_SAMPLES_RATES.contains(sampleRate), "Sample rate is invalid"); Preconditions.checkArgument(channels == 1 || channels == 2, "Number of channels is invalid"); Preconditions.checkArgument(bitrate >= MIN_BIT_RATE && bitrate <= MAX_BIT_RATE && (bitrate - MIN_BIT_RATE) % BIT_RATE_INTERVAL == 0, "Bitrate is invalid"); Preconditions.checkArgument(complexity >= MIN_COMPLEXITY && complexity <= MAX_COMPLEXITY, "Complexity is invalid"); mFrameSizeMillis = frameSizeMillis; mSampleRate = sampleRate; mChannels = channels; mBitrate = bitrate; mComplexity = complexity; mOpusEncoder = createOpusEncoder(sampleRate, channels, bitrate, complexity, IS_VBR, APPLICATION_AUDIO, SIGNAL_VOICE); mPacketSize = bitrate * frameSizeMillis / (Byte.SIZE * MS_PER_SEC); mFrameSize = sampleRate * frameSizeMillis / MS_PER_SEC; mMediaType = MediaType.parse("audio/x-cbr-opus-with-preamble") .withParameter("bit-rate", Integer.toString(bitrate)) .withParameter("frame-size-milliseconds", Integer.toString(frameSizeMillis)) .withParameter("preamble-size", "0"); }
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(); }//w w w .java 2 s . c om } return encoding; }
From source file:com.github.dirkraft.dropwizard.fileassets.FileAssetServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from ww w . j a v a 2s . co m final StringBuilder builder = new StringBuilder(req.getServletPath()); if (req.getPathInfo() != null) { builder.append(req.getPathInfo()); } final CachedAsset cachedAsset = loadAsset(builder.toString()); if (cachedAsset == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (isCachedClientSide(req, cachedAsset)) { resp.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } resp.setDateHeader(HttpHeaders.LAST_MODIFIED, cachedAsset.getLastModifiedTime()); resp.setHeader(HttpHeaders.ETAG, cachedAsset.getETag()); final String mimeTypeOfExtension = req.getServletContext().getMimeType(req.getRequestURI()); MediaType mediaType = DEFAULT_MEDIA_TYPE; if (mimeTypeOfExtension != null) { try { mediaType = MediaType.parse(mimeTypeOfExtension); if (defaultCharset != null && mediaType.is(MediaType.ANY_TEXT_TYPE)) { mediaType = mediaType.withCharset(defaultCharset); } } catch (IllegalArgumentException ignore) { } } resp.setContentType(mediaType.type() + '/' + mediaType.subtype()); if (mediaType.charset().isPresent()) { resp.setCharacterEncoding(mediaType.charset().get().toString()); } try (ServletOutputStream output = resp.getOutputStream()) { output.write(cachedAsset.getResource()); } } catch (RuntimeException | URISyntaxException ignored) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:com.linecorp.armeria.server.http.encoding.HttpEncodedResponse.java
private boolean shouldEncodeResponse(HttpHeaders headers) { if (headers.contains(HttpHeaderNames.CONTENT_ENCODING)) { // We don't do automatic encoding if the user-supplied headers contain // Content-Encoding. return false; }// w w w . j a v a 2s. c om if (headers.contains(HttpHeaderNames.CONTENT_TYPE)) { // Make sure the content type is worth encoding. try { MediaType contentType = MediaType.parse(headers.get(HttpHeaderNames.CONTENT_TYPE)); if (!encodableContentTypePredicate.test(contentType)) { return false; } } catch (IllegalArgumentException e) { // Don't know content type of response, don't encode. return false; } } if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { // We switch to chunked encoding and compress the response if it's reasonably // large as the compression savings should outweigh the chunked encoding // overhead. if (headers.getInt(HttpHeaderNames.CONTENT_LENGTH) < minBytesToForceChunkedAndEncoding) { return false; } } return true; }
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).//from www . j ava 2 s . c om */ @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:org.wisdom.api.router.Route.java
/** * Sets the set of media types produced by the route. * * @param types the set of type/*ww w . java 2s . c o m*/ * @return the current route */ public Route produces(String... types) { Preconditions.checkNotNull(types); final ImmutableSet.Builder<MediaType> builder = new ImmutableSet.Builder<>(); builder.addAll(this.producedMediaTypes); for (String s : types) { final MediaType mt = MediaType.parse(s); if (mt.hasWildcard()) { throw new RoutingException("A route cannot `produce` a mime type with a wildcard: " + mt); } builder.add(mt); } this.producedMediaTypes = builder.build(); return this; }