Java Code Examples for javax.ws.rs.core.MediaType.valueOf()

The following are Jave code examples for showing how to use valueOf() of the javax.ws.rs.core.MediaType class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: dotwebstack-framework   File: LdIntegrationTest.java   Source Code and License Vote up 6 votes
@Test
public void get_GetBreweryCollection_ThroughLdApi() {
  // Arrange
  Model model = new ModelBuilder().subject(DBEERPEDIA.BREWERIES).add(RDFS.LABEL,
      DBEERPEDIA.BREWERIES_LABEL).build();
  SparqlHttpStub.returnGraph(model);
  MediaType mediaType = MediaType.valueOf("text/turtle");

  // Act
  Response response = target.path("/dbp/ld/v1/graph-breweries").request().accept(mediaType).get();

  // Assert
  assertThat(response.getStatus(), equalTo(Status.OK.getStatusCode()));
  assertThat(response.getMediaType(), equalTo(mediaType));
  assertThat(response.getLength(), greaterThan(0));
  assertThat(response.readEntity(String.class),
      containsString(DBEERPEDIA.BREWERIES_LABEL.stringValue()));
}
 
Example 2
Project: dotwebstack-framework   File: LdIntegrationTest.java   Source Code and License Vote up 6 votes
@Test
public void get_GetDocResource_ThroughLdApi() {
  // Arrange
  Model model = new ModelBuilder().subject(DBEERPEDIA.BREWERIES).add(RDFS.LABEL,
      DBEERPEDIA.BREWERIES_LABEL).build();
  SparqlHttpStub.returnGraph(model);
  MediaType mediaType = MediaType.valueOf("text/turtle");

  // Act
  Response response = target.path("/dbp/ld/v1/doc/breweries").request().accept(mediaType).get();

  // Assert
  assertThat(response.getStatus(), equalTo(Status.OK.getStatusCode()));
  assertThat(response.getMediaType(), equalTo(mediaType));
  assertThat(response.getLength(), greaterThan(0));
  assertThat(response.readEntity(String.class),
      containsString(DBEERPEDIA.BREWERIES_LABEL.stringValue()));
}
 
Example 3
Project: vertx-zero   File: MimeAtomic.java   Source Code and License Vote up 6 votes
private Resolver<T> getResolver(final RoutingContext context,
                                final Epsilon<T> income) {
    /** 1.Read the resolver first **/
    final Annotation annotation = income.getAnnotation();
    final Class<?> resolverCls = Instance.invoke(annotation, "resolver");
    /** 2.Check configured in default **/
    if (null == resolverCls) {
        /** 3. Old path **/
        final JsonObject content = NODE.read();
        final String header = context.request().getHeader(HttpHeaders.CONTENT_TYPE);
        final String resolver;
        if (null == header) {
            resolver = content.getString("default");
        } else {
            final MediaType type = MediaType.valueOf(header);
            final JsonObject resolverMap = content.getJsonObject(type.getType());
            resolver = resolverMap.getString(type.getSubtype());
        }
        LOGGER.info(Info.RESOLVER, resolver, header, context.request().absoluteURI());
        return Instance.singleton(resolver);
    } else {
        LOGGER.info(Info.RESOLVER_CONFIG, resolverCls);
        return Instance.singleton(resolverCls);
    }
}
 
Example 4
Project: minijax   File: MinijaxStaticResource.java   Source Code and License Vote up 6 votes
@Override
Object invoke(final MinijaxRequestContext ctx) throws Exception {
    final String resourceName;

    if (directory) {
        resourceName = baseResourceName + "/" + ctx.getUriInfo().getPathParameters().getFirst("file");
    } else {
        resourceName = baseResourceName;
    }

    final URL resourceUrl = MinijaxStaticResource.class.getClassLoader().getResource(resourceName);
    if (resourceUrl == null) {
        return Response.status(Status.NOT_FOUND).build();
    }

    final File resourceFile = new File(resourceUrl.getFile());
    if (resourceFile.isDirectory()) {
        return Response.status(Status.NOT_FOUND).build();
    }

    final String contentType = Files.probeContentType(resourceFile.toPath());
    final MediaType mediaType = contentType == null ? MediaType.APPLICATION_OCTET_STREAM_TYPE : MediaType.valueOf(contentType);
    return Response.ok(resourceUrl.openStream(), mediaType).cacheControl(PUBLIC).build();
}
 
Example 5
Project: hadoop   File: WebHdfsFileSystem.java   Source Code and License Vote up 6 votes
static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream
    ) throws IOException {
  if (c.getContentLength() == 0) {
    return null;
  }
  final InputStream in = useErrorStream? c.getErrorStream(): c.getInputStream();
  if (in == null) {
    throw new IOException("The " + (useErrorStream? "error": "input") + " stream is null.");
  }
  try {
    final String contentType = c.getContentType();
    if (contentType != null) {
      final MediaType parsed = MediaType.valueOf(contentType);
      if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
        throw new IOException("Content-Type \"" + contentType
            + "\" is incompatible with \"" + MediaType.APPLICATION_JSON
            + "\" (parsed=\"" + parsed + "\")");
      }
    }
    ObjectMapper mapper = new ObjectMapper();
    return mapper.reader(Map.class).readValue(in);
  } finally {
    in.close();
  }
}
 
Example 6
Project: syndesis   File: ConnectorHandler.java   Source Code and License Vote up 5 votes
@PUT
@Path(value = "/{id}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void update(@NotNull @PathParam("id") @ApiParam(required = true) String id, @MultipartForm ConnectorFormData connectorFormData) {
    if (connectorFormData.getConnector() == null) {
        throw new IllegalArgumentException("Missing connector parameter");
    }

    Connector connectorToUpdate = connectorFormData.getConnector();

    if (connectorFormData.getIconInputStream() != null) {
        try(BufferedInputStream iconStream = new BufferedInputStream(connectorFormData.getIconInputStream())) {
            // URLConnection.guessContentTypeFromStream resets the stream after inspecting the media type so
            // can continue to be used, rather than being consumed.
            String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
            if (!guessedMediaType.startsWith("image/")) {
                throw new IllegalArgumentException("Invalid file contents for an image");
            }
            MediaType mediaType = MediaType.valueOf(guessedMediaType);
            Icon.Builder iconBuilder = new Icon.Builder().mediaType(mediaType.toString());

            Icon icon = getDataManager().create(iconBuilder.build());
            iconDao.write(icon.getId().get(), iconStream);
            connectorToUpdate = connectorToUpdate.builder().icon("db:" + icon.getId().get()).build();
        } catch (IOException e) {
            throw new IllegalArgumentException("Error while reading multipart request", e);
        }
    }

    getDataManager().update(connectorToUpdate);
}
 
Example 7
Project: app-ms   File: VertxRoutingContextHttpHeaders.java   Source Code and License Vote up 5 votes
public VertxRoutingContextHttpHeaders(final RoutingContext context) {

        this.context = context;

        final String obj = getHeaderString(CONTENT_TYPE);
        if (obj == null) {
            mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
        } else {
            mediaType = MediaType.valueOf(obj);
        }
    }
 
Example 8
Project: karate   File: JerseyHttpClient.java   Source Code and License Vote up 5 votes
@Override
public Entity getEntity(List<MultiPartItem> items, String mediaType) {
    MultiPart multiPart = new MultiPart();
    for (MultiPartItem item : items) {
        if (item.getValue() == null || item.getValue().isNull()) {
            continue;
        }
        String name = item.getName();
        String filename = item.getFilename();
        ScriptValue sv = item.getValue();
        String ct = item.getContentType();                    
        if (ct == null) {
            ct = HttpUtils.getContentType(sv);
        }
        MediaType itemType = MediaType.valueOf(ct);
        if (name == null) { // most likely multipart/mixed
            BodyPart bp = new BodyPart().entity(sv.getAsString()).type(itemType);
            multiPart.bodyPart(bp);
        } else if (filename != null) {
            StreamDataBodyPart part = new StreamDataBodyPart(name, sv.getAsStream(), filename, itemType);
            multiPart.bodyPart(part);
        } else {
            multiPart.bodyPart(new FormDataBodyPart(name, sv.getAsString(), itemType));
        }
    }
    return Entity.entity(multiPart, mediaType);
}
 
Example 9
Project: minijax   File: MockHttpServletResponse.java   Source Code and License Vote up 5 votes
private MediaType getMediaType() {
    final List<String> contentType = headers.get(HttpHeaders.CONTENT_TYPE);
    if (contentType == null || contentType.isEmpty()) {
        return null;
    }
    return MediaType.valueOf(contentType.get(0));
}
 
Example 10
Project: syndesis   File: ConnectorIconHandler.java   Source Code and License Vote up 4 votes
@POST
@ApiOperation("Updates the connector icon for the specified connector and returns the updated connector")
@ApiResponses(@ApiResponse(code = 200, response = Connector.class, message = "Updated Connector icon"))
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Connector create(MultipartFormDataInput dataInput) {
    if (dataInput == null || dataInput.getParts() == null || dataInput.getParts().isEmpty()) {
        throw new IllegalArgumentException("Multipart request is empty");
    }

    if (dataInput.getParts().size() != 1) {
        throw new IllegalArgumentException("Wrong number of parts in multipart request");
    }

    try {
        InputPart filePart = dataInput.getParts().iterator().next();
        InputStream result = filePart.getBody(InputStream.class, null);

        if (result == null) {
            throw new IllegalArgumentException("Can't find a valid 'icon' part in the multipart request");
        }

        try (BufferedInputStream iconStream = new BufferedInputStream(result)) {
            MediaType mediaType = filePart.getMediaType();
            if (!mediaType.getType().equals("image")) {
                // URLConnection.guessContentTypeFromStream resets the stream after inspecting the media type so
                // can continue to be used, rather than being consumed.
                String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
                if (!guessedMediaType.startsWith("image/")) {
                    throw new IllegalArgumentException("Invalid file contents for an image");
                }
                mediaType = MediaType.valueOf(guessedMediaType);
            }

            Icon.Builder iconBuilder = new Icon.Builder()
                .mediaType(mediaType.toString());

            Icon icon;
            String connectorIcon = connector.getIcon();
            if (connectorIcon != null && connectorIcon.startsWith("db:")) {
                String connectorIconId = connectorIcon.substring(3);
                iconBuilder.id(connectorIconId);
                icon = iconBuilder.build();
                getDataManager().update(icon);
            } else {
                icon = getDataManager().create(iconBuilder.build());
            }

            iconDao.write(icon.getId().get(), iconStream);

            Connector updatedConnector = new Connector.Builder().createFrom(connector).icon("db:" + icon.getId().get()).build();
            getDataManager().update(updatedConnector);
            return updatedConnector;
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Error while reading multipart request", e);
    }
}
 
Example 11
Project: syndesis   File: CustomConnectorHandler.java   Source Code and License Vote up 4 votes
@POST
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation("Creates a new Connector based on the ConnectorTemplate identified by the provided `id` and the data given in `connectorSettings` multipart part, plus optional `icon` file")
@ApiResponses(@ApiResponse(code = 200, response = Connector.class, message = "Newly created Connector"))
public Connector create(@MultipartForm CustomConnectorFormData customConnectorFormData) throws IOException {
    final ConnectorSettings connectorSettings = customConnectorFormData.getConnectorSettings();
    if (connectorSettings == null) {
        throw new IllegalArgumentException("Missing connectorSettings parameter");
    }

    final ConnectorSettings connectorSettingsToUse;
    if (connectorSettings.getConfiguredProperties().containsKey("specification")) {
        connectorSettingsToUse = connectorSettings;
    } else {
        final String specification;
        try (BufferedSource source = Okio.buffer(Okio.source(customConnectorFormData.getSpecification()))) {
            specification = source.readUtf8();
        }

        connectorSettingsToUse = new ConnectorSettings.Builder().createFrom(connectorSettings).putConfiguredProperty("specification", specification).build();
    }

    Connector generatedConnector = withGeneratorAndTemplate(connectorSettingsToUse.getConnectorTemplateId(),
        (generator, template) -> generator.generate(template, connectorSettingsToUse));

    if (customConnectorFormData.getIconInputStream() != null) {
        // URLConnection.guessContentTypeFromStream resets the stream after inspecting the media type so
        // can continue to be used, rather than being consumed.
        try(BufferedInputStream iconStream = new BufferedInputStream(customConnectorFormData.getIconInputStream())) {
            String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
            if (!guessedMediaType.startsWith("image/")) {
                throw new IllegalArgumentException("Invalid file contents for an image");
            }
            MediaType mediaType = MediaType.valueOf(guessedMediaType);
            Icon.Builder iconBuilder = new Icon.Builder()
                .mediaType(mediaType.toString());

            Icon icon = getDataManager().create(iconBuilder.build());
            iconDao.write(icon.getId().get(), iconStream);

            generatedConnector = new Connector.Builder().createFrom(generatedConnector).icon("db:" + icon.getId().get()).build();
        } catch (IOException e) {
            throw new IllegalArgumentException("Error while reading multipart request", e);
        }
    }

    return getDataManager().create(generatedConnector);
}
 
Example 12
Project: minijax   File: MinijaxHttpHeaders.java   Source Code and License Vote up 4 votes
@Override
public MediaType getMediaType() {
    final String contentType = getHeaderString("Content-Type");
    return contentType == null ? null : MediaType.valueOf(contentType);
}