Java Code Examples for com.google.common.net.MediaType#parse()
The following examples show how to use
com.google.common.net.MediaType#parse() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultContentValidator.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * Removes any parameter (like charset) for simpler matching. */ @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) { //https://maven.oracle.com is sending out incomplete content-type header, so lets try to clean it up and reprocess //i.e. 'Application/jar;charset=' int idx = declaredMediaType.indexOf(';'); if (idx >= 0) { String parsedDeclaredMediaType = declaredMediaType.substring(0, idx); log.debug("Invalid declared contentType {} will retry with {}", declaredMediaType, parsedDeclaredMediaType, e); return mediaTypeWithoutParameters(parsedDeclaredMediaType); } throw new InvalidContentException("Content type could not be determined: " + declaredMediaType, e); } }
Example 2
Source File: FakeRequest.java From wisdom with Apache License 2.0 | 6 votes |
/** * Checks if this request accepts a given media type. * * @param mimeType the mime type to check. * @return {@literal null} as this is a fake request. */ @Override public boolean accepts(String mimeType) { String contentType = getHeader(HeaderNames.ACCEPT); if (contentType == null) { contentType = MimeTypes.HTML; } // For performance reason, we first try a full match: if (contentType.contains(mimeType)) { return true; } // Else check the media types: MediaType input = MediaType.parse(mimeType); for (MediaType type : mediaTypes()) { if (input.is(type)) { return true; } } return false; }
Example 3
Source File: NettyHttpServletResponse.java From spring-boot-starter-netty with Apache License 2.0 | 6 votes |
@Override public void setContentType(String type) { if (isCommitted()) { return; } if (hasWriter()) { return; } if (null == type) { contentType = null; return; } MediaType mediaType = MediaType.parse(type); Optional<Charset> charset = mediaType.charset(); if (charset.isPresent()) { setCharacterEncoding(charset.get().name()); } contentType = mediaType.type() + '/' + mediaType.subtype(); }
Example 4
Source File: DownloadTraceHttpHelper.java From tracecompass with Eclipse Public License 2.0 | 6 votes |
/** * Try to find the name of the file by using connection information. * * @param connection * HTTP connection * @return File name */ private static String getFileName(HttpURLConnection connection) { String fileName = getLastSegmentUrl(connection.getURL().toString()); String contentType = connection.getContentType(); if (contentType != null) { MediaType type = MediaType.parse(contentType); if (type.is(MediaType.ANY_APPLICATION_TYPE)) { String contentDisposition = connection.getHeaderField(CONTENT_DISPOSITION); if (contentDisposition != null) { String[] content = contentDisposition.split(";"); //$NON-NLS-1$ for (String string : content) { if (string.contains("filename=")) { //$NON-NLS-1$ int index = string.indexOf('"'); fileName = string.substring(index + 1, string.length() - 1); } } } } } return fileName; }
Example 5
Source File: Engine.java From wisdom with Apache License 2.0 | 6 votes |
/** * Finds the 'best' content serializer for the given accept headers. * * @param mediaTypes the ordered set of {@link com.google.common.net.MediaType} from the {@code ACCEPT} header. * @return the best serializer from the list matching the {@code ACCEPT} header, {@code null} if none match */ @Override public ContentSerializer getBestSerializer(Collection<MediaType> mediaTypes) { if (mediaTypes == null || mediaTypes.isEmpty()) { mediaTypes = ImmutableList.of(MediaType.HTML_UTF_8); } for (MediaType type : mediaTypes) { for (ContentSerializer ser : serializers) { MediaType mt = MediaType.parse(ser.getContentType()); if (mt.is(type.withoutParameters())) { return ser; } } } return null; }
Example 6
Source File: RequestFromVertx.java From wisdom with Apache License 2.0 | 6 votes |
/** * Check if this request accepts a given media type. * * @return true if <code>mimeType</code> is in the Accept header, otherwise false */ @Override public boolean accepts(String mimeType) { String contentType = request.headers().get(HeaderNames.ACCEPT); if (contentType == null) { contentType = MimeTypes.HTML; } // For performance reason, we first try a full match: if (contentType.contains(mimeType)) { return true; } // Else check the media types: MediaType input = MediaType.parse(mimeType); for (MediaType type : mediaTypes()) { if (input.is(type)) { return true; } } return false; }
Example 7
Source File: KatharsisInvoker.java From katharsis-framework with Apache License 2.0 | 6 votes |
private boolean isAcceptableMediaType(KatharsisInvokerContext invokerContext) { String acceptHeader = invokerContext.getRequestHeader("Accept"); if (acceptHeader != null) { String[] accepts = acceptHeader.split(","); MediaType acceptableType; for (String mediaTypeItem : accepts) { acceptableType = MediaType.parse(mediaTypeItem.trim()); if (JsonApiMediaType.isCompatibleMediaType(acceptableType)) { return true; } } } return false; }
Example 8
Source File: Negotiation.java From wisdom with Apache License 2.0 | 6 votes |
/** * 'Accept' based negotiation. * This method determines the result to send to the client based on the 'Accept' header of the request. * The returned result is enhanced with the 'Vary' header set to {@literal Accept}. * <p/> * This methods retrieves the accepted media type in their preference order and check, * one-by-one if the given results match one of them. So, it ensures we get the most acceptable result. * * @param results the set of result structured as follows: mime-type -> result. The mime-type (keys) must be * valid mime type such as 'application/json' or 'text/html'. * @return the selected result, or a result with the status {@link org.wisdom.api.http.Status#NOT_ACCEPTABLE} if * none of the given results match the request. */ public static Result accept(Map<String, ? extends Result> results) { Context context = Context.CONTEXT.get(); if (context == null) { throw new IllegalStateException("Negotiation cannot be achieved outside of a request"); } Collection<MediaType> accepted = context.request().mediaTypes(); // accepted cannot be empty, if the header is missing text/* is added. for (MediaType media : accepted) { // Do we have a matching key. for (Map.Entry<String, ? extends Result> entry : results.entrySet()) { MediaType input = MediaType.parse(entry.getKey()); if (input.is(media)) { return entry.getValue().with(HeaderNames.VARY, HeaderNames.ACCEPT); } } } return Results.status(Status.NOT_ACCEPTABLE); }
Example 9
Source File: MCRAudioVideoExtender.java From mycore with GNU General Public License v3.0 | 6 votes |
/** * Helper method that connects to the given URL and returns the response as * a String * * @param url * the URL to connect to * @return the response content as a String */ protected String getMetadata(String url) throws MCRPersistenceException { try { URLConnection connection = getConnection(url); connection.setConnectTimeout(getConnectTimeout()); String contentType = connection.getContentType(); Charset charset = StandardCharsets.ISO_8859_1; //defined by RFC 2616 (sec 3.7.1) if (contentType != null) { MediaType mediaType = MediaType.parse(contentType); mediaType.charset().or(StandardCharsets.ISO_8859_1); } ByteArrayOutputStream out = new ByteArrayOutputStream(1024); forwardData(connection, out); return new String(out.toByteArray(), charset); } catch (IOException exc) { String msg = "Could not get metadata from Audio/Video Store URL: " + url; throw new MCRPersistenceException(msg, exc); } }
Example 10
Source File: NettyHttpServletResponse.java From spring-boot-starter-netty with GNU General Public License v3.0 | 6 votes |
@Override public void setContentType(String type) { if (isCommitted()) { return; } if (hasWriter()) { return; } if (null == type) { contentType = null; return; } MediaType mediaType = MediaType.parse(type); Optional<Charset> charset = mediaType.charset(); if (charset.isPresent()) { setCharacterEncoding(charset.get().name()); } contentType = mediaType.type() + '/' + mediaType.subtype(); }
Example 11
Source File: ScriptToResponse.java From purplejs with Apache License 2.0 | 5 votes |
private MediaType findContentType( final ScriptValue value, final ScriptValue body ) { final String type = ( value != null ) ? value.getValue( String.class ) : null; if ( type != null ) { return MediaType.parse( type ); } return new BodySerializer().findType( body ); }
Example 12
Source File: RequestFromVertx.java From wisdom with Apache License 2.0 | 5 votes |
/** * Get the content media type that is acceptable for the client. E.g. Accept: text/*;q=0.3, text/html;q=0.7, * text/html;level=1,text/html;level=2;q=0.4 * <p/> * The Accept request-header field can be used to specify certain media * types which are acceptable for the response. Accept headers can be used * to indicate that the request is specifically limited to a small set of * desired types, as in the case of a request for an in-line image. * * @return a MediaType that is acceptable for the * client or {@see MediaType#ANY_TEXT_TYPE} if not set * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" * >http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html</a> */ @Override public Collection<MediaType> mediaTypes() { String contentType = request.headers().get(HeaderNames.ACCEPT); if (contentType == null) { // Any text by default. return ImmutableList.of(MediaType.ANY_TEXT_TYPE); } TreeSet<MediaType> set = new TreeSet<>(new Comparator<MediaType>() { @Override public int compare(MediaType o1, MediaType o2) { double q1 = 1.0, q2 = 1.0; List<String> ql1 = o1.parameters().get("q"); List<String> ql2 = o2.parameters().get("q"); if (ql1 != null && !ql1.isEmpty()) { q1 = Double.parseDouble(ql1.get(0)); } if (ql2 != null && !ql2.isEmpty()) { q2 = Double.parseDouble(ql2.get(0)); } return new Double(q2).compareTo(q1); } }); // Split and sort. String[] segments = contentType.split(","); for (String segment : segments) { MediaType type = MediaType.parse(segment.trim()); set.add(type); } return set; }
Example 13
Source File: HttpMessage.java From selenium with Apache License 2.0 | 5 votes |
public Charset getContentEncoding() { Charset charset = UTF_8; 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 charset; }
Example 14
Source File: Route.java From wisdom with Apache License 2.0 | 5 votes |
/** * Sets the set of media types produced by the route. * * @param types the set of type * @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; }
Example 15
Source File: FileAssetServlet.java From robe with GNU Lesser General Public License v3.0 | 5 votes |
private void decideMimeAndEncoding(HttpServletRequest req, HttpServletResponse resp) { //Decide mimetype String mime = req.getServletContext().getMimeType(req.getRequestURI()); MediaType mediaType = (mime == null) ? DEFAULT_MEDIA_TYPE : MediaType.parse(mime); if (defaultCharset != null && mediaType.is(MediaType.ANY_TEXT_TYPE)) { mediaType = mediaType.withCharset(defaultCharset); } resp.setContentType(mediaType.type() + '/' + mediaType.subtype()); if (mediaType.charset().isPresent()) { resp.setCharacterEncoding(mediaType.charset().get().toString()); } }
Example 16
Source File: Email.java From email-mime-parser with Apache License 2.0 | 5 votes |
private boolean isValidImageMimeType(String imageMimeType) { // Here 'MediaType' of Google Guava library is 'MimeType' of Apache James mime4j MediaType mediaType = null; try { mediaType = MediaType.parse(imageMimeType); } catch (IllegalArgumentException e) { LOGGER.error(e.getMessage()); } return (mediaType != null); }
Example 17
Source File: FakeRequest.java From wisdom with Apache License 2.0 | 5 votes |
/** * @return {@literal empty} as this is a fake request. */ @Override public Collection<MediaType> mediaTypes() { String contentType = getHeader(HeaderNames.ACCEPT); if (contentType == null) { // Any text by default. return ImmutableList.of(MediaType.ANY_TEXT_TYPE); } TreeSet<MediaType> set = new TreeSet<>(new Comparator<MediaType>() { @Override public int compare(MediaType o1, MediaType o2) { double q1 = 1.0, q2 = 1.0; List<String> ql1 = o1.parameters().get("q"); List<String> ql2 = o2.parameters().get("q"); if (ql1 != null && !ql1.isEmpty()) { q1 = Double.parseDouble(ql1.get(0)); } if (ql2 != null && !ql2.isEmpty()) { q2 = Double.parseDouble(ql2.get(0)); } return new Double(q2).compareTo(q1); } }); // Split and sort. String[] segments = contentType.split(","); for (String segment : segments) { MediaType type = MediaType.parse(segment.trim()); set.add(type); } return set; }
Example 18
Source File: KnownMimeTypes.java From wisdom with Apache License 2.0 | 5 votes |
/** * 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 */ public static MediaType getMediaTypeByExtension(String extension) { final String input = EXTENSIONS.get(extension); if (input == null) { return null; } return MediaType.parse(input); }
Example 19
Source File: MultipartItemImpl.java From purplejs with Apache License 2.0 | 4 votes |
@Override public MediaType getContentType() { final String itemContentType = this.part.getContentType(); return itemContentType != null ? MediaType.parse( itemContentType ) : null; }
Example 20
Source File: S3Opener.java From render with GNU General Public License v2.0 | 4 votes |
@Override public ImagePlus openURL(final String url) { ImagePlus imagePlus = null; if (url.startsWith("s3://")) { String name = ""; final int index = url.lastIndexOf('/'); if (index > 0) { name = url.substring(index + 1); } try { if (handler == null) { buildS3Handler(); } final URL u = new URL(null, url, handler); final URLConnection uc = u.openConnection(); // assumes content type is always available, should be ok final MediaType contentType = MediaType.parse(uc.getContentType()); final String lowerCaseUrl = url.toLowerCase(Locale.US); // honor content type over resource naming conventions, check for most common source image types first if (contentType.equals(MediaType.TIFF)) { imagePlus = super.openTiff(u.openStream(), name); } else if (contentType.equals(MediaType.PNG)) { imagePlus = openPngUsingURL(name, u); } else if (contentType.equals(MediaType.JPEG) || contentType.equals(MediaType.GIF)) { imagePlus = openJpegOrGifUsingURL(name, u); } else if (lowerCaseUrl.endsWith(".tif") || lowerCaseUrl.endsWith(".tiff")) { imagePlus = super.openTiff(u.openStream(), name); } else if (lowerCaseUrl.endsWith(".png")) { imagePlus = openPngUsingURL(name, u); } else if (lowerCaseUrl.endsWith(".jpg") || lowerCaseUrl.endsWith(".gif")) { imagePlus = openJpegOrGifUsingURL(name, u); } else { throw new IOException("unsupported content type " + contentType + " for " + url); } } catch (final Throwable t) { // null imagePlus will be returned and handled upstream, no need to raise exception here LOG.error("failed to load " + url, t); } } else { imagePlus = super.openURL(url); } return imagePlus; }