下面列出了javax.ws.rs.client.Entity#json ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public PowerBiResponse put(String json) throws RateLimitExceededException, RequestAuthenticationException {
Entity<String> entity = Entity.json(json);
Response r = request.put(entity);
checkResponseCode(r);
return new PowerBiResponseImpl(r);
}
@Test
public void testGetResponsePostInvalidKey() throws Exception {
AsyncDataToken dataToken = new AsyncDataToken("group", null);
Entity<AsyncDataToken> asyncDataTokenEntity = Entity.json(dataToken);
GroupResponse response = resources.client()
.target("/v1/async")
.request()
.post(asyncDataTokenEntity, GroupResponse.class);
assertNull(response);
}
@Test
public void TestGetMe() {
webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetMe());
Entity<Update> entity = Entity.json(getUpdate());
BotApiMethod result =
target("callback/testbot")
.request(MediaType.APPLICATION_JSON)
.post(entity, GetMe.class);
assertEquals("{\"method\":\"getme\"}", map(result));
}
/**
* This demonstrates a client who provides the correct credentials, a valid
* token, and passes all of the business rules to access the protected
* resource.
*/
@Test
public final void verifySuccessfulBusinessRuleCheck() {
// given
final LoginRequest login = new LoginRequest("alice", "1QYCGznPQ1z8T1aX_CNXKheDMAnNSfq_xnSxWXPLeKU=");
final Entity<LoginRequest> entity = Entity.json(login);
final String tokenString = target("session").request().accept(MediaType.TEXT_PLAIN_TYPE).post(entity, String.class);
// when
final String result = target("secrets").request().header("X-Authorization", tokenString).get(String.class);
// then
assertEquals("42", result);
}
@Test
public void synchronizeBadJSON() throws Exception {
String json = "NOT_A_JSON_STRING";
Entity<String> entity = Entity.json(json);
Response response = target("/v1/synchronize").request(MediaType.APPLICATION_JSON_TYPE).post(entity);
int statusCode = response.getStatus();
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), statusCode);
}
@Test
public void TestGetChat() {
webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetChat());
Entity<Update> entity = Entity.json(getUpdate());
BotApiMethod result =
target("callback/testbot")
.request(MediaType.APPLICATION_JSON)
.post(entity, GetChat.class);
assertEquals("{\"chat_id\":\"12345\",\"method\":\"getChat\"}", map(result));
}
@Test
public void testSaveDocumentsEmptyList() throws Exception {
Entity<List<Document>> list = Entity.json(Collections.emptyList());
Response response = resources.client()
.target(String.format("/v1/document/%s/bulk", TestUtils.TEST_TABLE_NAME))
.request()
.post(list);
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
public void testToOne_FromNull() {
e2().insertColumns("id_", "name")
.values(1, "xxx")
.values(8, "yyy").exec();
e3().insertColumns("id_", "name", "e2_id").values(3, "zzz", null).exec();
Entity<String> entity = Entity.json("{\"id\":3,\"e2\":8}");
Response response = target("/e3/3").request().put(entity);
onSuccess(response).bodyEquals(1, "{\"id\":3,\"name\":\"zzz\",\"phoneNumber\":null}");
e3().matcher().eq("id_", 3).eq("e2_id", 8).assertOneMatch();
}
@Test
public void TestUnbanChatMember() {
webhookBot.setReturnValue(BotApiMethodHelperFactory.getUnbanChatMember());
Entity<Update> entity = Entity.json(getUpdate());
BotApiMethod result =
target("callback/testbot")
.request(MediaType.APPLICATION_JSON)
.post(entity, UnbanChatMember.class);
assertEquals("{\"chat_id\":\"12345\",\"user_id\":98765,\"method\":\"unbanchatmember\"}", map(result));
}
private Entity<InputStream> toEntity(Request request) {
InputStream body = request.body();
if (body != null) {
return Entity.entity(body, MediaType.APPLICATION_JSON_TYPE);
}
switch (request.method()) {
case "POST":
return Entity.json(null);
default:
return null;
}
}
public Entity build() {
HashMap<String, Object> map = new HashMap<>();
map.put("serviceEntityId", serviceEntityId);
map.put("assertionConsumerServiceUrl", assertionConsumerServiceUrl);
map.put("signingCertificate", signingCertificate);
map.put("encryptionCertificate", encryptionCertificate);
map.put("matchingDatasetJson", matchingDataset);
return Entity.json(map);
}
@Test
public void TestSendMessage() {
webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendMessage());
Entity<Update> entity = Entity.json(getUpdate());
BotApiMethod result =
target("callback/testbot")
.request(MediaType.APPLICATION_JSON)
.post(entity, SendMessage.class);
assertEquals("{\"chat_id\":\"@test\",\"text\":\"Hithere\",\"parse_mode\":\"html\",\"reply_to_message_id\":12,\"reply_markup\":{\"force_reply\":true},\"method\":\"sendmessage\"}", map(result));
}
@Test
public void TestAnswerCallbackQuery() {
webhookBot.setReturnValue(BotApiMethodHelperFactory.getAnswerCallbackQuery());
Entity<Update> entity = Entity.json(getUpdate());
BotApiMethod result =
target("callback/testbot")
.request(MediaType.APPLICATION_JSON)
.post(entity, AnswerCallbackQuery.class);
assertEquals("{\"callback_query_id\":\"id\",\"text\":\"text\",\"show_alert\":true,\"method\":\"answercallbackquery\"}", map(result));
}
@Test
public void TestAnswerInlineQuery() {
webhookBot.setReturnValue(BotApiMethodHelperFactory.getAnswerInlineQuery());
Entity<Update> entity = Entity.json(getUpdate());
BotApiMethod result =
target("callback/testbot")
.request(MediaType.APPLICATION_JSON)
.post(entity, AnswerInlineQuery.class);
assertEquals("{\"personal\":true,\"inline_query_id\":\"id\",\"results\":[{\"type\":\"article\",\"id\":\"0\",\"title\":\"Title\",\"input_message_content\":{\"message_text\":\"Text\",\"parse_mode\":\"Markdown\"},\"reply_markup\":{\"inline_keyboard\":[[{\"text\":\"Button1\",\"callback_data\":\"Callback\"}]]},\"url\":\"Url\",\"hide_url\":false,\"description\":\"Description\",\"thumb_url\":\"ThumbUrl\",\"thumb_width\":10,\"thumb_height\":20},{\"type\":\"photo\",\"id\":\"1\",\"photo_url\":\"PhotoUrl\",\"mime_type\":\"image/jpg\",\"photo_width\":10,\"photo_height\":20,\"thumb_url\":\"ThumbUrl\",\"title\":\"Title\",\"description\":\"Description\",\"caption\":\"Caption\",\"input_message_content\":{\"message_text\":\"Text\",\"parse_mode\":\"Markdown\"},\"reply_markup\":{\"inline_keyboard\":[[{\"text\":\"Button1\",\"callback_data\":\"Callback\"}]]}}],\"cache_time\":100,\"is_personal\":true,\"next_offset\":\"3\",\"switch_pm_text\":\"pmText\",\"switch_pm_parameter\":\"PmParameter\",\"method\":\"answerInlineQuery\"}", map(result));
}
@Test
public void TestGetChatMember() {
webhookBot.setReturnValue(BotApiMethodHelperFactory.getChatMember());
Entity<Update> entity = Entity.json(getUpdate());
BotApiMethod result =
target("callback/testbot")
.request(MediaType.APPLICATION_JSON)
.post(entity, GetChatMember.class);
assertEquals("{\"chat_id\":\"12345\",\"user_id\":98765,\"method\":\"getChatMember\"}", map(result));
}
@Test
public void TestSetGameScore() {
webhookBot.setReturnValue(BotApiMethodHelperFactory.getSetGameScore());
Entity<Update> entity = Entity.json(getUpdate());
BotApiMethod result =
target("callback/testbot")
.request(MediaType.APPLICATION_JSON)
.post(entity, SetGameScore.class);
assertEquals("{\"inline_message_id\":\"12345\",\"disable_edit_message\":true,\"user_id\":98765,\"score\":12,\"method\":\"setGameScore\"}", map(result));
}
/**
* @param since
* @param types
* @param properties
* @param exportType
* @return
* @throws Exception
*/
public String submitExport(Instant since, List<String> types, Map<String, String> properties, ExportType exportType)
throws Exception {
WebTarget target = getWebTarget(properties.get(BulkDataConfigUtil.BATCH_URL));
JobInstanceRequest.Builder builder = JobInstanceRequest.builder();
builder.applicationName(properties.get(BulkDataConfigUtil.APPLICATION_NAME));
builder.moduleName(properties.get(BulkDataConfigUtil.MODULE_NAME));
builder.cosBucketName(properties.get(BulkDataConfigUtil.JOB_PARAMETERS_BUCKET));
builder.cosLocation(properties.get(BulkDataConfigUtil.JOB_PARAMETERS_LOCATION));
builder.cosEndpointUrl(properties.get(BulkDataConfigUtil.JOB_PARAMETERS_ENDPOINT));
builder.cosCredentialIbm(properties.get(BulkDataConfigUtil.JOB_PARAMETERS_IBM));
builder.cosApiKey(properties.get(BulkDataConfigUtil.JOB_PARAMETERS_KEY));
builder.cosSrvInstId(properties.get(BulkDataConfigUtil.JOB_PARAMETERS_ID));
// Fetch a string generated from random 32 bytes
builder.cosBucketPathPrefix(FHIRUtil.getRandomKey("AES"));
// Export Type - FHIR
switch (exportType) {
case PATIENT:
builder.jobXMLName("FhirBulkExportPatientChunkJob");
break;
case GROUP:
builder.jobXMLName("FhirBulkExportGroupChunkJob");
builder.fhirPatientGroupId(properties.get(BulkDataConstants.PARAM_GROUP_ID));
break;
default:
builder.jobXMLName("FhirBulkExportChunkJob");
break;
}
String fhirTenant = FHIRRequestContext.get().getTenantId();
builder.fhirTenant(fhirTenant);
String fhirDataStoreId = FHIRRequestContext.get().getDataStoreId();
builder.fhirDataStoreId(fhirDataStoreId);
String resourceType = String.join(",", types);
builder.fhirResourceType(resourceType);
if (since != null) {
builder.fhirSearchFromDate(since.getValue().format(Instant.PARSER_FORMATTER));
} else {
builder.fhirSearchFromDate("1970-01-01");
}
if (properties.get(BulkDataConstants.PARAM_TYPE_FILTER) != null) {
builder.fhirTypeFilters(properties.get(BulkDataConstants.PARAM_TYPE_FILTER));
}
String entityStr = JobInstanceRequest.Writer.generate(builder.build(), true);
Entity<String> entity = Entity.json(entityStr);
Response r = target.request().post(entity);
String responseStr = r.readEntity(String.class);
// Debug / Dev only
if (log.isLoggable(Level.FINE)) {
log.warning("JSON -> \n" + responseStr);
}
JobInstanceResponse response = JobInstanceResponse.Parser.parse(responseStr);
// From the response
String jobId = Integer.toString(response.getInstanceId());
String baseUri = properties.get(BulkDataConfigUtil.BASE_URI);
return baseUri + "/$bulkdata-status?job="
+ BulkDataExportUtil.encryptBatchJobId(jobId, BulkDataConstants.BATCHJOBID_ENCRYPTION_KEY);
}
@Test
public void testGetResponsePost() throws Exception {
GroupRequest groupRequest = new GroupRequest();
groupRequest.setTable(TestUtils.TEST_TABLE_NAME);
groupRequest.setNesting(Arrays.asList("os", "device", "version"));
Map<String, Object> expectedResponse = new LinkedHashMap<String, Object>();
final Map<String, Object> nexusResponse = new LinkedHashMap<String, Object>() {{
put("1", 2);
put("2", 2);
put("3", 1);
}};
final Map<String, Object> galaxyResponse = new LinkedHashMap<String, Object>() {{
put("2", 1);
put("3", 1);
}};
expectedResponse.put("android", new LinkedHashMap<String, Object>() {{
put("nexus", nexusResponse);
put("galaxy", galaxyResponse);
}});
final Map<String, Object> nexusResponse2 = new LinkedHashMap<String, Object>() {{
put("2", 1);
}};
final Map<String, Object> iPadResponse = new LinkedHashMap<String, Object>() {{
put("2", 2);
}};
final Map<String, Object> iPhoneResponse = new LinkedHashMap<String, Object>() {{
put("1", 1);
}};
expectedResponse.put("ios", new LinkedHashMap<String, Object>() {{
put("nexus", nexusResponse2);
put("ipad", iPadResponse);
put("iphone", iPhoneResponse);
}});
AsyncDataToken dataToken = getQueryExecutor().executeAsync(groupRequest);
await().pollDelay(5000, TimeUnit.MILLISECONDS).until(() -> true);
Entity<AsyncDataToken> asyncDataTokenEntity = Entity.json(dataToken);
GroupResponse response = resources.client()
.target("/v1/async")
.request()
.post(asyncDataTokenEntity, GroupResponse.class);
assertEquals(expectedResponse, response.getResult());
}
@Test
public void testRunSyncAsync() throws Exception {
GroupRequest groupRequest = new GroupRequest();
groupRequest.setTable(TestUtils.TEST_TABLE_NAME);
groupRequest.setNesting(Arrays.asList("os", "device", "version"));
Map<String, Object> expectedResponse = new LinkedHashMap<String, Object>();
final Map<String, Object> nexusResponse = new LinkedHashMap<String, Object>() {{
put("1", 2);
put("2", 2);
put("3", 1);
}};
final Map<String, Object> galaxyResponse = new LinkedHashMap<String, Object>() {{
put("2", 1);
put("3", 1);
}};
expectedResponse.put("android", new LinkedHashMap<String, Object>() {{
put("nexus", nexusResponse);
put("galaxy", galaxyResponse);
}});
final Map<String, Object> nexusResponse2 = new LinkedHashMap<String, Object>() {{
put("2", 1);
}};
final Map<String, Object> iPadResponse = new LinkedHashMap<String, Object>() {{
put("2", 2);
}};
final Map<String, Object> iPhoneResponse = new LinkedHashMap<String, Object>() {{
put("1", 1);
}};
expectedResponse.put("ios", new LinkedHashMap<String, Object>() {{
put("nexus", nexusResponse2);
put("ipad", iPadResponse);
put("iphone", iPhoneResponse);
}});
Entity<GroupRequest> serviceUserEntity = Entity.json(groupRequest);
AsyncDataToken response = resources.client()
.target("/v1/analytics/async")
.request()
.post(serviceUserEntity, AsyncDataToken.class);
await().pollDelay(2000, TimeUnit.MILLISECONDS).until(() -> true);
GroupResponse actualResponse = GroupResponse.class.cast(getCacheManager().getCacheFor(response.getAction())
.get(response.getKey()));
assertEquals(expectedResponse, actualResponse.getResult());
}
/**
* Builds, signs and executes a request to an API endpoint using the provided credentials.
* Signs the request using the Amazon Signature 4 algorithm and returns the response.
* @param apiClient Jersey Client object
* @param accessKey access key
* @param secretKey secret key
* @param httpMethod the method (GET, POST...)
* @param endpointURL protocol://host:port
* @param reqPath the API resource path relative to the endpointURL
* @param headers headers map
* @param params parameters map
* @param jsonEntity an object serialized to JSON byte array (payload), could be null
* @return a response object
*/
public Response invokeSignedRequest(Client apiClient, String accessKey, String secretKey,
String httpMethod, String endpointURL, String reqPath,
Map<String, String> headers, MultivaluedMap<String, String> params, byte[] jsonEntity) {
boolean isJWT = StringUtils.startsWithIgnoreCase(secretKey, "Bearer");
WebTarget target = apiClient.target(endpointURL).path(reqPath);
Map<String, String> signedHeaders = new HashMap<>();
if (!isJWT) {
signedHeaders = signRequest(accessKey, secretKey, httpMethod, endpointURL, reqPath,
headers, params, jsonEntity);
}
if (params != null) {
for (Map.Entry<String, List<String>> param : params.entrySet()) {
String key = param.getKey();
List<String> value = param.getValue();
if (value != null && !value.isEmpty() && value.get(0) != null) {
target = target.queryParam(key, value.toArray());
}
}
}
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON);
if (headers != null) {
for (Map.Entry<String, String> header : headers.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
}
Entity<?> jsonPayload = null;
if (jsonEntity != null && jsonEntity.length > 0) {
try {
jsonPayload = Entity.json(new String(jsonEntity, Config.DEFAULT_ENCODING));
} catch (IOException ex) {
logger.error(null, ex);
}
}
if (isJWT) {
builder.header(HttpHeaders.AUTHORIZATION, secretKey);
} else {
builder.header(HttpHeaders.AUTHORIZATION, signedHeaders.get(HttpHeaders.AUTHORIZATION)).
header("X-Amz-Date", signedHeaders.get("X-Amz-Date"));
}
if (Config.getConfigBoolean("user_agent_id_enabled", true)) {
String userAgent = new StringBuilder("Para client ").append(Para.getVersion()).append(" ").append(accessKey).
append(" (Java ").append(System.getProperty("java.runtime.version")).append(")").toString();
builder.header(HttpHeaders.USER_AGENT, userAgent);
}
if (jsonPayload != null) {
return builder.method(httpMethod, jsonPayload);
} else {
return builder.method(httpMethod);
}
}