Example usage for org.springframework.http MediaType parseMediaType

List of usage examples for org.springframework.http MediaType parseMediaType

Introduction

In this page you can find the example usage for org.springframework.http MediaType parseMediaType.

Prototype

public static MediaType parseMediaType(String mediaType) 

Source Link

Document

Parse the given String into a single MediaType .

Usage

From source file:com.github.ffremont.microservices.springboot.manager.nexus.NexusClientApiTest.java

@Test
public void testGetData() {
    String g = "gg", a = "aa", v = "1.0.0", c = "cc", p = "jar";

    // init mock/*from  w  w w.j av  a  2  s. co m*/
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.parseMediaType(MediaType.APPLICATION_JSON.toString())));
    HttpEntity<NexusDataResult> entity = new HttpEntity<>(headers);
    NexusDataResult nexusResult = new NexusDataResult();
    nexusResult.setData(new NexusData());
    ResponseEntity responseEntity = new ResponseEntity(nexusResult, HttpStatus.OK);
    when(this.nexusRestTemplate
            .exchange(prop.getBaseurl() + "/service/local/artifact/maven/resolve?r=snapshots&g=" + g + "&a=" + a
                    + "&v=" + v + "&p=" + p + "&c=" + c, HttpMethod.GET, entity, NexusDataResult.class))
                            .thenReturn(responseEntity);

    NexusData r = nexus.getData(g, a, p, c, v);

    assertNotNull(r);
}

From source file:com.xyxy.platform.examples.showcase.demos.hystrix.web.HystrixExceptionHandler.java

/**
 * ?Hystrix ClientException(404)./*from ww  w  .  ja va 2 s . c o m*/
 * ClientException?, ?
 */
@ExceptionHandler(value = { HystrixBadRequestException.class })
public final ResponseEntity<?> handleException(HystrixBadRequestException e, WebRequest request) {
    String message = Exceptions.getErrorMessageWithNestedException(e);
    logger.error(message, e);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(MediaTypes.TEXT_PLAIN_UTF_8));
    return handleExceptionInternal(e, message, headers, HttpStatus.BAD_REQUEST, request);
}

From source file:zipkin.autoconfigure.metrics.PrometheusMetricsAutoConfiguration.java

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> prometheusMetrics() {
    StringBuilder sb = new StringBuilder();

    for (PublicMetrics publicMetrics : this.publicMetrics) {
        for (Metric<?> metric : publicMetrics.metrics()) {
            final String sanitizedName = sanitizeMetricName(metric.getName());
            final String type = typeForName(sanitizedName);
            final String metricName = metricName(sanitizedName, type);
            double value = metric.getValue().doubleValue();

            sb.append(String.format("#TYPE %s %s\n", metricName, type));
            sb.append(String.format("#HELP %s %s\n", metricName, metricName));
            sb.append(String.format("%s %s\n", metricName, prometheusDouble(value)));
        }/*from  w  ww  . j  a v a  2 s  . c  o m*/
    }
    return ResponseEntity.ok().contentType(MediaType.parseMediaType("text/plain; version=0.0.4; charset=utf-8"))
            .body(sb.toString());

}

From source file:com.asual.summer.core.spring.ViewResolverConfiguration.java

public AbstractView handleViews(Collection<AbstractView> views, NativeWebRequest request) {
    List<MediaType> requestedMediaTypes;
    try {/*from w  ww.jav a 2s. c om*/
        requestedMediaTypes = contentNegotiationManager.resolveMediaTypes(request);
        for (MediaType requestedMediaType : requestedMediaTypes) {
            for (AbstractView view : views) {
                MediaType producableMediaType = MediaType.parseMediaType(view.getContentType());
                if (requestedMediaType.isCompatibleWith(producableMediaType)
                        && !requestedMediaType.isWildcardType() && requestedMediaType.getQualityValue() > 0.9) {
                    return view;
                }
            }

        }
    } catch (HttpMediaTypeNotAcceptableException e) {
        logger.debug(e.getMessage(), e);
    }
    return null;
}

From source file:com.epam.ta.reportportal.ws.SortingMvcTest.java

@Test
public void testAsc() throws Exception {
    ResultActions resultActions = this.mvcMock
            .perform(get(PROJECT_BASE_URL + getPageUrl(Sort.Direction.ASC))
                    .principal(AuthConstants.ADMINISTRATOR).secure(true)
                    .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
            .andExpect(status().isOk());

    ResultActions resultActions1 = resultActions
            .andExpect(content().contentType("application/json;charset=UTF-8"));
    MvcResult mvcResult = resultActions1.andReturn();
    System.out.println(mvcResult.getResponse().getHeader("Content-Type"));
    System.out.println(mvcResult.getResponse().getContentAsString());
    resultActions1.andExpect(jsonPath("$.content[0].name").value("Demo launch"));
}

From source file:it.tidalwave.northernwind.frontend.springmvc.SpringMvcResponseBuilder.java

@Override
@Nonnull//from  www .  j  a  v  a  2s.co  m
public ResponseBuilder withContentType(final @Nonnull String contentType) {
    headers.setContentType(MediaType.parseMediaType(contentType));
    return this;
}

From source file:be.dnsbelgium.rdap.DomainControllerTest.java

@Test
public void testNotFound() throws Exception {
    when(domainService.getDomain(Mockito.any(DomainName.class))).thenReturn(null);
    mockMvc.perform(get("/domain/example.com").accept(MediaType.parseMediaType("application/rdap+json")))
            .andExpect(status().isNotFound());
}

From source file:platform.filter.HttpPutDeleteFormContentFilter.java

private boolean isFormContentType(HttpServletRequest request) {
    String contentType = request.getContentType();
    if (contentType != null) {
        try {//from w w  w .  ja  v a  2 s  .  co m
            MediaType mediaType = MediaType.parseMediaType(contentType);
            return (MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType));
        } catch (IllegalArgumentException ex) {
            return false;
        }
    } else {
        return false;
    }
}

From source file:com.github.ffremont.microservices.springboot.node.services.MsService.java

/**
 * Retourne un MS/*from   ww w  . java  2s .  c  o  m*/
 *
 * @param msName
 * @return
 */
public MicroServiceRest getMs(String msName) {
    MasterUrlBuilder builder = new MasterUrlBuilder(cluster, node, masterhost, masterPort, masterCR);
    builder.setUri(msName);

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.parseMediaType(MS_JSON_TYPE_MIME)));
    HttpEntity<MicroServiceRest> entity = new HttpEntity<>(headers);

    ResponseEntity<MicroServiceRest> response = restTempate.exchange(builder.build(), HttpMethod.GET, entity,
            MicroServiceRest.class);

    return HttpStatus.OK.equals(response.getStatusCode()) ? response.getBody() : null;
}

From source file:carldav.jackrabbit.webdav.io.DavInputContext.java

/**
 * Parses the input stream into a calendar object.
 * //from w w w  .  j a v a2 s.c  o m
 * @param allowCalendarWithMethod
 *            don't break on Calendars with METHOD property
 * @return Calendar parsed
 * @throws CosmoDavException
 *             - if something is wrong this exception is thrown.
 */
public Calendar getCalendar(boolean allowCalendarWithMethod) throws CosmoDavException {
    if (calendar != null) {
        return calendar;
    }

    if (!hasStream()) {
        return null;
    }

    if (getContentType() == null) {
        throw new BadRequestException("No media type specified");
    }

    final MediaType mediaType = MediaType.parseMediaType(getContentType());
    if (!mediaType.isCompatibleWith(TEXT_CALENDAR) && !mediaType.isCompatibleWith(TEXT_VCARD)) {
        throw new UnsupportedCalendarDataException(mediaType.toString());
    }

    try {
        Calendar c = CalendarUtils.parseCalendar(getInputStream());
        c.validate(true);

        if (CalendarUtils.hasMultipleComponentTypes(c)) {
            throw new InvalidCalendarResourceException(
                    "Calendar object contains more than one type of component");
        }
        if (!allowCalendarWithMethod && c.getProperties().getProperty(Property.METHOD) != null) {
            throw new InvalidCalendarResourceException("Calendar object contains METHOD property");
        }

        calendar = c;
    } catch (IOException e) {
        throw new CosmoDavException(e);
    } catch (ParserException e) {
        throw new InvalidCalendarDataException("Failed to parse calendar object: " + e.getMessage());
    } catch (ValidationException e) {
        throw new InvalidCalendarDataException("Invalid calendar object: " + e.getMessage());
    }

    return calendar;
}