本文整理汇总了Java中javax.ws.rs.core.MediaType类的典型用法代码示例。如果您正苦于以下问题:Java MediaType类的具体用法?Java MediaType怎么用?Java MediaType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MediaType类属于javax.ws.rs.core包,在下文中一共展示了MediaType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createInstance
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
/**
* Create a broker Instance
*
* @param brokerName
* @return
* @throws CloudKarafkaServiceException
*/
public CloudKarafkaCreateInstanceResponse createInstance(final String brokerName,
final String plan) throws CloudKarafkaServiceException {
// build input form
final MultivaluedMap<String, String> form = new MultivaluedHashMap<>();
form.add("name", brokerName);
form.add("plan", plan);
form.add("region", brokerConfig.getCloudKarafkaRegion());
//build post request
final String target = String.format("%s/%s", brokerConfig.getCloudkarafkaApiUrl(), "instances");
final WebTarget webTarget = client.target(target);
// call create broker instances API
return webTarget.request(MediaType.APPLICATION_JSON)
.post(Entity.form(form), CloudKarafkaCreateInstanceResponse.class);
}
示例2: createViaNP
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
/**
* NP経由でExtCellを作成するユーティリティ.
* @param cellName セル名
* @param token トークン
* @param extCellUrl ExtCellのUrl
* @param srcEntitySet ソース側エンティティセット名
* @param srcEntitySetKey ソース側エンティティのキー
* @param code レスポンスコード
* @return レスポンス
*/
@SuppressWarnings("unchecked")
public static TResponse createViaNP(
final String token,
final String cellName,
final String extCellUrl,
final String srcEntitySet,
final String srcEntitySetKey,
final int code) {
JSONObject body = new JSONObject();
body.put("Url", extCellUrl);
return Http.request("createNP.txt")
.with("token", token)
.with("accept", MediaType.APPLICATION_JSON)
.with("contentType", MediaType.APPLICATION_JSON)
.with("cell", cellName)
.with("entityType", srcEntitySet)
.with("id", srcEntitySetKey)
.with("navPropName", "_ExtCell")
.with("body", body.toString())
.returns()
.statusCode(code);
}
示例3: testJobCounters
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
@Test
public void testJobCounters() throws JSONException, Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("mapreduce")
.path("jobs").path(jobId).path("counters")
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject info = json.getJSONObject("jobCounters");
verifyAMJobCounters(info, jobsMap.get(id));
}
}
示例4: createData
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
/**
* Keyあり取得時にexpandに存在しないリースを指定した場合に400が返却されること.
*/
@Test
public final void Keyあり取得時にexpandに存在しないリースを指定した場合に400が返却されること() {
try {
// データ作成
createData();
// $expandを指定してデータを取得
Http.request("box/odatacol/list.txt")
.with("cell", Setup.TEST_CELL1)
.with("box", Setup.TEST_BOX1)
.with("collection", Setup.TEST_ODATA)
.with("entityType", navPropName + "('" + fromUserDataId + "')")
.with("query", "?\\$expand=_test")
.with("accept", MediaType.APPLICATION_JSON)
.with("token", PersoniumUnitConfig.getMasterToken())
.returns()
.statusCode(HttpStatus.SC_BAD_REQUEST)
.debug();
} finally {
// データ削除
deleteData();
}
}
示例5: addNamespacedList
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
@POST
@Path("validate")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response addNamespacedList(final SnapshotList snapshotList) {
NamespacedList namespace = (NamespacedList)snapshotList.getEntityToSave();
if (!namespacedListsService.getNamespaceDuplicates(namespace, snapshotList.getNamespaces()).isEmpty()) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity(new ErrorMessage("There are duplicates in the namespaced list.")).build());
}
try {
ModelValidationFacade.validateNamespacedList(namespace);
namespace.updateVersion();
namespace.setValueCount(namespace.getValueSet().size());
} catch (ExpressionValidationException ex) {
String error = String.format("Failed to save namespace '%s' due to validation error(s). %s", namespace.getName(), ex.getMessage());
throw new WebApplicationException(error, ex, Response.Status.BAD_REQUEST);
}
return Response.ok(namespace).build();
}
示例6: reply
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
public static void reply(
final RoutingContext context,
final Envelop envelop) {
// 1. Get response reference
final HttpServerResponse response
= context.response();
// 2. Set response status
final HttpStatusCode code = envelop.status();
response.setStatusCode(code.code());
response.setStatusMessage(code.message());
response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
// 3. Response process
if (!response.ended()) {
response.end(envelop.response());
}
response.close();
}
示例7: getKeyVersionPair
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
@GET
@Path(KMSRESTConstants.KEY_PAIR_VERSION_RESOURCE + "/{versionName:.*}")
@Produces(MediaType.APPLICATION_JSON)
public Response getKeyVersionPair(
@PathParam("versionName") final String versionName) throws Exception {
UserGroupInformation user = HttpUserGroupInformation.get();
KMSClientProvider.checkNotEmpty(versionName, "versionName");
KMSWebApp.getKeyCallsMeter().mark();
assertAccess(KMSACLs.Type.GET, user, KMSOp.GET_KEY_VERSION);
KeyPairVersion keyVersion = user.doAs(
new PrivilegedExceptionAction<KeyPairVersion>() {
@Override
public KeyPairVersion run() throws Exception {
return provider.getKeyPairVersion(versionName);
}
}
);
if (keyVersion != null) {
kmsAudit.ok(user, KMSOp.GET_KEY_VERSION, keyVersion.getName(), "");
}
Object json = KMSServerJSONUtils.toJSON(keyVersion);
return Response.ok().type(MediaType.APPLICATION_JSON).entity(json).build();
}
示例8:
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
/**
* UserDataに前方一致検索クエリに真偽値trueを指定した場合ステータスコード400が返却されること.
*/
@Test
public final void UserDataに前方一致検索クエリに真偽値trueを指定した場合ステータスコード400が返却されること() {
// ユーザデータの一覧取得
String sdEntityTypeName = "SalesDetail";
Http.request("box/odatacol/list.txt")
.with("cell", cellName)
.with("box", boxName)
.with("collection", colName)
.with("entityType", sdEntityTypeName)
.with("query", "?\\$filter=startswith%28truth%2ctrue%29")
.with("accept", MediaType.APPLICATION_JSON)
.with("token", PersoniumUnitConfig.getMasterToken())
.returns()
.statusCode(HttpStatus.SC_BAD_REQUEST)
.debug();
}
示例9: testInvalidRuleName
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
@Test
public void testInvalidRuleName() throws InstantiationException, IllegalAccessException {
IfExpressionBuilder builder = new IfExpressionBuilder();
IfExpression expression = builder.
withRuleName(invalidRuleName).
withExpression(newSingleParamExpression(Equals.class, "param1", "value1")).
withExpression(newSingleParamExpression(Matches.class, "param2", "value2")).
withExpression(newSingleParamExpression(NotEqual.class, "param3", "value3")).
withExpression(newSingleParamExpression(LessThan.class, "param4", "4")).
withReturnStatement(newSimpleServerForFlavor("1.1")).build();
// now trying to post rule with invalid name
WebTarget webTarget = HttpTestServerHelper.target().path(RULES_SERVICE_PATH).path(SERVICE_NAME).path(expression.getId());
ValidationState error = ServiceHelper.post(webTarget, expression, MediaType.APPLICATION_JSON, ValidationState.class, true);
// should get error ValidationState.ErrorType.InvalidRuleName
Assert.assertEquals(1, error.getErrors().size());
Assert.assertEquals(ValidationState.ErrorType.InvalidRuleName, error.getErrors().keySet().iterator().next());
}
示例10: testJobsQueryFinishTimeBeginNegative
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
@Test
public void testJobsQueryFinishTimeBeginNegative() throws JSONException,
Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs")
.queryParam("finishedTimeBegin", String.valueOf(-1000))
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
assertEquals(Status.BAD_REQUEST, response.getClientResponseStatus());
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject msg = response.getEntity(JSONObject.class);
JSONObject exception = msg.getJSONObject("RemoteException");
assertEquals("incorrect number of elements", 3, exception.length());
String message = exception.getString("message");
String type = exception.getString("exception");
String classname = exception.getString("javaClassName");
WebServicesTestUtils.checkStringMatch("exception message",
"java.lang.Exception: finishedTimeBegin must be greater than 0",
message);
WebServicesTestUtils.checkStringMatch("exception type",
"BadRequestException", type);
WebServicesTestUtils.checkStringMatch("exception classname",
"org.apache.hadoop.yarn.webapp.BadRequestException", classname);
}
示例11: createVirtualNetwork
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
/**
* Creates a virtual network from the JSON input stream.
*
* @param stream tenant identifier JSON stream
* @return status of the request - CREATED if the JSON is correct,
* BAD_REQUEST if the JSON is invalid
* @onos.rsModel TenantId
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createVirtualNetwork(InputStream stream) {
try {
final TenantId tid = TenantId.tenantId(getFromJsonStream(stream, "id").asText());
VirtualNetwork newVnet = vnetAdminService.createVirtualNetwork(tid);
UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
.path("vnets")
.path(newVnet.id().toString());
return Response
.created(locationBuilder.build())
.build();
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
示例12: addFile
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public FileOutVO addFile(@FormDataParam("json") FormDataBodyPart json,
@FormDataParam("data") FormDataBodyPart content,
@FormDataParam("data") FormDataContentDisposition contentDisposition,
@FormDataParam("data") final InputStream input) throws AuthenticationException, AuthorisationException, ServiceException {
// in.setTrialId(trialId);
// in.setModule(FileModule.TRIAL_DOCUMENT);
// https://stackoverflow.com/questions/27609569/file-upload-along-with-other-object-in-jersey-restful-web-service
json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
FileInVO in = json.getValueAs(FileInVO.class);
FileStreamInVO stream = new FileStreamInVO();
stream.setStream(input);
stream.setMimeType(content.getMediaType().toString()); // .getType());
stream.setSize(contentDisposition.getSize());
stream.setFileName(contentDisposition.getFileName());
return WebUtil.getServiceLocator().getFileService().addFile(auth, in, stream);
}
示例13: getAppState
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
@GET
@Path("/apps/{appid}/state")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public AppState getAppState(@Context HttpServletRequest hsr,
@PathParam("appid") String appId) throws AuthorizationException {
init();
UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true);
String userName = "";
if (callerUGI != null) {
userName = callerUGI.getUserName();
}
RMApp app = null;
try {
app = getRMAppForAppId(appId);
} catch (NotFoundException e) {
RMAuditLogger.logFailure(userName, AuditConstants.KILL_APP_REQUEST,
"UNKNOWN", "RMWebService",
"Trying to get state of an absent application " + appId);
throw e;
}
AppState ret = new AppState();
ret.setState(app.getState().toString());
return ret;
}
示例14: createFragment
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
@Pact(consumer = "AuthenticationService")
public PactFragment createFragment(PactDslWithProvider pactDslWithProvider) throws JsonProcessingException {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
return pactDslWithProvider
.given("Customer Sean is registered")
.uponReceiving("a request to validate Sean")
.path("/rest/api/login/validate")
.method("POST")
.query("sessionId=" + customerSessionInfo.getId())
.headers(headers)
.willRespondWith()
.status(200)
.body(objectMapper.writeValueAsString(customerSessionInfo), MediaType.APPLICATION_JSON)
.toFragment();
}
示例15: register
import javax.ws.rs.core.MediaType; //导入依赖的package包/类
@POST
@Path("register")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String register(@FormParam("userName") String userName,
@FormParam("password") String password,
@FormParam("phone") Long phone, @FormParam("email") String email,
@FormParam("nick") String nick, @FormParam("addr") String addr,
@FormParam("gender") String gender) {
// check not null
User u = new User();// dao 应该查询
u.setAddr(addr);
u.setEmail(email);
u.setGender(gender);
u.setNick(nick);
u.setPassword(password);
u.setPhone(phone);
u.setUsername(userName);
return JsonUtil.bean2Json(u);
}