本文整理汇总了Java中com.google.common.net.MediaType类的典型用法代码示例。如果您正苦于以下问题:Java MediaType类的具体用法?Java MediaType怎么用?Java MediaType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MediaType类属于com.google.common.net包,在下文中一共展示了MediaType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: setContentType
import com.google.common.net.MediaType; //导入依赖的package包/类
@Override
public void setContentType(String type) {
if (isCommitted()) {
return;
}
if (hasWriter()) {
return;
}
if (null == type) {
contentType = null;
return;
}
MediaType mediaType = MediaType.parse(type);
Optional<Charset> charset = mediaType.charset();
if (charset.isPresent()) {
setCharacterEncoding(charset.get().name());
}
contentType = mediaType.type() + '/' + mediaType.subtype();
}
示例2: requestAccessToken
import com.google.common.net.MediaType; //导入依赖的package包/类
private boolean requestAccessToken(Map<String, Object> queryMap) {
Url tokenUri = Url.url("https://streamlabs.com/api/v1.0", "token");
String formData = Url.createQueryString(queryMap);
HttpFields headers = new HttpFields();
headers.put(WebClient.NO_CACHE_HEADER, "true");
try {
Response<StreamLabsToken> response = webClient.post(tokenUri, headers, formData, MediaType.FORM_DATA, StreamLabsToken.class);
//noinspection Duplicates
if (response.isOK()) {
accessToken = response.getData().getAccessToken();
refreshToken = response.getData().getRefreshToken();
timeToLive = response.getData().getExpiresIn();
} else {
authenticationError = "Failed exchanging authorization code for access token: " + response.getRawData();
}
} catch (Exception e) {
authenticationError = e.getMessage();
}
return authenticationError == null;
}
示例3: getMapper
import com.google.common.net.MediaType; //导入依赖的package包/类
private static <T> T getMapper(List<MediaType> contentTypes, Map<MediaType, T> contentTypeMap, String errorMessage) throws LambdaException {
List<MediaType> contentTypesWithoutParameters = contentTypes.stream()
.map(MediaType::withoutParameters)
.collect(toList());
return contentTypesWithoutParameters.stream()
.map(contentTypeMap::get)
.filter(Objects::nonNull)
.findFirst()
.orElseThrow(() -> {
ApiGatewayProxyResponse unsupportedContentType = new ApiGatewayProxyResponseBuilder()
.withStatusCode(UNSUPPORTED_MEDIA_TYPE.getStatusCode())
.withBody(String.format(errorMessage, contentTypes))
.build();
return new LambdaException(unsupportedContentType);
});
}
示例4: shouldIgnoreParametersWhenMatchingContentTypeAndAccept
import com.google.common.net.MediaType; //导入依赖的package包/类
@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());
}
示例5: shouldIgnoreParametersWhenRegisteringContentTypeAndAccept
import com.google.common.net.MediaType; //导入依赖的package包/类
@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());
}
示例6: MediaTypeClassifierImpl
import com.google.common.net.MediaType; //导入依赖的package包/类
MediaTypeClassifierImpl(Iterable<? extends MediaType> mts) {
Table<String, String, Set<MediaType>> typeTable =
HashBasedTable.<String, String, Set<MediaType>>create();
for (MediaType mt : mts) {
String type = mt.type();
String subtype = mt.subtype();
Set<MediaType> typeSet = typeTable.get(type, subtype);
if (typeSet == null) {
typeSet = Sets.newLinkedHashSet();
typeTable.put(type, subtype, typeSet);
}
typeSet.add(mt);
}
ImmutableTable.Builder<String, String, ImmutableSet<MediaType>> b =
ImmutableTable.builder();
for (Table.Cell<String, String, Set<MediaType>> cell
: typeTable.cellSet()) {
b.put(cell.getRowKey(), cell.getColumnKey(), ImmutableSet.copyOf(cell.getValue()));
}
this.types = b.build();
}
示例7: apply
import com.google.common.net.MediaType; //导入依赖的package包/类
@Override
public Classification apply(
UrlValue x, Diagnostic.Receiver<? super UrlValue> r) {
MediaType t = x.getContentMediaType();
if (t == null) {
r.note(Diagnostics.MISSING_MEDIA_TYPE, x);
return Classification.INVALID;
}
String type = t.type();
String subtype = t.subtype();
if ("*".equals(type) || "*".equals(subtype)) {
r.note(Diagnostics.WILDCARD, x);
return Classification.INVALID;
}
if (anyRangeMatches(t, types.get(type, subtype))
|| anyRangeMatches(t, types.get(type, "*"))
|| anyRangeMatches(t, types.get("*", "*"))) {
return Classification.MATCH;
}
r.note(Diagnostics.WITHIN_NO_RANGES, x);
return Classification.NOT_A_MATCH;
}
示例8: read
import com.google.common.net.MediaType; //导入依赖的package包/类
/**
* Extracts a JSON object from a servlet request.
*
* @return JSON object or {@code null} on error, in which case servlet should return.
* @throws IOException if we failed to read from {@code req}.
*/
@Nullable
@SuppressWarnings("unchecked")
public static Map<String, ?> read(HttpServletRequest req) throws IOException {
if (!"POST".equals(req.getMethod())
&& !"PUT".equals(req.getMethod())) {
logger.warning("JSON request payload only allowed for POST/PUT");
return null;
}
if (!JSON_UTF_8.is(MediaType.parse(req.getContentType()))) {
logger.warningfmt("Invalid JSON Content-Type: %s", req.getContentType());
return null;
}
try (Reader jsonReader = req.getReader()) {
try {
return checkNotNull((Map<String, ?>) JSONValue.parseWithException(jsonReader));
} catch (ParseException | NullPointerException | ClassCastException e) {
logger.warning(e, "Malformed JSON");
return null;
}
}
}
示例9: setContentType
import com.google.common.net.MediaType; //导入依赖的package包/类
@Override
public void setContentType(String type) {
if (isCommitted()) {
return;
}
// if (hasWriter()) {
// return;
// }
if (null == type) {
contentType = null;
return;
}
MediaType mediaType = MediaType.parse(type);
Optional<Charset> charset = mediaType.charset();
if (charset.isPresent()) {
setCharacterEncoding(charset.get().name());
}
contentType = mediaType.type() + '/' + mediaType.subtype();
}
示例10: createOrUpdateFile
import com.google.common.net.MediaType; //导入依赖的package包/类
/**
* Creates a file with the given parent or updates the existing one if a file already exists with
* that same title and parent.
*
* @throws IllegalStateException if multiple files with that name exist in the given folder.
* @throws IOException if communication with Google Drive fails for any reason.
* @returns the file id.
*/
public String createOrUpdateFile(
String title,
MediaType mimeType,
String parentFolderId,
byte[] bytes) throws IOException {
List<String> existingFiles = listFiles(parentFolderId, String.format("title = '%s'", title));
if (existingFiles.size() > 1) {
throw new IllegalStateException(String.format(
"Could not update file '%s' in Drive folder id '%s' because multiple files with that "
+ "name already exist.",
title,
parentFolderId));
}
return existingFiles.isEmpty()
? createFile(title, mimeType, parentFolderId, bytes)
: updateFile(existingFiles.get(0), title, mimeType, bytes);
}
示例11: testCreateOrUpdateFile_succeedsForNewFile
import com.google.common.net.MediaType; //导入依赖的package包/类
@Test
public void testCreateOrUpdateFile_succeedsForNewFile() throws Exception {
when(files.insert(
eq(new File()
.setTitle("title")
.setMimeType("video/webm")
.setParents(ImmutableList.of(new ParentReference().setId("driveFolderId")))),
argThat(hasByteArrayContent(DATA))))
.thenReturn(insert);
ChildList emptyChildList = new ChildList().setItems(ImmutableList.of()).setNextPageToken(null);
when(childrenList.execute()).thenReturn(emptyChildList);
assertThat(driveConnection.createOrUpdateFile(
"title",
MediaType.WEBM_VIDEO,
"driveFolderId",
DATA))
.isEqualTo("id");
}
示例12: init
import com.google.common.net.MediaType; //导入依赖的package包/类
@Before
public void init() throws Exception {
command.setConnection(connection);
premiumTermsPath = writeToNamedTmpFile(
"example_premium_terms.csv",
readResourceUtf8(
CreatePremiumListCommandTest.class,
"testdata/example_premium_terms.csv"));
servletPath = "/_dr/admin/createPremiumList";
when(connection.send(
eq(CreatePremiumListAction.PATH),
anyMapOf(String.class, String.class),
any(MediaType.class),
any(byte[].class)))
.thenReturn(JSON_SAFETY_PREFIX + "{\"status\":\"success\",\"lines\":[]}");
}
示例13: test_deleteTwoEntities
import com.google.common.net.MediaType; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void test_deleteTwoEntities() throws Exception {
String firstKey = "alphaNumericKey1";
String secondKey = "alphaNumericKey2";
String rawKeys = String.format("%s,%s", firstKey, secondKey);
when(connection.send(anyString(), anyMap(), any(MediaType.class), any(byte[].class)))
.thenReturn("Deleted 1 raw entities and 1 registered entities.");
runCommandForced(firstKey, secondKey);
verify(connection).send(
eq("/_dr/admin/deleteEntity"),
eq(ImmutableMap.of("rawKeys", rawKeys)),
eq(MediaType.PLAIN_TEXT_UTF_8),
eq(new byte[0]));
assertInStdout("Deleted 1 raw entities and 1 registered entities.");
}
示例14: getMetadata
import com.google.common.net.MediaType; //导入依赖的package包/类
/**
* Helper method that connects to the given URL and returns the response as
* a String
*
* @param url
* the URL to connect to
* @return the response content as a String
*/
protected String getMetadata(String url) throws MCRPersistenceException {
try {
URLConnection connection = getConnection(url);
connection.setConnectTimeout(getConnectTimeout());
String contentType = connection.getContentType();
Charset charset = StandardCharsets.ISO_8859_1; //defined by RFC 2616 (sec 3.7.1)
if (contentType != null) {
MediaType mediaType = MediaType.parse(contentType);
mediaType.charset().or(StandardCharsets.ISO_8859_1);
}
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
forwardData(connection, out);
return new String(out.toByteArray(), charset);
} catch (IOException exc) {
String msg = "Could not get metadata from Audio/Video Store URL: " + url;
throw new MCRPersistenceException(msg, exc);
}
}
示例15: isAcceptableMediaType
import com.google.common.net.MediaType; //导入依赖的package包/类
private boolean isAcceptableMediaType(KatharsisInvokerContext invokerContext) {
String acceptHeader = invokerContext.getRequestHeader("Accept");
if (acceptHeader != null) {
String[] accepts = acceptHeader.split(",");
MediaType acceptableType;
for (String mediaTypeItem : accepts) {
acceptableType = MediaType.parse(mediaTypeItem.trim());
if (JsonApiMediaType.isCompatibleMediaType(acceptableType)) {
return true;
}
}
}
return false;
}