javax.ws.rs.client.Entity#json ( )源码实例Demo

下面列出了javax.ws.rs.client.Entity#json ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: powerbi-rest-java   文件: PowerBiRequestImpl.java
@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);
}
 
源代码2 项目: foxtrot   文件: AsyncResourceTest.java
@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);
}
 
源代码3 项目: TelegramBots   文件: TestRestApi.java
@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));
}
 
源代码4 项目: fernet-java8   文件: SecretInjectionIT.java
/**
 * 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);
}
 
源代码5 项目: cep   文件: RestRulesTest.java
@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);
}
 
源代码6 项目: TelegramBots   文件: TestRestApi.java
@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));
}
 
源代码7 项目: foxtrot   文件: DocumentResourceTest.java
@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());
}
 
源代码8 项目: agrest   文件: PUT_IT.java
@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();
}
 
源代码9 项目: TelegramBots   文件: TestRestApi.java
@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));
}
 
源代码10 项目: docker-java   文件: JerseyDockerHttpClient.java
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);
}
 
源代码12 项目: TelegramBots   文件: TestRestApi.java
@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));
}
 
源代码13 项目: TelegramBots   文件: TestRestApi.java
@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));
}
 
源代码14 项目: TelegramBots   文件: TestRestApi.java
@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));
}
 
源代码15 项目: TelegramBots   文件: TestRestApi.java
@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));
}
 
源代码16 项目: TelegramBots   文件: TestRestApi.java
@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));
}
 
源代码17 项目: FHIR   文件: BulkDataClient.java
/**
 * @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);
}
 
源代码18 项目: foxtrot   文件: AsyncResourceTest.java
@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());
}
 
源代码19 项目: foxtrot   文件: AnalyticsResourceTest.java
@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());
}
 
源代码20 项目: para   文件: Signer.java
/**
 * 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);
	}
}
 
 方法所在类
 同类方法