下面列出了怎么用com.google.common.net.MediaType的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
@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");
}
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;
}
@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);
}
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);
}
}
@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));
}
@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()));
}
}
@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öä;#+ß§"));
}
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();
}
@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());
}
@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());
}
@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());
}
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;
}
/**
* 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;
}
@Test
public void testMediaType() throws Exception {
String accept = "text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5";
assertThat(mediaTypes(accept)).containsExactly(
MediaType.parse("text/html").withParameter("level", "1"),
MediaType.parse("text/html").withParameter("q", "0.7"),
MediaType.parse("*/*").withParameter("q", "0.5"),
MediaType.parse("text/html").withParameter("level", "2").withParameter("q", "0.4"),
MediaType.parse("text/*").withParameter("q", "0.3")
);
}
@Test
public void testMultiDataPost() throws Exception {
runCommand(
"--path=/foo/bar?a=1&b=2", "--data=first=100", "-d", "second=200", "--service=PUBAPI");
verify(connection).withService(PUBAPI);
verifyNoMoreInteractions(connection);
verify(connectionForService)
.sendPostRequest(
eq("/foo/bar?a=1&b=2"),
eq(ImmutableMap.<String, String>of()),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq("first=100&second=200".getBytes(UTF_8)));
}
@Test
public void testJsonRequestBodyPost() {
//given
TestResponse response = TestRequest.post("/requestAndJson")
.withContentType(MediaType.JSON_UTF_8.withoutParameters().toString())
.withStringBody(json)
.execute();
//then
assertThat(response, not(nullValue()));
assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
assertThat(response.getContent(), equalTo("/requestAndJsonPeter"));
}
private static CommonResponse newHttpResponseWithMessage(HttpResponseStatus status,
@Nullable String message) throws IOException {
// this is an "expected" exception, no need to send back stack trace
StringBuilder sb = new StringBuilder();
JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
try {
jg.writeStartObject();
jg.writeStringField("message", message);
jg.writeEndObject();
} finally {
jg.close();
}
return new CommonResponse(status, MediaType.JSON_UTF_8, sb.toString());
}
@Test
public void testCreatePerson() {
Person expectedPerson = new Person("Hank", 42, 5L);
new MockServerClient(mockServer.getContainerIpAddress(), mockServer.getServerPort())
.when(request("/mock-passthrough/person/5"))
.respond(response().withBody(jsonb.toJson(expectedPerson), MediaType.JSON_UTF_8));
Person actualPerson = personSvc.getPersonFromExternalService(5);
assertEquals("Hank", actualPerson.name);
assertEquals(42, actualPerson.age);
assertEquals(5, actualPerson.id);
}
@Test
public void testJsonParsingPut() {
//given
TestResponse response = TestRequest.put("/parse")
.withContentType(MediaType.JSON_UTF_8.withoutParameters().toString())
.withStringBody(json)
.execute();
//then
assertThat(response, not(nullValue()));
assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
assertThat(response.getContent(), equalTo("Peter;Parker;24"));
}
@Test
public void test_overrides() throws Exception {
createTld("foo");
runCommandForced(
"--tld=foo",
"--client_id=NewRegistrar",
"--successful_host_creates=10",
"--successful_domain_creates=11",
"--successful_contact_creates=12",
"--host_infos=13",
"--domain_infos=14",
"--contact_infos=15",
"--run_seconds=16");
ImmutableMap<String, Object> parms = new ImmutableMap.Builder<String, Object>()
.put("tld", "foo")
.put("clientId", "NewRegistrar")
.put("successfulHostCreates", 10)
.put("successfulDomainCreates", 11)
.put("successfulContactCreates", 12)
.put("hostInfos", 13)
.put("domainInfos", 14)
.put("contactInfos", 15)
.put("runSeconds", 16)
.build();
verify(connection)
.sendPostRequest(
eq("/_dr/loadtest"), eq(parms), eq(MediaType.PLAIN_TEXT_UTF_8), eq(new byte[0]));
}
private ChannelFuture sendRoot(final ChannelHandlerContext ctx, final HttpRequest request) {
checkRequestMethod(request, HttpMethod.GET, HttpMethod.HEAD);
checkAndGetPreferredMediaTypes(request, TEXT_HTML);
final ByteBuf content = request.getMethod() == HttpMethod.GET ? ROOT_DOCUMENT.slice() : ctx.alloc().buffer(0, 0);
final DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
response.headers().add(HttpHeaders.Names.CONTENT_TYPE, MediaType.HTML_UTF_8);
return ctx.writeAndFlush(response);
}
/**
* Get char set from headers
*
* */
protected 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();
}
}
@Test
public void testGetBestSerializer() throws Exception {
// Match */* (use first form serializer list)
Collection<MediaType> types = mediaTypes("text/*;q=0.3, text/html;q=0.7, text/html;level=1, " +
"text/html;level=2;q=0.4, */*;q=0.5");
assertThat(engine.getBestSerializer(types)).isEqualTo(json);
// Match application/xml
types = mediaTypes("text/*;q=0.3, application/xml;q=0.7, text/html;level=1, " +
"text/html;level=2;q=0.4, */*;q=0.5");
assertThat(engine.getBestSerializer(types)).isEqualTo(xml);
// Match application/json
types = mediaTypes("text/*;q=0.3, application/json;q=0.7, text/html;level=1, " +
"text/html;level=2;q=0.4, */*;q=0.5");
assertThat(engine.getBestSerializer(types)).isEqualTo(json);
// Match application/json
types = mediaTypes(MimeTypes.JSON);
assertThat(engine.getBestSerializer(types)).isEqualTo(json);
// Match application/* (use first form serializer list)
types = mediaTypes("application/*");
assertThat(engine.getBestSerializer(types)).isEqualTo(json);
// Match application/json
types = mediaTypes("text/*;q=0.3, application/json;q=0.7, application/xml;level=1;q=0.6, " +
"text/html;level=2;q=0.4, */*;q=0.5");
assertThat(engine.getBestSerializer(types)).isEqualTo(json);
// Match application/xml
types = mediaTypes("text/*;q=0.3, application/json;q=0.6, application/xml;level=1, " +
"text/html;level=2;q=0.4, */*;q=0.5");
assertThat(engine.getBestSerializer(types)).isEqualTo(xml);
assertThat(engine.getBestSerializer(null)).isNull();
assertThat(engine.getBestSerializer(Collections.<MediaType>emptyList())).isNull();
}
@Override
public void run() {
try {
response.setHeader("Content-Disposition", "attachment");
response.setHeader("X-Content-Type-Options", "nosniff");
response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
response.setContentType(MediaType.JSON_UTF_8);
response.setPayload(toJSONString(doCheck()));
} finally {
CheckApiMetric metric = metricBuilder.build();
checkApiMetrics.incrementCheckApiRequest(metric);
checkApiMetrics.recordProcessingTime(metric);
}
}
/**
* Returns the boundary attribtue of the given multipart/byteranges media type. If the subtype is
* not byteranges or no boundary attribute value is set, an IOException is thrown.
*
* @param mediaType
* @return
* @throws IOException
* @throws ParseException
*/
static byte[] getBoundary(final MediaType mediaType) throws IOException {
if (!"byteranges".equals(mediaType.subtype())) {
throw new IOException("Invalid multipart subtype " + mediaType.subtype() + ", expected 'byteranges'");
}
final List<String> value = mediaType.parameters().get("boundary");
if (value.isEmpty()) {
throw new IOException("Missing multipart boundary parameter");
}
return value.get(0).getBytes(ISO_8859_1);
}
private void verifySent(
String fields, Optional<Boolean> printHeaderRow, Optional<Boolean> fullFieldNames)
throws Exception {
ImmutableMap.Builder<String, Object> params = new ImmutableMap.Builder<>();
if (fields != null) {
params.put(FIELDS_PARAM, fields);
}
printHeaderRow.ifPresent(aBoolean -> params.put(PRINT_HEADER_ROW_PARAM, aBoolean));
fullFieldNames.ifPresent(aBoolean -> params.put(FULL_FIELD_NAMES_PARAM, aBoolean));
params.putAll(getOtherParameters());
verify(connection)
.sendPostRequest(
eq(getTaskPath()), eq(params.build()), eq(MediaType.PLAIN_TEXT_UTF_8), eq(new byte[0]));
}
private static Blob makeBlob(BlobStore blobStore, String blobName)
throws IOException {
return blobStore.blobBuilder(blobName)
.payload(BYTE_SOURCE)
.contentDisposition("attachment; filename=foo.mp4")
.contentEncoding("compress")
.contentLength(BYTE_SOURCE.size())
.contentType(MediaType.MP4_AUDIO)
.contentMD5(BYTE_SOURCE.hash(TestUtils.MD5))
.userMetadata(ImmutableMap.of("key", "value"))
.build();
}
/**
* Sets the set of media types produced by the route.
*
* @param types the set of type
* @return the current route
*/
public Route produces(String... types) {
Preconditions.checkNotNull(types);
final ImmutableSet.Builder<MediaType> builder = new ImmutableSet.Builder<>();
builder.addAll(this.producedMediaTypes);
for (String s : types) {
final MediaType mt = MediaType.parse(s);
if (mt.hasWildcard()) {
throw new RoutingException("A route cannot `produce` a mime type with a wildcard: " + mt);
}
builder.add(mt);
}
this.producedMediaTypes = builder.build();
return this;
}
/**
* @return {@literal empty} as this is a fake request.
*/
@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;
}