com.google.common.net.MediaType Java Examples

The following examples show how to use com.google.common.net.MediaType. 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: FakeRequest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #2
Source File: ResultProcessorTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcessResultFileFalure() {
    ProcessSession processSession = mock(ProcessSession.class);
    ComponentLog componentLog = mock(ComponentLog.class);
    FlowFile flowFile = mock(FlowFile.class);
    Exception exception = new Exception();
    String name = "name";

    when(processSession.putAttribute(eq(flowFile), anyString(), anyString())).thenReturn(flowFile);

    resultProcessor.process(processSession, componentLog, flowFile, exception, name);
    verify(processSession).putAttribute(flowFile, CoreAttributes.FILENAME.key(), name);
    verify(processSession).putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(), MediaType.APPLICATION_XML_UTF_8.toString());
    verify(processSession).transfer(flowFile, failureRelationship);
    verify(componentLog).error(eq(ResultProcessor.UNABLE_TO_PROCESS_DUE_TO), any(Object[].class), eq(exception));
}
 
Example #3
Source File: ResponsesTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteSuccessfulResponse() throws IOException {
  String content = "<html>Hello, world!</html>";
  Request baseRequest = createMock(Request.class);
  baseRequest.setHandled(true);

  HttpServletResponse response = createMock(HttpServletResponse.class);
  response.setStatus(200);
  response.setContentType("text/html; charset=utf-8");
  StringWriter stringWriter = new StringWriter();
  PrintWriter printWriter = new PrintWriter(stringWriter); // NOPMD required by API
  expect(response.getWriter()).andReturn(printWriter);
  response.flushBuffer();

  replayAll();
  Responses.writeSuccessfulResponse(content, MediaType.HTML_UTF_8, baseRequest, response);
  verifyAll();

  assertEquals(content, stringWriter.toString());
}
 
Example #4
Source File: MethodHandlerTest.java    From aws-lambda-proxy-java with MIT License 6 votes vote down vote up
@Test
public void shouldIgnoreParametersWhenRegisteringContentTypeAndAccept() throws Exception {
    MediaType contentTypeWithParameter = CONTENT_TYPE_1.withParameter("attribute", "value");
    MediaType acceptTypeWithParameter = ACCEPT_TYPE_1.withParameter("attribute", "value");
    sampleMethodHandler.registerPerContentType(contentTypeWithParameter, contentTypeMapper1);
    sampleMethodHandler.registerPerAccept(acceptTypeWithParameter, acceptMapper1);
    int output = 0;
    when(contentTypeMapper1.toInput(request, context)).thenReturn(output);
    when(acceptMapper1.outputToResponse(output)).thenReturn(new ApiGatewayProxyResponse.ApiGatewayProxyResponseBuilder()
            .withStatusCode(OK.getStatusCode())
            .build());

    ApiGatewayProxyResponse response = sampleMethodHandler.handle(request, singletonList(CONTENT_TYPE_1), singletonList(ACCEPT_TYPE_1), context);

    assertThat(response.getStatusCode()).isEqualTo(OK.getStatusCode());
}
 
Example #5
Source File: Engine.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * 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: MethodHandlerTest.java    From aws-lambda-proxy-java with MIT License 6 votes vote down vote up
@Test
public void shouldIgnoreParametersWhenMatchingContentTypeAndAccept() throws Exception {
    sampleMethodHandler.registerPerContentType(CONTENT_TYPE_1, contentTypeMapper1);
    sampleMethodHandler.registerPerAccept(ACCEPT_TYPE_1, acceptMapper1);
    int output = 0;
    when(contentTypeMapper1.toInput(request, context)).thenReturn(output);
    when(acceptMapper1.outputToResponse(output)).thenReturn(new ApiGatewayProxyResponse.ApiGatewayProxyResponseBuilder()
            .withStatusCode(OK.getStatusCode())
            .build());
    MediaType contentTypeWithParameter = CONTENT_TYPE_1.withParameter("attribute", "value");
    MediaType acceptTypeWithParameter = ACCEPT_TYPE_1.withParameter("attribute", "value");

    ApiGatewayProxyResponse response = sampleMethodHandler.handle(request, singletonList(contentTypeWithParameter), singletonList(acceptTypeWithParameter), context);

    assertThat(response.getStatusCode()).isEqualTo(OK.getStatusCode());
}
 
Example #7
Source File: RequestRouter.java    From wisdom with Apache License 2.0 6 votes vote down vote up
private boolean hasSameOrOverlappingAcceptedTypes(Route actual, Route other) {
    final Set<MediaType> actualAcceptedMediaTypes = actual.getAcceptedMediaTypes();
    final Set<MediaType> otherAcceptedMediaTypes = other.getAcceptedMediaTypes();

    // Both are empty
    if (actualAcceptedMediaTypes.isEmpty() && otherAcceptedMediaTypes.isEmpty()) {
        return true;
    }

    // One is empty
    if (actualAcceptedMediaTypes.isEmpty() || otherAcceptedMediaTypes.isEmpty()) {
        return true;
    }

    // None are empty, check intersection
    final Sets.SetView<MediaType> intersection = Sets.intersection(actualAcceptedMediaTypes, otherAcceptedMediaTypes);
    return !intersection.isEmpty();
}
 
Example #8
Source File: EventualBlobStoreTest.java    From s3proxy with Apache License 2.0 6 votes vote down vote up
private static void validateBlob(Blob blob) throws IOException {
    assertThat(blob).isNotNull();

    ContentMetadata contentMetadata =
            blob.getMetadata().getContentMetadata();
    assertThat(contentMetadata.getContentDisposition())
            .isEqualTo("attachment; filename=foo.mp4");
    assertThat(contentMetadata.getContentEncoding())
            .isEqualTo("compress");
    assertThat(contentMetadata.getContentLength())
            .isEqualTo(BYTE_SOURCE.size());
    assertThat(contentMetadata.getContentType())
            .isEqualTo(MediaType.MP4_AUDIO.toString());

    assertThat(blob.getMetadata().getUserMetadata())
            .isEqualTo(ImmutableMap.of("key", "value"));

    try (InputStream actual = blob.getPayload().openStream();
            InputStream expected = BYTE_SOURCE.openStream()) {
        assertThat(actual).hasContentEqualTo(expected);
    }
}
 
Example #9
Source File: ResultProcessorTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcessResultFileSuccess() {
    ProcessSession processSession = mock(ProcessSession.class);
    ComponentLog componentLog = mock(ComponentLog.class);
    FlowFile flowFile = mock(FlowFile.class);
    Exception exception = null;
    String name = "basename";

    when(processSession.putAttribute(eq(flowFile), anyString(), anyString())).thenReturn(flowFile);

    resultProcessor.process(processSession, componentLog, flowFile, exception, name);
    verify(processSession).putAttribute(flowFile, CoreAttributes.FILENAME.key(), name);
    verify(processSession).putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(), MediaType.APPLICATION_XML_UTF_8.toString());
    verify(processSession).transfer(flowFile, successRelationship);
    verifyNoMoreInteractions(componentLog);
}
 
Example #10
Source File: HttpSessionManager.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private CommonResponse createSession(String username, Set<String> roles, boolean ldap)
        throws Exception {
    String sessionId = new BigInteger(130, secureRandom).toString(32);
    ImmutableSession session = ImmutableSession.builder()
            .caseAmbiguousUsername(username)
            .ldap(ldap)
            .roles(roles)
            .lastRequest(clock.currentTimeMillis())
            .build();
    sessionMap.put(sessionId, session);

    String layoutJson = layoutService
            .getLayoutJson(session.createAuthentication(central, configRepository));
    CommonResponse response = new CommonResponse(OK, MediaType.JSON_UTF_8, layoutJson);
    Cookie cookie =
            new DefaultCookie(configRepository.getWebConfig().sessionCookieName(), sessionId);
    cookie.setHttpOnly(true);
    cookie.setPath("/");
    response.setHeader(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
    purgeExpiredSessions();

    auditSuccessfulLogin(username);
    return response;
}
 
Example #11
Source File: CopyDetailReportsActionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_nonDetailReportFiles_notSent() throws IOException{
  writeGcsFile(
      gcsService,
      new GcsFilename("test-bucket", "results/invoice_details_2017-10_TheRegistrar_hello.csv"),
      "hola,mundo\n3,4".getBytes(UTF_8));

  writeGcsFile(
      gcsService,
      new GcsFilename("test-bucket", "results/not_a_detail_report_2017-10_TheRegistrar_test.csv"),
      "hello,world\n1,2".getBytes(UTF_8));
  action.run();
  verify(driveConnection)
      .createOrUpdateFile(
          "invoice_details_2017-10_TheRegistrar_hello.csv",
          MediaType.CSV_UTF_8,
          "0B-12345",
          "hola,mundo\n3,4".getBytes(UTF_8));
  // Verify we didn't copy the non-detail report file.
  verifyNoMoreInteractions(driveConnection);
  assertThat(response.getStatus()).isEqualTo(SC_OK);
  assertThat(response.getContentType()).isEqualTo(MediaType.PLAIN_TEXT_UTF_8);
  assertThat(response.getPayload()).isEqualTo("Copied detail reports.\n");
}
 
Example #12
Source File: JsonApiMediaType.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
public static boolean isCompatibleMediaType(MediaType mediaType) {
    if (mediaType == null) {
        return false;
    }

    if (WILDCARD.equals(mediaType.type())) {
        return true;
    }

    if (MediaType.ANY_APPLICATION_TYPE.type()
        .equalsIgnoreCase(mediaType.type())) {
        log.debug("application mediaType : {}", mediaType);
        if (WILDCARD.equals(mediaType.subtype())) {
            return true;
        }

        if (APPLICATION_JSON_API_TYPE.subtype()
            .equalsIgnoreCase(mediaType.subtype())) {
            log.debug("application mediaType having json api subtype : {}", mediaType);
            return true;
        }
    }

    return false;
}
 
Example #13
Source File: FormControllerTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormEncoding() {
	// given
	Multimap<String, String> parameter = ArrayListMultimap.create();
       parameter.put("username", "süpöä");
       parameter.put("password", "#+ߧ");
	
	// when
	TestResponse response = TestRequest.post("/form")
	        .withContentType(MediaType.FORM_DATA.withoutParameters().toString())
			.withForm(parameter)
			.execute();

	// then
	assertThat(response, not(nullValue()));
	assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
	assertThat(response.getContent(), equalTo("süpöä;#+ߧ"));
}
 
Example #14
Source File: ObjectStoreFileStorage.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
@Override
public void addFile(FileEntry fileEntry, File file) throws FileStorageException {
    String entryName = fileEntry.getId();
    long fileSize = fileEntry.getSize()
                             .longValue();
    Blob blob = blobStore.blobBuilder(entryName)
                         .payload(file)
                         .contentDisposition(fileEntry.getName())
                         .contentType(MediaType.OCTET_STREAM.toString())
                         .userMetadata(createFileEntryMetadata(fileEntry))
                         .build();
    try {
        putBlobWithRetries(blob, 3);
        LOGGER.debug(MessageFormat.format(Messages.STORED_FILE_0_WITH_SIZE_1_SUCCESSFULLY_2, fileEntry.getId(), fileSize));
    } catch (ContainerNotFoundException e) {
        throw new FileStorageException(MessageFormat.format(Messages.FILE_UPLOAD_FAILED, fileEntry.getName(),
                                                            fileEntry.getNamespace()));
    }
}
 
Example #15
Source File: AdminJsonService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@RequiresNonNull("httpServer")
private CommonResponse onSuccessfulEmbeddedWebUpdate(EmbeddedWebConfig config)
        throws Exception {
    boolean closeCurrentChannelAfterPortChange = false;
    boolean portChangeFailed = false;
    if (config.port() != checkNotNull(httpServer.getPort())) {
        try {
            httpServer.changePort(config.port());
            closeCurrentChannelAfterPortChange = true;
        } catch (PortChangeFailedException e) {
            logger.error(e.getMessage(), e);
            portChangeFailed = true;
        }
    }
    if (config.https() != httpServer.getHttps() && !portChangeFailed) {
        // only change protocol if port change did not fail, otherwise confusing to display
        // message that port change failed while at the same time redirecting user to HTTP/S
        httpServer.changeProtocol(config.https());
        closeCurrentChannelAfterPortChange = true;
    }
    String responseText = getEmbeddedWebConfig(portChangeFailed);
    CommonResponse response = new CommonResponse(OK, MediaType.JSON_UTF_8, responseText);
    if (closeCurrentChannelAfterPortChange) {
        response.setCloseConnectionAfterPortChange();
    }
    return response;
}
 
Example #16
Source File: JsonControllerTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonNullResponseBody() {
    //given
    TestResponse response = TestRequest.post("/body")
            .withContentType(MediaType.JSON_UTF_8.withoutParameters().toString())
            .withStringBody(null)
            .execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), not(nullValue()));
}
 
Example #17
Source File: LambdaProxyHandlerTest.java    From aws-lambda-proxy-java with MIT License 5 votes vote down vote up
@Test
public void corsSupportShouldReturnBadRequestForNonRegisteredMethod() {
    LambdaProxyHandler<Configuration> handlerWithCORSSupport = new TestLambdaProxyHandler(true);
    String methodBeingInvestigated = "GET";
    Collection<String> supportedMethods = singletonList("POST");
    MediaType mediaType1 = MediaType.create("application", "type1");
    MediaType mediaType2 = MediaType.create("application", "type2");
    MediaType mediaType3 = MediaType.create("application", "type3");
    MediaType mediaType4 = MediaType.create("application", "type4");
    Collection<String> requiredHeaders = Stream.of("header1", "header2")
            .map(Util::randomizeCase)
            .collect(toList());
    SampleMethodHandler sampleMethodHandler = new SampleMethodHandler(requiredHeaders);
    sampleMethodHandler.registerPerAccept(mediaType1, mock(AcceptMapper.class));
    sampleMethodHandler.registerPerAccept(mediaType2, mock(AcceptMapper.class));
    sampleMethodHandler.registerPerAccept(mediaType3, mock(AcceptMapper.class));
    sampleMethodHandler.registerPerContentType(mediaType4, mock(ContentTypeMapper.class));
    supportedMethods.forEach(method -> handlerWithCORSSupport.registerMethodHandler(
            method,
            c -> sampleMethodHandler
    ));
    Map<String, String> headers = new ConcurrentHashMap<>();
    headers.put(ACCESS_CONTROL_REQUEST_METHOD, methodBeingInvestigated);
    Collection<String> requestHeaders = new HashSet<>(requiredHeaders);
    requestHeaders.add("header3");
    headers.put(ACCESS_CONTROL_REQUEST_HEADERS, String.join(", ", requestHeaders));
    headers.put("Content-Type", mediaType4.toString());
    headers.put("Origin", "http://127.0.0.1:8888");
    randomiseKeyValues(headers);
    ApiGatewayProxyRequest request = new ApiGatewayProxyRequestBuilder()
            .withHttpMethod("OPTIONS")
            .withHeaders(headers)
            .withContext(context)
            .build();

    ApiGatewayProxyResponse response = handlerWithCORSSupport.handleRequest(request, context);

    assertThat(response.getStatusCode()).isEqualTo(BAD_REQUEST.getStatusCode());
    assertThat(response.getBody()).isEqualTo(String.format("Lambda cannot handle the method %s", methodBeingInvestigated.toLowerCase()));
}
 
Example #18
Source File: Email.java    From email-mime-parser with Apache License 2.0 5 votes vote down vote up
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 #19
Source File: EppToolVerifier.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private void setArgumentsIfNeeded() throws Exception {
  if (capturedParams != null) {
    return;
  }
  ArgumentCaptor<byte[]> params = ArgumentCaptor.forClass(byte[].class);
  verify(connection, atLeast(0))
      .sendPostRequest(
          eq("/_dr/epptool"), eq(ImmutableMap.of()), eq(MediaType.FORM_DATA), params.capture());
  capturedParams = ImmutableList.copyOf(params.getAllValues());
  paramIndex = 0;
}
 
Example #20
Source File: RecordedHttpMessage.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public String getCharset() {
  // Content_Type cannot have multiple, commas-separated values, so this is safe.
  Iterator<String> header = _headers.get(HttpHeaders.CONTENT_TYPE).iterator();
  if (!header.hasNext()) {
    return DEFAULT_CHARSET;
  } else {
    return MediaType.parse(header.next()).charset().or(Charsets.UTF_8).toString();
  }
}
 
Example #21
Source File: CreateOrUpdatePremiumListCommandTestCase.java    From nomulus with Apache License 2.0 5 votes vote down vote up
void verifySentParams(
    AppEngineConnection connection, String path, ImmutableMap<String, String> parameterMap)
    throws Exception {
  verify(connection)
      .sendPostRequest(
          eq(path),
          urlParamCaptor.capture(),
          eq(MediaType.FORM_DATA),
          requestBodyCaptor.capture());
  assertThat(new ImmutableMap.Builder<String, String>()
      .putAll(urlParamCaptor.getValue())
      .putAll(UriParameters.parse(new String(requestBodyCaptor.getValue(), UTF_8)).entries())
      .build())
          .containsExactlyEntriesIn(parameterMap);
}
 
Example #22
Source File: ImageRepository.java    From oxTrust with MIT License 5 votes vote down vote up
/**
 * Creates image in repository
 * 
 * @param image
 *            image file
 * @return true if image was added successfully, false otherwise
 * @throws Exception
 */

public boolean addThumbnail(GluuImage image, int thumbWidth, int thumbHeight) throws Exception {
	if (!image.getSourceContentType().matches("image/(gif|png|jpeg|jpg|bmp)")) {
		return false;
	}

	// Load source image
	BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(image.getData()));
	if (bufferedImage == null) {
		throw new IOException("The image data is empty");
	}

	// Set source image size
	image.setWidth(bufferedImage.getWidth());
	image.setHeight(bufferedImage.getHeight());

	BufferedImage bi = ImageTransformationUtility.scaleImage(bufferedImage, thumbWidth, thumbHeight);

	// Set thumb properties
	image.setThumbWidth(bi.getWidth());
	image.setThumbHeight(bi.getHeight());

	image.setThumbContentType(MediaType.PNG.toString());

	// Store thumb image
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	try {
		ImageIO.write(bufferedImage, "png", bos);
		image.setThumbData(bos.toByteArray());
	} finally {
		bos.close();
	}

	return true;
}
 
Example #23
Source File: DefaultErrorHandler.java    From purplejs with Apache License 2.0 5 votes vote down vote up
private String renderBody( final ErrorInfo ex, final MediaType type )
{
    if ( isHtmlType( type ) )
    {
        return renderHtml( ex );
    }

    return renderJson( ex );
}
 
Example #24
Source File: GetContainer.java    From sfs with Apache License 2.0 5 votes vote down vote up
public GetContainer setMediaTypes(List<MediaType> mediaTypes) {
    headerParams.removeAll(ACCEPT);
    headerParams.putAll(ACCEPT,
            from(mediaTypes)
                    .transform(input -> input.toString()));
    return this;
}
 
Example #25
Source File: Route.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether the given request is compliant with the media type accepted by the current route.
 *
 * @param request the request
 * @return {@code true} if the request is compliant, {@code false} otherwise
 */
public boolean isCompliantWithRequestAccept(Request request) {
    if (producedMediaTypes == null || producedMediaTypes.isEmpty() || request == null
            || request.getHeader(HeaderNames.ACCEPT) == null) {
        return true;
    } else {
        for (MediaType mt : producedMediaTypes) {
            if (request.accepts(mt.toString())) {
                return true;
            }
        }
        return false;
    }
}
 
Example #26
Source File: ExceptionHandler.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Throwable throwable = exchange.getAttachment(io.undertow.server.handlers.ExceptionHandler.THROWABLE);
    if (throwable != null) {
        LOG.error("Internal Server Exception", throwable);
    }
    
    try {
        Server.headers()
            .entrySet()
            .stream()
            .filter(entry -> StringUtils.isNotBlank(entry.getValue()))
            .forEach(entry -> exchange.getResponseHeaders().add(entry.getKey().toHttpString(), entry.getValue()));

        exchange.getResponseHeaders().put(Header.CONTENT_TYPE.toHttpString(), MediaType.HTML_UTF_8.withoutParameters().toString());
        exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);

        if (Application.inDevMode()) {
            TemplateEngine templateEngine = new TemplateEngine();
            if (throwable == null) {
                exchange.getResponseSender().send(Template.DEFAULT.serverError());
            } else if (throwable.getCause() == null) {
                exchange.getResponseSender().send(templateEngine.renderException(exchange, throwable, true));
            } else {
                exchange.getResponseSender().send(templateEngine.renderException(exchange, throwable.getCause(), false));
            }
        } else {
            exchange.getResponseSender().send(Template.DEFAULT.serverError());
        }
    } catch (Exception e) { // NOSONAR Intentionally catching Exception
        LOG.error("Failed to pass an exception to the frontend", e); 
    }
}
 
Example #27
Source File: CommonHandler.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private CommonResponse handleStaticResource(String path, CommonRequest request)
        throws IOException {
    URL url = getSecureUrlForPath(RESOURCE_BASE + path);
    if (url == null) {
        // log at debug only since this is typically just exploit bot spam
        logger.debug("unexpected path: {}", path);
        return new CommonResponse(NOT_FOUND);
    }
    Date expires = getExpiresForPath(path);
    if (request.getHeader(HttpHeaderNames.IF_MODIFIED_SINCE) != null && expires == null) {
        // all static resources without explicit expires are versioned and can be safely
        // cached forever
        return new CommonResponse(NOT_MODIFIED);
    }
    int extensionStartIndex = path.lastIndexOf('.');
    checkState(extensionStartIndex != -1, "found path under %s with no extension: %s",
            RESOURCE_BASE, path);
    String extension = path.substring(extensionStartIndex + 1);
    MediaType mediaType = mediaTypes.get(extension);
    checkNotNull(mediaType, "found extension under %s with no media type: %s", RESOURCE_BASE,
            extension);
    CommonResponse response = new CommonResponse(OK, mediaType, url);
    if (expires != null) {
        response.setHeader(HttpHeaderNames.EXPIRES, expires);
        response.setHeader(HttpHeaderNames.CACHE_CONTROL,
                "public, max-age=" + expires.getTime());
    } else {
        response.setHeader(HttpHeaderNames.LAST_MODIFIED, new Date(0));
        response.setHeader(HttpHeaderNames.EXPIRES,
                new Date(clock.currentTimeMillis() + TEN_YEARS));
        response.setHeader(HttpHeaderNames.CACHE_CONTROL,
                "public, max-age=" + TEN_YEARS + ", immutable");
    }
    return response;
}
 
Example #28
Source File: NetworkInterceptorTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  appServer = new JreAppServer(req -> new HttpResponse()
      .setStatus(200)
      .addHeader("Content-Type", MediaType.XHTML_UTF_8.toString())
      .setContent(utf8String("<html><head><title>Hello, World!</title></head><body/></html>")));
  appServer.start();

  driver = new WebDriverBuilder().get();

  assumeThat(driver).isInstanceOf(HasDevTools.class);
}
 
Example #29
Source File: DriveConnectionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateFile_succeeds() throws Exception {
  when(files.update(
          eq("id"), eq(new File().setTitle("title")), argThat(hasByteArrayContent(DATA))))
      .thenReturn(update);
  assertThat(driveConnection.updateFile("id", "title", MediaType.WEBM_VIDEO, DATA))
      .isEqualTo("id");
}
 
Example #30
Source File: MethodHandlerTest.java    From aws-lambda-proxy-java with MIT License 5 votes vote down vote up
@Test
public void shouldReturnUnsupportedMediaTypeIfNoContentTypeMapperRegistered() throws Exception {
    List<MediaType> contentTypes = asList(CONTENT_TYPE_1, CONTENT_TYPE_2);

    ApiGatewayProxyResponse response = sampleMethodHandler.handle(request, contentTypes, singletonList(ACCEPT_TYPE_1), context);

    assertThat(response.getStatusCode()).isEqualTo(UNSUPPORTED_MEDIA_TYPE.getStatusCode());
    assertThat(response.getBody()).contains(String.format("Content-Types %s are not supported", contentTypes));
}