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

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

Introduction

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

Prototype

ImmutableListMultimap parameters

To view the source code for com.google.common.net MediaType parameters.

Click Source Link

Usage

From source file:org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorExtensions.java

/**
 * get a task editor extension for a specific task attribute
 * /*  w ww  .j a v a2  s .  c  om*/
 * @param taskRepository
 * @param taskAttribute
 * @return the extension, or null if there is none
 * @see #getTaskEditorExtension(TaskRepository);
 * @since 3.11
 */
public static AbstractTaskEditorExtension getTaskEditorExtension(TaskRepository taskRepository,
        TaskAttribute taskAttribute) {
    init();
    String input = taskAttribute.getMetaData().getMediaType();
    if (input != null) {
        try {
            MediaType media = MediaType.parse(input);
            Multimap<String, String> parameters = media.parameters();
            if (parameters.containsKey(MARKUP_KEY)) {
                Iterator<String> iter = parameters.get(MARKUP_KEY).iterator();
                String markup = iter.next();
                SortedSet<RegisteredTaskEditorExtension> extensions = getTaskEditorExtensions();
                for (RegisteredTaskEditorExtension extension : extensions) {
                    if (markup.equals(extension.getName())) {
                        return extension.getExtension();
                    }
                }
            }
        } catch (IllegalArgumentException e) {
            StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
                    String.format("Unable to parse markup type for attribute %s", taskAttribute.toString()), //$NON-NLS-1$
                    e));
        }
    }
    return getTaskEditorExtension(taskRepository);
}

From source file:io.github.mike10004.vhs.testsupport.MakeFileUploadHar.java

private static NanoHTTPD.Response parseBody(MediaType contentType, byte[] data,
        Map<String, TypedContent> storage) {
    if (contentType.is(MediaType.parse("multipart/form-data"))) {
        @Nullable//from   ww  w.j  ava 2 s. c o  m
        String boundary = contentType.parameters().get("boundary").stream().findFirst().orElse(null);
        if (boundary == null) {
            return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.BAD_REQUEST, "text/plain",
                    "Bad Request: Content type is multipart/form-data but boundary missing");
        }
        List<FormDataPart> formDataParts;
        try {
            formDataParts = new NanohttpdFormDataParser().decodeMultipartFormData(contentType, data);
        } catch (MultipartFormDataParser.BadMultipartFormDataException e) {
            e.printStackTrace(System.err);
            return NanoHTTPD.newFixedLengthResponse(
                    MakeTestHar.lookup(MultipartFormDataParser.BadMultipartFormDataException.STATUS_CODE),
                    "text/plain", e.getMessage());
        }
        System.out.format("%d parts parsed from request body%n", formDataParts.size());
        formDataParts.forEach(part -> {
            System.out.format("  %s%n", part);
            part.headers.forEach((name, value) -> {
                System.out.format("    %s: %s%n", name, value);
            });
        });
        List<TypedContent> files = formDataParts.stream()
                .filter(p -> p.contentDisposition != null && p.contentDisposition.getFilename() != null)
                .map(p -> p.file).collect(Collectors.toList());
        if (files.isEmpty()) {
            return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.BAD_REQUEST, "text/plain",
                    "Bad Request: no files");
        }
        AtomicReference<UUID> lastId = new AtomicReference<>(null);
        files.forEach(fileData -> {
            UUID id = UUID.randomUUID();
            lastId.set(id);
            storage.put(id.toString(), fileData);
        });
        return redirect("/file?id=" + lastId.get());
    } else {
        return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.BAD_REQUEST, "text/plain",
                "Bad Request: expected content type = multipart/form-data");
    }
}

From source file:org.mule.module.apikit.RestContentTypeParser.java

/**
 * Find the best match for a given mimeType against a list of media_ranges
 * that have already been parsed by MimeParse.parseMediaRange(). Returns a
 * tuple of the fitness value and the value of the 'q' quality parameter of
 * the best match, or (-1, 0) if no match was found. Just as for
 * quality_parsed(), 'parsed_ranges' must be a list of parsed media ranges.
 *
 * @param target//from   w w  w. j a  v a  2 s  . c o m
 * @param parsedRanges
 * @deprecated used by apikit1 only
 */
protected static FitnessAndQuality fitnessAndQualityParsed(MediaType target, List<MediaType> parsedRanges) {
    int bestFitness = -1;
    float bestFitQ = 0;

    for (MediaType range : parsedRanges) {
        if ((target.type().equals(range.type()) || range.type().equals("*") || target.type().equals("*"))
                && (target.subtype().equals(range.subtype()) || range.subtype().equals("*")
                        || target.subtype().equals("*"))) {
            for (String k : target.parameters().keySet()) {
                int paramMatches = 0;
                if (!k.equals("q") && range.parameters().containsKey(k)
                        && target.parameters().get(k).equals(range.parameters().get(k))) {
                    paramMatches++;
                }
                int fitness = (range.type().equals(target.type())) ? 100 : 0;
                fitness += (range.subtype().equals(target.subtype())) ? 10 : 0;
                fitness += paramMatches;
                if (fitness > bestFitness) {
                    bestFitness = fitness;

                    if (range.type().equals("*") && range.subtype().equals("*")) {
                        bestFitQ = NumberUtils.toFloat(target.parameters().get("q").get(0), 0);
                    } else {
                        bestFitQ = NumberUtils.toFloat(range.parameters().get("q").get(0), 0);
                    }
                }
            }
        }
    }
    return new FitnessAndQuality(bestFitness, bestFitQ);
}

From source file:at.ac.univie.isc.asio.matcher.MimeMatcher.java

private boolean parametersCompatible(final MediaType actual) {
    return actual.parameters().entries().containsAll(expected.parameters().entries());
}

From source file:at.ac.univie.isc.asio.jaxrs.MediaTypeConverter.java

@Override
protected javax.ws.rs.core.MediaType doBackward(@Nonnull final com.google.common.net.MediaType input) {
    final ImmutableMap.Builder<String, String> parameters = ImmutableMap.builder();
    for (Map.Entry<String, Collection<String>> entry : input.parameters().asMap().entrySet()) {
        assert entry.getValue().size() <= 1 : "cannot convert duplicate parameters in " + input;
        parameters.put(entry.getKey(), entry.getValue().iterator().next());
    }//from ww w  .j av  a  2  s.  c  o  m
    return new javax.ws.rs.core.MediaType(input.type(), input.subtype(), parameters.build());
}

From source file:org.wisdom.test.parents.FakeRequest.java

/**
 * @return {@literal empty} as this is a fake request.
 *//*from w  w w .j  ava2  s .  c o m*/
@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;
}

From source file:org.wisdom.engine.wrapper.RequestFromNetty.java

/**
 * 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/>//from  w  w w.j a  v  a  2s.  c o m
 * 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;
}

From source file:com.tinspx.util.net.MultipartBody.java

private MultipartBody setContentType(@NonNull MediaType contentType, @Nullable String boundary, boolean init) {
    if (boundary != null) {
        contentType = contentType.withParameter(BOUNDARY, boundary);
    } else {//from   w  ww. j a  v  a  2  s  .  c  o m
        List<String> b = contentType.parameters().get(BOUNDARY);
        if (b.isEmpty()) {
            boundary = init ? generateBoundary() : this.boundary;
            contentType = contentType.withParameter(BOUNDARY, boundary);
        } else if (b.size() > 1) {
            throw new IllegalArgumentException(
                    String.format("type (%s) has multiple boundary parameters", contentType));
        } else {
            boundary = b.get(0);
        }
    }
    checkBoundary(boundary);
    boundaryBytes = CharUtils.encodeAscii(boundary);
    this.boundary = boundary;
    headers.replaceValues(HttpHeaders.CONTENT_TYPE, Collections.singleton(contentType.toString()));
    type = contentType;
    valid = false;
    return this;
}