Example usage for com.google.common.net MediaType parse

List of usage examples for com.google.common.net MediaType parse

Introduction

In this page you can find the example usage for com.google.common.net MediaType parse.

Prototype

public static MediaType parse(String input) 

Source Link

Document

Parses a media type from its string representation.

Usage

From source file:io.airlift.http.client.DefaultingJsonResponseHandler.java

@Override
public T handle(Request request, Response response) {
    if (!successfulResponseCodes.contains(response.getStatusCode())) {
        return defaultValue;
    }// w  ww . j  a  v a2 s .c o m
    String contentType = response.getHeader(CONTENT_TYPE);
    if (!MediaType.parse(contentType).is(MEDIA_TYPE_JSON)) {
        return defaultValue;
    }
    try {
        return jsonCodec.fromJson(ByteStreams.toByteArray(response.getInputStream()));
    } catch (Exception e) {
        return defaultValue;
    }
}

From source file:com.linecorp.armeria.server.http.file.MimeTypeUtil.java

@Nullable
static MediaType guessFromPath(String path, boolean preCompressed) {
    requireNonNull(path, "path");
    // If the path is for a precompressed file, it will have an additional extension indicating the
    // encoding, which we don't want to use when determining content type.
    if (preCompressed) {
        path = path.substring(0, path.lastIndexOf('.'));
    }/*w  w w  . j av  a 2  s. c  o  m*/
    final int dotIdx = path.lastIndexOf('.');
    final int slashIdx = path.lastIndexOf('/');
    if (dotIdx < 0 || slashIdx > dotIdx) {
        // No extension
        return null;
    }

    final String extension = path.substring(dotIdx + 1).toLowerCase(Locale.US);
    final MediaType mediaType = EXTENSION_TO_MEDIA_TYPE.get(extension);
    if (mediaType != null) {
        return mediaType;
    }
    final String guessedContentType = URLConnection.guessContentTypeFromName(path);
    return guessedContentType != null ? MediaType.parse(guessedContentType) : null;
}

From source file:org.biokoframework.system.command.crud.binary.HeadBinaryEntityCommand.java

@Override
public Fields execute(Fields input) throws CommandException {
    logInput(input);//from  w  w w . j ava 2  s.c  om
    Fields result = new Fields();
    BinaryEntityRepository blobRepo = getRepository(BinaryEntity.class);

    ArrayList<BinaryEntity> response = new ArrayList<BinaryEntity>();

    String blobId = input.get(DomainEntity.ID);
    if (blobId == null || blobId.isEmpty()) {
        throw CommandExceptionsFactory.createExpectedFieldNotFound(DomainEntity.ID);
    }

    BinaryEntity blob = blobRepo.retrieveWithoutFile(blobId);
    if (blob == null) {
        throw CommandExceptionsFactory.createEntityNotFound(BinaryEntity.class, blobId);
    }
    response.add(blob);

    String mediaType = blob.get(BinaryEntity.MEDIA_TYPE);
    result.put(GenericFieldNames.RESPONSE_CONTENT_TYPE, MediaType.parse(mediaType));
    result.put(GenericFieldNames.RESPONSE, response);

    logOutput(result);
    return result;
}

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 {//from  w  w  w .  j  ava2  s  . c om
            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:org.biokoframework.system.command.crud.binary.GetBinaryEntityCommand.java

@Override
public Fields execute(Fields input) throws CommandException {
    logInput(input);/* w  w  w  .  j av  a2  s. c  o  m*/

    BinaryEntityRepository blobRepo = getRepository(BinaryEntity.class);

    ArrayList<BinaryEntity> response = new ArrayList<BinaryEntity>();

    String blobId = input.get(DomainEntity.ID);
    if (blobId == null || blobId.isEmpty()) {
        throw CommandExceptionsFactory.createExpectedFieldNotFound(DomainEntity.ID);
    }

    BinaryEntity blob = blobRepo.retrieve(blobId);
    if (blob == null) {
        throw CommandExceptionsFactory.createEntityNotFound(BinaryEntity.class, blobId);
    }
    response.add(blob);

    String mediaType = blob.get(BinaryEntity.MEDIA_TYPE);
    Fields output = new Fields("mediaType", MediaType.parse(mediaType), GenericFieldNames.RESPONSE, response);

    logOutput(output);
    return output;
}

From source file:com.lumata.lib.lupa.extractor.internal.ContentExtractorMatcher.java

private boolean matchContentType(ReadableResource res) {
    // hasConstraint(type) -> hasContentType() ^ is(type, constraint(type))
    return !constraints.containsKey(CONTENT_TYPE) || (res.getContentType().isPresent()
            && res.getContentType().get().is(MediaType.parse(constraints.get(CONTENT_TYPE))));
}

From source file:io.airlift.http.client.JsonResponseHandler.java

@Override
public T handle(Request request, Response response) {
    if (!successfulResponseCodes.contains(response.getStatusCode())) {
        throw new UnexpectedResponseException(String.format("Expected response code to be %s, but was %d: %s",
                successfulResponseCodes, response.getStatusCode(), response.getStatusMessage()), request,
                response);/*w w w.  j a v a2  s .  c  o  m*/
    }
    String contentType = response.getHeader(CONTENT_TYPE);
    if (contentType == null) {
        throw new UnexpectedResponseException("Content-Type is not set for response", request, response);
    }
    if (!MediaType.parse(contentType).is(MEDIA_TYPE_JSON)) {
        throw new UnexpectedResponseException(
                "Expected application/json response from server but got " + contentType, request, response);
    }
    byte[] bytes;
    try {
        bytes = ByteStreams.toByteArray(response.getInputStream());
    } catch (IOException e) {
        throw new RuntimeException("Error reading response from server");
    }
    try {
        return jsonCodec.fromJson(bytes);
    } catch (IllegalArgumentException e) {
        String json = new String(bytes, UTF_8);
        throw new IllegalArgumentException(
                "Unable to create " + jsonCodec.getType() + " from JSON response:\n" + json, e);
    }
}

From source file:org.openqa.selenium.remote.http.HttpMessage.java

public String getContentString() {
    Charset charset = UTF_8;/*from   w  ww . ja  v  a2  s .c om*/
    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:de.ks.idnadrev.category.create.CreateCategoryController.java

protected void selectImage(File newFile) throws IOException {
    MediaType mediaType = MediaType.parse(Files.probeContentType(newFile.toPath()));
    if (mediaType.is(MediaType.ANY_IMAGE_TYPE)) {
        loadImage(newFile);/* w w  w  . ja v a2s. com*/
        fileStoreReference = fileStore.getReference(newFile);
        this.file = newFile;
    }
}

From source file:org.wisdom.content.engines.Engine.java

/**
 * 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
 *///from  www.j  av a  2  s . c om
@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;
}