下面列出了javax.ws.rs.core.MediaType#APPLICATION_JSON_TYPE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public ObjectMapper locateMapper(Class<?> type, MediaType mediaType) {
if (ourMapper != null)
return ourMapper;
findSharedMapper();
if (ourMapper != null)
return ourMapper;
if (!notFound) {
log.warn("Management context not available; using default ObjectMapper in "+this);
notFound = true;
}
return super.locateMapper(Object.class, MediaType.APPLICATION_JSON_TYPE);
}
/**
* 受信/送信メッセージEntityを作成する.
* @param uriInfo URL情報
* @param reader リクエストボディ
* @return response情報
*/
protected Response createMessage(UriInfo uriInfo,
Reader reader) {
// response用URLに__ctlを追加する
UriInfo resUriInfo = DcCoreUtils.createUriInfo(uriInfo, 2, "__ctl");
// Entityの作成を Producerに依頼
OEntityWrapper oew = getOEntityWrapper(reader, odataResource, CtlSchema.getEdmDataServicesForMessage().build());
EntityResponse res = getOdataProducer().createEntity(getEntitySetName(), oew);
// レスポンスボディを生成する
OEntity ent = res.getEntity();
MediaType outputFormat = MediaType.APPLICATION_JSON_TYPE;
List<MediaType> contentTypes = new ArrayList<MediaType>();
contentTypes.add(MediaType.APPLICATION_JSON_TYPE);
String key = AbstractODataResource.replaceDummyKeyToNull(ent.getEntityKey().toKeyString());
String responseStr = renderEntityResponse(resUriInfo, res, "json", contentTypes);
// 制御コードのエスケープ処理
responseStr = escapeResponsebody(responseStr);
ResponseBuilder rb = getPostResponseBuilder(ent, outputFormat, responseStr, resUriInfo, key);
return rb.build();
}
private MediaType getAcceptMediaType(List<MediaType> accept) {
Iterator<MediaType> it = accept.iterator();
while (it.hasNext()) {
MediaType mt = it.next();
/*
* application/xml media type causes an exception:
* org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure: Could not find MessageBodyWriter for response
* object of type: org.jboss.resteasy.api.validation.ViolationReport of media type: application/xml
*/
/*if (MediaType.APPLICATION_XML_TYPE.getType().equals(mt.getType())
&& MediaType.APPLICATION_XML_TYPE.getSubtype().equals(mt.getSubtype())) {
return MediaType.APPLICATION_XML_TYPE;
}*/
if (MediaType.APPLICATION_JSON_TYPE.getType().equals(mt.getType())
&& MediaType.APPLICATION_JSON_TYPE.getSubtype().equals(mt.getSubtype())) {
return MediaType.APPLICATION_JSON_TYPE;
}
}
return null;
}
public static MediaType getMediaType(final RequestContext request) {
MediaType outputType = MediaType.APPLICATION_JSON_TYPE;
final List<String> accept = request.getHeaders().get("Accept");
String responseMediaType = "";
if (accept != null && accept.get(0) != null) {
responseMediaType = accept.get(0);
}
if (MediaType.APPLICATION_XML.equals(responseMediaType)) {
return MediaType.APPLICATION_XML_TYPE;
}
boolean isJsonOK = false;
boolean isYamlOK = false;
final MediaType yamlMediaType = new MediaType(APPLICATION, YAML);
for (final MediaType mediaType : request.getAcceptableMediaTypes()) {
if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
isJsonOK = true;
} else if (mediaType.equals(yamlMediaType)) {
isYamlOK = true;
}
}
if (isYamlOK && !isJsonOK) {
outputType = yamlMediaType;
}
return outputType;
}
public static MediaType getMediaType(String acceptHeader) {
MediaType mediaType = null;
try {
mediaType = FHIRMediaType.valueOf(acceptHeader);
} catch (IllegalArgumentException e) {
// ignore
}
if (mediaType != null) {
MediaType outMediaType = null;
if (mediaType.isCompatible(FHIRMediaType.APPLICATION_FHIR_JSON_TYPE)) {
outMediaType = FHIRMediaType.APPLICATION_FHIR_JSON_TYPE;
} else if (mediaType.isCompatible(FHIRMediaType.APPLICATION_JSON_TYPE)) {
outMediaType = MediaType.APPLICATION_JSON_TYPE;
} else if (mediaType.isCompatible(FHIRMediaType.APPLICATION_FHIR_XML_TYPE)) {
outMediaType = FHIRMediaType.APPLICATION_FHIR_XML_TYPE;
} else if (mediaType.isCompatible(FHIRMediaType.APPLICATION_XML_TYPE)) {
outMediaType = MediaType.APPLICATION_XML_TYPE;
} else {
outMediaType = FHIRMediaType.APPLICATION_FHIR_JSON_TYPE;
}
// Need to get the charset setting from the acceptHeader if there
if (mediaType.getParameters() != null
&& mediaType.getParameters().get("charset") != null) {
outMediaType = outMediaType.withCharset(mediaType.getParameters().get("charset"));
}
return outMediaType;
}
// default
return FHIRMediaType.APPLICATION_FHIR_JSON_TYPE;
}
public static MediaType parseMediaType(String extension) {
// FIXME: bigger list, and override in config
if(extension.equalsIgnoreCase("html"))
return MediaType.TEXT_HTML_TYPE;
if(extension.equalsIgnoreCase("xml"))
return MediaType.APPLICATION_XML_TYPE;
if(extension.equalsIgnoreCase("txt"))
return MediaType.TEXT_PLAIN_TYPE;
if(extension.equalsIgnoreCase("json"))
return MediaType.APPLICATION_JSON_TYPE;
System.err.println("Unknown extension type: "+extension);
return MediaType.APPLICATION_OCTET_STREAM_TYPE;
}
private static MediaType mediaTypeFor(final String type) {
if ("json".equals(type)) {
return MediaType.APPLICATION_JSON_TYPE;
}
return YAML_TYPE;
}
/**
* DomainのJson形式のリストのフォーマットチェック.
* @param response DcResponseオブジェクト
* @param contentType レスポンスのContentType
*/
public final void checkDomainListResponse(DcResponse response, MediaType contentType) {
// Cell取得のレスポンスチェック
// 200になることを確認
assertEquals(HttpStatus.SC_OK, response.getStatusCode());
// DataServiceVersionのチェック
Header[] resDsvHeaders = response.getResponseHeaders(ODataConstants.Headers.DATA_SERVICE_VERSION);
assertEquals(1, resDsvHeaders.length);
assertEquals("2.0", resDsvHeaders[0].getValue());
// ContentTypeのチェック
Header[] resContentTypeHeaders = response.getResponseHeaders(HttpHeaders.CONTENT_TYPE);
assertEquals(1, resContentTypeHeaders.length);
String value = resContentTypeHeaders[0].getValue();
String[] values = value.split(";");
assertEquals(contentType.toString(), values[0]);
if (contentType == MediaType.APPLICATION_JSON_TYPE) {
// レスポンスボディのJsonもチェックが必要
checkDomainListResponse(response.bodyAsJson());
} else if (contentType == MediaType.APPLICATION_ATOM_XML_TYPE) {
// レスポンスボディのチェック
fail("Not Implemented.");
// checkCellXML(response.bodyAsXml());
}
}
@Override
public Response toResponse(AccessDeniedException e) {
//There are a few jax-rs resources that generate HTML content, and we want the
//default web-container error handler pages to get used in those cases.
if (headers.getAcceptableMediaTypes().contains(MediaType.TEXT_HTML_TYPE)) {
try {
response.sendError(403, e.getMessage());
return null; //the error page handles the response, so no need to return a response
} catch (IOException ex) {
LOG.error("Error displaying error page", ex);
}
}
Response.Status errorStatus = Response.Status.FORBIDDEN;
SLIPrincipal principal = null ;
String message = e.getMessage();
if (SecurityContextHolder.getContext().getAuthentication() != null) {
principal = (SLIPrincipal)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
LOG.warn("Access has been denied to user: {}",principal );
} else {
LOG.warn("Access has been denied to user for being incorrectly associated");
}
LOG.warn("Cause: {}", e.getMessage());
MediaType errorType = MediaType.APPLICATION_JSON_TYPE;
if(this.headers.getMediaType() == MediaType.APPLICATION_XML_TYPE) {
errorType = MediaType.APPLICATION_XML_TYPE;
}
return Response.status(errorStatus).entity(new ErrorResponse(errorStatus.getStatusCode(), errorStatus.getReasonPhrase(), "Access DENIED: " + e.getMessage())).type(errorType).build();
}
private MediaType typeOfMediaType(String type) {
switch (type) {
case XML:
return MediaType.APPLICATION_XML_TYPE;
case JSON:
return MediaType.APPLICATION_JSON_TYPE;
case MediaType.WILDCARD:
return MediaType.WILDCARD_TYPE;
default:
throw new IllegalArgumentException("Unsupported media type " + type);
}
}
/**
* クエリでの指定($format)から出力フォーマットを決定する.
* @param format $formatの指定値
* @return 出力フォーマット("application/json" or "application/atom+xml")
*/
private MediaType decideOutputFormatFromQueryValue(String format) {
MediaType mediaType = null;
if (format.equals(FORMAT_ATOM)) {
// $formatの指定がatomである場合
mediaType = MediaType.APPLICATION_ATOM_XML_TYPE;
} else if (format.equals(FORMAT_JSON)) {
mediaType = MediaType.APPLICATION_JSON_TYPE;
} else {
throw DcCoreException.OData.FORMAT_INVALID_ERROR.params(format);
}
return mediaType;
}
public boolean init() {
if ( super.init() ) {
data.resultFieldName = environmentSubstitute( meta.getFieldName() );
data.resultCodeFieldName = environmentSubstitute( meta.getResultCodeFieldName() );
data.resultResponseFieldName = environmentSubstitute( meta.getResponseTimeFieldName() );
data.resultHeaderFieldName = environmentSubstitute( meta.getResponseHeaderFieldName() );
// get authentication settings once
data.realProxyHost = environmentSubstitute( meta.getProxyHost() );
data.realProxyPort = Const.toInt( environmentSubstitute( meta.getProxyPort() ), 8080 );
data.realHttpLogin = environmentSubstitute( meta.getHttpLogin() );
data.realHttpPassword = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( meta.getHttpPassword() ) );
if ( !meta.isDynamicMethod() ) {
data.method = environmentSubstitute( meta.getMethod() );
if ( Utils.isEmpty( data.method ) ) {
logError( BaseMessages.getString( PKG, "Rest.Error.MethodMissing" ) );
return false;
}
}
data.trustStoreFile = environmentSubstitute( meta.getTrustStoreFile() );
data.trustStorePassword = environmentSubstitute( meta.getTrustStorePassword() );
String applicationType = Const.NVL( meta.getApplicationType(), "" );
if ( applicationType.equals( RestMeta.APPLICATION_TYPE_XML ) ) {
data.mediaType = MediaType.APPLICATION_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_JSON ) ) {
data.mediaType = MediaType.APPLICATION_JSON_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_OCTET_STREAM ) ) {
data.mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_XHTML ) ) {
data.mediaType = MediaType.APPLICATION_XHTML_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_FORM_URLENCODED ) ) {
data.mediaType = MediaType.APPLICATION_FORM_URLENCODED_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_ATOM_XML ) ) {
data.mediaType = MediaType.APPLICATION_ATOM_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_SVG_XML ) ) {
data.mediaType = MediaType.APPLICATION_SVG_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_TEXT_XML ) ) {
data.mediaType = MediaType.TEXT_XML_TYPE;
} else {
data.mediaType = MediaType.TEXT_PLAIN_TYPE;
}
try {
setConfig();
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "Rest.Error.Config" ), e );
return false;
}
return true;
}
return false;
}
protected void doFilter(ContainerRequestContext context, Message m) {
if (!"GET".equals(m.get(Message.HTTP_REQUEST_METHOD))) {
return;
}
UriInfo ui = context.getUriInfo();
if (!ui.getQueryParameters().containsKey(WADL_QUERY)) {
if (stylesheetReference != null || !docLocationMap.isEmpty()) {
String path = ui.getPath(false);
if (path.startsWith("/") && path.length() > 0) {
path = path.substring(1);
}
if (stylesheetReference != null && path.endsWith(".xsl")
|| docLocationMap.containsKey(path)) {
context.abortWith(getExistingResource(m, ui, path));
}
}
return;
}
if (ignoreRequests) {
context.abortWith(Response.status(404).build());
return;
}
if (whiteList != null && !whiteList.isEmpty()) {
ServletRequest servletRequest = (ServletRequest)m.getContextualProperty(
"HTTP.REQUEST");
String remoteAddress = null;
if (servletRequest != null) {
remoteAddress = servletRequest.getRemoteAddr();
} else {
remoteAddress = "";
}
boolean foundMatch = false;
for (String addr : whiteList) {
if (addr.equals(remoteAddress)) {
foundMatch = true;
break;
}
}
if (!foundMatch) {
context.abortWith(Response.status(404).build());
return;
}
}
HttpHeaders headers = new HttpHeadersImpl(m);
List<MediaType> accepts = headers.getAcceptableMediaTypes();
MediaType type = accepts.contains(WADL_TYPE) ? WADL_TYPE : accepts
.contains(MediaType.APPLICATION_JSON_TYPE) ? MediaType.APPLICATION_JSON_TYPE
: defaultWadlResponseMediaType;
Response response = getExistingWadl(m, ui, type);
if (response != null) {
context.abortWith(response);
return;
}
boolean isJson = isJson(type);
StringBuilder sbMain = generateWADL(getBaseURI(m, ui), getResourcesList(m, ui), isJson, m, ui);
m.getExchange().put(JAXRSUtils.IGNORE_MESSAGE_WRITERS, !isJson && ignoreMessageWriters);
Response r = Response.ok().type(type).entity(createResponseEntity(m, ui, sbMain.toString(), isJson)).build();
context.abortWith(r);
}
private FormDataBodyPart getImportRequestBodyPart(AtlasImportRequest request) {
return new FormDataBodyPart(IMPORT_REQUEST_PARAMTER, AtlasType.toJson(request), MediaType.APPLICATION_JSON_TYPE);
}
public void testCreateNewContentFromJson() throws Throwable {
MediaType mediaType = MediaType.APPLICATION_JSON_TYPE;
this.testCreateNewLabel(mediaType);
}
@Test(timeout = 120000)
public void testSingleAppKill() throws Exception {
rm.start();
MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
String[] mediaTypes =
{ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML };
MediaType[] contentTypes =
{ MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE };
for (String mediaType : mediaTypes) {
for (MediaType contentType : contentTypes) {
RMApp app = rm.submitApp(CONTAINER_MB, "", webserviceUserName);
amNodeManager.nodeHeartbeat(true);
AppState targetState =
new AppState(YarnApplicationState.KILLED.toString());
Object entity;
if (contentType.equals(MediaType.APPLICATION_JSON_TYPE)) {
entity = appStateToJSON(targetState);
} else {
entity = targetState;
}
ClientResponse response =
this
.constructWebResource("apps", app.getApplicationId().toString(),
"state").entity(entity, contentType).accept(mediaType)
.put(ClientResponse.class);
if (!isAuthenticationEnabled()) {
assertEquals(Status.UNAUTHORIZED, response.getClientResponseStatus());
continue;
}
assertEquals(Status.ACCEPTED, response.getClientResponseStatus());
if (mediaType.equals(MediaType.APPLICATION_JSON)) {
verifyAppStateJson(response, RMAppState.FINAL_SAVING,
RMAppState.KILLED, RMAppState.KILLING, RMAppState.ACCEPTED);
} else {
verifyAppStateXML(response, RMAppState.FINAL_SAVING,
RMAppState.KILLED, RMAppState.KILLING, RMAppState.ACCEPTED);
}
String locationHeaderValue =
response.getHeaders().getFirst(HttpHeaders.LOCATION);
Client c = Client.create();
WebResource tmp = c.resource(locationHeaderValue);
if (isAuthenticationEnabled()) {
tmp = tmp.queryParam("user.name", webserviceUserName);
}
response = tmp.get(ClientResponse.class);
assertEquals(Status.OK, response.getClientResponseStatus());
assertTrue(locationHeaderValue.endsWith("/ws/v1/cluster/apps/"
+ app.getApplicationId().toString() + "/state"));
while (true) {
Thread.sleep(100);
response =
this
.constructWebResource("apps",
app.getApplicationId().toString(), "state").accept(mediaType)
.entity(entity, contentType).put(ClientResponse.class);
assertTrue((response.getClientResponseStatus() == Status.ACCEPTED)
|| (response.getClientResponseStatus() == Status.OK));
if (response.getClientResponseStatus() == Status.OK) {
assertEquals(RMAppState.KILLED, app.getState());
if (mediaType.equals(MediaType.APPLICATION_JSON)) {
verifyAppStateJson(response, RMAppState.KILLED);
} else {
verifyAppStateXML(response, RMAppState.KILLED);
}
break;
}
}
}
}
rm.stop();
}
public void testGetJsonContent() throws Throwable {
MediaType mediaType = MediaType.APPLICATION_JSON_TYPE;
this.testGetContent(mediaType, "admin", "ALL4", "en");
}
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (RestMeta) smi;
data = (RestData) sdi;
if ( super.init( smi, sdi ) ) {
data.resultFieldName = environmentSubstitute( meta.getFieldName() );
data.resultCodeFieldName = environmentSubstitute( meta.getResultCodeFieldName() );
data.resultResponseFieldName = environmentSubstitute( meta.getResponseTimeFieldName() );
data.resultHeaderFieldName = environmentSubstitute( meta.getResponseHeaderFieldName() );
// get authentication settings once
data.realProxyHost = environmentSubstitute( meta.getProxyHost() );
data.realProxyPort = Const.toInt( environmentSubstitute( meta.getProxyPort() ), 8080 );
data.realHttpLogin = environmentSubstitute( meta.getHttpLogin() );
data.realHttpPassword = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( meta.getHttpPassword() ) );
if ( !meta.isDynamicMethod() ) {
data.method = environmentSubstitute( meta.getMethod() );
if ( Utils.isEmpty( data.method ) ) {
logError( BaseMessages.getString( PKG, "Rest.Error.MethodMissing" ) );
return false;
}
}
data.trustStoreFile = environmentSubstitute( meta.getTrustStoreFile() );
data.trustStorePassword = environmentSubstitute( meta.getTrustStorePassword() );
String applicationType = Const.NVL( meta.getApplicationType(), "" );
if ( applicationType.equals( RestMeta.APPLICATION_TYPE_XML ) ) {
data.mediaType = MediaType.APPLICATION_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_JSON ) ) {
data.mediaType = MediaType.APPLICATION_JSON_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_OCTET_STREAM ) ) {
data.mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_XHTML ) ) {
data.mediaType = MediaType.APPLICATION_XHTML_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_FORM_URLENCODED ) ) {
data.mediaType = MediaType.APPLICATION_FORM_URLENCODED_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_ATOM_XML ) ) {
data.mediaType = MediaType.APPLICATION_ATOM_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_SVG_XML ) ) {
data.mediaType = MediaType.APPLICATION_SVG_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_TEXT_XML ) ) {
data.mediaType = MediaType.TEXT_XML_TYPE;
} else {
data.mediaType = MediaType.TEXT_PLAIN_TYPE;
}
try {
setConfig();
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "Rest.Error.Config" ), e );
return false;
}
return true;
}
return false;
}
@Test
public void testSetDatastreamProfile() throws Exception {
RemoteStorage fedora = new RemoteStorage(client);
LocalObject local = new LocalStorage().create();
local.setLabel(test.getMethodName());
fedora.ingest(local, "junit");
RemoteObject remote = fedora.find(local.getPid());
String dsId = "missingDatastream";
MediaType mime = MediaType.TEXT_PLAIN_TYPE;
// first test missing datastream
RemoteXmlStreamEditor editor = new RemoteXmlStreamEditor(remote, FoxmlUtils.managedProfile(dsId, mime, "defaultLabel"));
DatastreamProfile profile = editor.getProfile();
assertEquals(mime.toString(), profile.getDsMIME());
String expectedLabel = "label1";
profile.setDsLabel(expectedLabel);
editor.setProfile(profile);
editor.write(new byte[2], editor.getLastModified(), "write1");
remote.flush();
editor = new RemoteXmlStreamEditor(remote, FoxmlUtils.managedProfile(dsId, mime, ""));
profile = editor.getProfile();
assertEquals(mime.toString(), profile.getDsMIME());
assertEquals(expectedLabel, profile.getDsLabel());
// test existing datastream
expectedLabel = "label2";
MediaType newMime = MediaType.TEXT_HTML_TYPE;
profile = editor.getProfile();
profile.setDsMIME(newMime.toString());
profile.setDsLabel(expectedLabel);
editor.setProfile(profile);
editor.write(new byte[2], editor.getLastModified(), "write2");
profile = editor.getProfile();
assertEquals(newMime.toString(), profile.getDsMIME());
assertEquals(expectedLabel, profile.getDsLabel());
remote.flush();
editor = new RemoteXmlStreamEditor(remote, FoxmlUtils.managedProfile(dsId, mime, ""));
profile = editor.getProfile();
assertEquals(newMime.toString(), profile.getDsMIME());
assertEquals(expectedLabel, profile.getDsLabel());
// test standalone profile change (without content)
newMime = MediaType.APPLICATION_JSON_TYPE;
expectedLabel = "label3";
profile.setDsMIME(newMime.toString());
profile.setDsLabel(expectedLabel);
editor.setProfile(profile);
remote.flush();
editor = new RemoteXmlStreamEditor(remote, FoxmlUtils.managedProfile(dsId, mime, ""));
profile = editor.getProfile();
assertEquals(newMime.toString(), profile.getDsMIME());
assertEquals(expectedLabel, profile.getDsLabel());
}
public CreateBranchRequest(String baseUri, BranchDescriptor branch) {
super(baseUri + request, branch, MediaType.APPLICATION_JSON_TYPE);
}