org.apache.http.HttpHeaders源码实例Demo

org.apache.http.impl.client.AbstractResponseHandler#org.apache.http.HttpHeaders源码实例Demo

下面列出了org.apache.http.impl.client.AbstractResponseHandler#org.apache.http.HttpHeaders 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test(groups = {"Integration","Broken"})
public void testInteractionOfSecurityFilterAndFormMapProvider() throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        Server server = useServerForTest(baseLauncher()
                .forceUseOfDefaultCatalogWithJavaClassPath(true)
                .withoutJsgui()
                .start());
        String appId = startAppAtNode(server);
        String entityId = getTestEntityInApp(server, appId);
        HttpClient client = HttpTool.httpClientBuilder()
                .uri(getBaseUriRest())
                .build();
        List<? extends NameValuePair> nvps = Lists.newArrayList(
                new BasicNameValuePair("arg", "bar"));
        String effector = String.format("/applications/%s/entities/%s/effectors/identityEffector", appId, entityId);
        HttpToolResponse response = HttpTool.httpPost(client, URI.create(getBaseUriRest() + effector),
                ImmutableMap.of(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType()),
                URLEncodedUtils.format(nvps, Charsets.UTF_8).getBytes());

        LOG.info("Effector response: {}", response.getContentAsString());
        assertTrue(HttpTool.isStatusCodeHealthy(response.getResponseCode()), "response code=" + response.getResponseCode());
    } finally {
        LOG.info("testInteractionOfSecurityFilterAndFormMapProvider complete in " + Time.makeTimeStringRounded(stopwatch));
    }
}
 
@Test
public void createEntryRoomInlineFeedWithInvalidProperty() throws Exception {
  String content = "{\"d\":{\"__metadata\":{\"id\":\"" + getEndpoint() + "Buildings('2')\","
      + "\"uri\":\"" + getEndpoint() + "Buildings('2')\",\"type\":\"RefScenario.Building\"},"
      + "\"Id\":\"2\",\"Name\":\"Building 2\",\"Image\":null,"
      + "\"nb_Rooms\":{\"results\":[{\"__metadata\":{\"id\":\"" + getEndpoint() + "Rooms('2')\","
      + "\"uri\":\"" + getEndpoint() + "Rooms('2')\",\"type\":\"RefScenario.Room\","
      + "\"etag\":\"W/\\\"2\\\"\"},"
      + "\"Id\":\"2\",\"Name\":\"Room 2\",\"Seats\":5,\"Version\":2,"
      + "\"nr_Employees\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('2')/nr_Employees\"}},"
      + "\"nr_Building\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('2')/nr_Building\"}}},"
      + "{\"__metadata\":{\"id\":\"" + getEndpoint() + "Rooms('3')\","
      + "\"uri\":\"" + getEndpoint() + "Rooms('3')\",\"type\":\"RefScenario.Room\","
      + "\"etag\":\"W/\\\"3\\\"\"},"
      + "\"Id\":\"3\",\"Name\":\"Room 3\",\"Seats\":2,\"Version\":3,\"Id\":\"2\""
      + "\"nr_Employees\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('3')/nr_Employees\"}},"
      + "\"nr_Building\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('3')/nr_Building\"}}}]}}}";

  postUri("Buildings", content, HttpContentType.APPLICATION_JSON, HttpHeaders.ACCEPT, HttpContentType.APPLICATION_JSON, HttpStatusCodes.BAD_REQUEST);
}
 
源代码3 项目: io   文件: MoveFileTest.java
/**
 * FileのMOVEでDestinationヘッダに存在しないBoxのURLを指定した場合に400エラーとなること.
 */
@Test
public final void FileのMOVEでDestinationヘッダに存在しないBoxのURLを指定した場合に400エラーとなること() {
    final String destination = UrlUtils.boxRoot(CELL_NAME, "dummyTestBoxForMove");
    try {
        // 事前準備
        DavResourceUtils.createWebDavFile(TOKEN, CELL_NAME,
                BOX_NAME + "/" + FILE_NAME, FILE_BODY, MediaType.TEXT_PLAIN, HttpStatus.SC_CREATED);

        // Fileの移動
        String url = UrlUtils.box(CELL_NAME, BOX_NAME, FILE_NAME);
        DcRequest req = DcRequest.move(url);
        req.header(HttpHeaders.AUTHORIZATION, AbstractCase.BEARER_MASTER_TOKEN);
        req.header(HttpHeaders.DESTINATION, destination);

        // リクエスト実行
        DcResponse response = AbstractCase.request(req);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
        DcCoreException expectedException = DcCoreException.Dav.INVALID_REQUEST_HEADER.params(
                HttpHeaders.DESTINATION, destination);
        ODataCommon.checkErrorResponseBody(response, expectedException.getCode(), expectedException.getMessage());

    } finally {
        DavResourceUtils.deleteWebDavFile(CELL_NAME, TOKEN, BOX_NAME, FILE_NAME);
    }
}
 
源代码4 项目: io   文件: BarInstallTest.java
/**
 * rootprops_xmlで定義済みのODataCol用contentsがない場合に異常終了する.
 */
@Test
public final void rootprops_xmlで定義済みのODataCol用contentsがない場合に異常終了する() {
    String reqCell = Setup.TEST_CELL1;
    String reqPath = INSTALL_TARGET;

    try {
        TResponse res = null;
        File barFile = new File(RESOURCE_PATH + BAR_FILE_ODATA_SPEC_NOTEXIST);
        byte[] body = BarInstallTestUtils.readBarFile(barFile);
        Map<String, String> headers = new LinkedHashMap<String, String>();
        headers.put(HttpHeaders.CONTENT_TYPE, REQ_CONTENT_TYPE);
        headers.put(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length));

        res = BarInstallTestUtils.request(REQUEST_NORM_FILE, reqCell, reqPath, headers, body);
        res.statusCode(HttpStatus.SC_ACCEPTED);
        String location = res.getHeader(HttpHeaders.LOCATION);
        String expected = UrlUtils.cellRoot(reqCell) + reqPath;
        assertEquals(expected, location);

        BarInstallTestUtils.assertBarInstallStatus(location, SCHEMA_URL, ProgressInfo.STATUS.FAILED);
    } finally {
        BarInstallTestUtils.deleteCollection("odatacol1");
    }
}
 
源代码5 项目: io   文件: BarInstallTest.java
/**
 * relation_jsonの必須項目がない場合に異常終了すること.
 */
@Test
public final void relation_jsonの必須項目がない場合に異常終了すること() {
    String reqCell = Setup.TEST_CELL1;
    String reqPath = INSTALL_TARGET;

    TResponse res = null;
    File barFile = new File(RESOURCE_PATH + BAR_FILE_RELATION_NONAME);
    byte[] body = BarInstallTestUtils.readBarFile(barFile);
    Map<String, String> headers = new LinkedHashMap<String, String>();
    headers.put(HttpHeaders.CONTENT_TYPE, REQ_CONTENT_TYPE);
    headers.put(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length));

    res = BarInstallTestUtils.request(REQUEST_NORM_FILE, reqCell, reqPath, headers, body);

    res.statusCode(HttpStatus.SC_ACCEPTED);
    String location = res.getHeader(HttpHeaders.LOCATION);
    String expected = UrlUtils.cellRoot(reqCell) + reqPath;
    assertEquals(expected, location);

    BarInstallTestUtils.assertBarInstallStatus(location, SCHEMA_URL, ProgressInfo.STATUS.FAILED);
}
 
源代码6 项目: FishingBot   文件: RealmsAPI.java
public String getServerIP(long serverId) {
    HttpUriRequest request = RequestBuilder.get()
            .setUri(REALMS_ENDPOINT + "/worlds/v1/" + serverId + "/join/pc")
            .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
            .build();

    try {
        HttpResponse answer = client.execute(request);
        if (answer.getStatusLine().getStatusCode() != 200) {
            FishingBot.getLog().severe("Could not retrieve IP from " + REALMS_ENDPOINT + ": " + answer.getStatusLine());
            return null;
        }
        JsonObject responseJson = (JsonObject) new JsonParser().parse(EntityUtils.toString(answer.getEntity(), Charsets.UTF_8));
        FishingBot.getLog().info("Connecting to: " + responseJson.toString());
        return responseJson.get("address").getAsString();
    } catch (IOException e) {
        FishingBot.getLog().severe("Could not connect to " + REALMS_ENDPOINT);
    }
    return null;
}
 
源代码7 项目: devops-cm-client   文件: CMODataAbapClient.java
public Transport createTransport(Map<String, Object> transport) throws IOException, URISyntaxException, ODataException, UnexpectedHttpResponseException
{
  try (CloseableHttpClient client = clientFactory.createClient()) {
    HttpPost post = requestBuilder.createTransport();
    post.setHeader("x-csrf-token", getCSRFToken());
    EdmEntityContainer entityContainer = getEntityDataModel().getDefaultEntityContainer();
    EdmEntitySet entitySet = entityContainer.getEntitySet(TransportRequestBuilder.getEntityKey());
    URI rootUri = new URI(endpoint.toASCIIString() + "/");
    EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(rootUri).build();
    ODataResponse marshaller = null;

    try {
      marshaller = EntityProvider.writeEntry(post.getHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue(), entitySet, transport, properties);
      post.setEntity(EntityBuilder.create().setStream(marshaller.getEntityAsStream()).build());

      try(CloseableHttpResponse httpResponse = client.execute(post)) {
        hasStatusOrFail(httpResponse, SC_CREATED);
        return getTransport(httpResponse);
      }
    } finally {
        if(marshaller != null) marshaller.close();
    }
  }
}
 
源代码8 项目: flowable-engine   文件: BaseSpringRestTestCase.java
protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode, boolean addJsonContentType) {
    try {
        if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
            // Revert to default content-type
            request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
        }
        CloseableHttpResponse response = client.execute(request);
        assertThat(response.getStatusLine()).isNotNull();

        int responseStatusCode = response.getStatusLine().getStatusCode();
        if (expectedStatusCode != responseStatusCode) {
            LOGGER.info("Wrong status code : {}, but should be {}", responseStatusCode, expectedStatusCode);
            if (response.getEntity() != null) {
                LOGGER.info("Response body: {}", IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
            }
        }

        assertThat(responseStatusCode).isEqualTo(expectedStatusCode);
        httpResponses.add(response);
        return response;

    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
源代码9 项目: io   文件: MoveFileTest.java
/**
 * FileのMOVEでDestinationヘッダに存在しないCellのURLを指定した場合に400エラーとなること.
 */
@Test
public final void FileのMOVEでDestinationヘッダに存在しないCellのURLを指定した場合に400エラーとなること() {
    final String destination = UrlUtils.cellRoot("dummyTestCellForMove");
    try {
        // 事前準備
        DavResourceUtils.createWebDavFile(TOKEN, CELL_NAME,
                BOX_NAME + "/" + FILE_NAME, FILE_BODY, MediaType.TEXT_PLAIN, HttpStatus.SC_CREATED);

        // Fileの移動
        String url = UrlUtils.box(CELL_NAME, BOX_NAME, FILE_NAME);
        DcRequest req = DcRequest.move(url);
        req.header(HttpHeaders.AUTHORIZATION, AbstractCase.BEARER_MASTER_TOKEN);
        req.header(HttpHeaders.DESTINATION, destination);

        // リクエスト実行
        DcResponse response = AbstractCase.request(req);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
        DcCoreException expectedException = DcCoreException.Dav.INVALID_REQUEST_HEADER.params(
                HttpHeaders.DESTINATION, destination);
        ODataCommon.checkErrorResponseBody(response, expectedException.getCode(), expectedException.getMessage());

    } finally {
        DavResourceUtils.deleteWebDavFile(CELL_NAME, TOKEN, BOX_NAME, FILE_NAME);
    }
}
 
源代码10 项目: hbase   文件: TestThriftSpnegoHttpFallbackServer.java
@Override
protected void talkToThriftServer(String url, int customHeaderSize) throws Exception {
  // Close httpClient and THttpClient automatically on any failures
  try (
    CloseableHttpClient httpClient = createHttpClient();
    THttpClient tHttpClient = new THttpClient(url, httpClient)
  ) {
    tHttpClient.open();
    if (customHeaderSize > 0) {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < customHeaderSize; i++) {
        sb.append("a");
      }
      tHttpClient.setCustomHeader(HttpHeaders.USER_AGENT, sb.toString());
    }

    TProtocol prot = new TBinaryProtocol(tHttpClient);
    Hbase.Client client = new Hbase.Client(prot);
    TestThriftServer.createTestTables(client);
    TestThriftServer.checkTableList(client);
    TestThriftServer.dropTestTables(client);
  }
}
 
源代码11 项目: io   文件: UpdateTest.java
/**
 * Cellの更新の$formatがjson, atom以外のテスト.
 */
@SuppressWarnings("unchecked")
@Test
public final void Cellの更新の$formatがjsonとatom以外のテスト() {

    // Cellを更新
    // リクエストヘッダをセット
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
    headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    headers.put(HttpHeaders.IF_MATCH, "*");

    // リクエストボディを生成
    JSONObject requestBody = new JSONObject();
    requestBody.put("Name", cellName);

    res = updateCellQuery(headers, requestBody, "$format=test");

    // Cell更新のレスポンスチェック
    // TODO $formatのチェックが実装されたら変更する必要がある
    assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode());
}
 
源代码12 项目: io   文件: BarInstallTest.java
/**
 * ODataCol用の00_metadata_xmlと10_odatarelations_jsonの順序が不正の場合に異常終了する.
 */
@Test
public final void ODataCol用の00_metadata_xmlと10_odatarelations_jsonの順序が不正の場合に異常終了する() {
    String reqCell = Setup.TEST_CELL1;
    String reqPath = INSTALL_TARGET;

    try {
        TResponse res = null;
        File barFile = new File(RESOURCE_PATH + BAR_FILE_INVALID_CONT_ORDER);
        byte[] body = BarInstallTestUtils.readBarFile(barFile);
        Map<String, String> headers = new LinkedHashMap<String, String>();
        headers.put(HttpHeaders.CONTENT_TYPE, REQ_CONTENT_TYPE);
        headers.put(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length));

        res = BarInstallTestUtils.request(REQUEST_NORM_FILE, reqCell, reqPath, headers, body);
        res.statusCode(HttpStatus.SC_ACCEPTED);
        String location = res.getHeader(HttpHeaders.LOCATION);
        String expected = UrlUtils.cellRoot(reqCell) + reqPath;
        assertEquals(expected, location);

        BarInstallTestUtils.assertBarInstallStatus(location, SCHEMA_URL, ProgressInfo.STATUS.FAILED);
    } finally {
        BarInstallTestUtils.deleteCollection("odatacol1");
    }
}
 
源代码13 项目: io   文件: ReadTest.java
/**
 * Acceptに空文字を指定してCell取得した場合にjsonフォーマットでレスポンスが返却されること. $format → json Accept → 空文字
 */
@Test
public final void $formatがjsonでacceptが空文字でCell取得した場合にjsonフォーマットでレスポンスが返却されること() {
    String url = getUrl(this.cellId);
    // $format json
    // Acceptヘッダ 空文字
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
    headers.put(HttpHeaders.ACCEPT, "");
    this.setHeaders(headers);

    DcResponse res = restGet(url + "?" + QUERY_FORMAT_JSON);
    // TODO Acceptヘッダーのチェック処理が完了したら、NOT_ACCEPTABLEのチェックに変更する
    assertEquals(HttpStatus.SC_OK, res.getStatusCode());
    this.checkHeaders(res);
    // Etagのチェック
    assertEquals(1, res.getResponseHeaders(HttpHeaders.ETAG).length);
    // レスポンスボディのパース
    this.checkCellResponse(res.bodyAsJson(), url);
}
 
源代码14 项目: io   文件: CellUtils.java
/**
 * __event/{boxName}のPOSTを行うユーティリティ.
 * @param authorization Authorizationヘッダの値(auth-shemaを含む文字列)
 * @param cellName セル名
 * @param boxName ボックス名
 * @param level ログ出力レベル
 * @param action イベントのアクション
 * @param object イベントの対象オブジェクト
 * @param result イベントの結果
 * @return レスポンス
 * @throws DcException リクエスト失敗
 */
@SuppressWarnings("unchecked")
public static DcResponse eventUnderBox(String authorization,
        String cellName,
        String boxName,
        String level,
        String action,
        String object,
        String result) throws DcException {
    JSONObject body = new JSONObject();
    body.put("level", level);
    body.put("action", action);
    body.put("object", object);
    body.put("result", result);

    DcRestAdapter adaper = new DcRestAdapter();
    HashMap<String, String> header = new HashMap<String, String>();
    header.put(HttpHeaders.AUTHORIZATION, authorization);
    return adaper.post(UrlUtils.cellRoot(cellName) + "__event/" + boxName,
            body.toJSONString(), header);
}
 
源代码15 项目: io   文件: ComplexTypeCreateTest.java
/**
 * ComplexTypeのName属性がない場合_BadRequestが返却されること.
 */
@Test
public final void ComplexTypeのName属性がない場合_BadRequestが返却されること() {
    // リクエストパラメータ設定
    DcRequest req = DcRequest.post(REQUEST_URL);
    req.header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
    req.addStringBody("{}");

    // リクエスト実行
    DcResponse response = request(req);

    // レスポンスチェック
    assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode());
    checkErrorResponse(response.bodyAsJson(),
            DcCoreException.OData.INPUT_REQUIRED_FIELD_MISSING.getCode(),
            DcCoreException.OData.INPUT_REQUIRED_FIELD_MISSING.params(COMPLEX_TYPE_NAME_KEY).getMessage());
}
 
源代码16 项目: io   文件: ImplicitFlowTest.java
/**
 * パスワード認証で不正なパスワードを指定して自分セルトークンを取得し認証フォームにエラーメッセージが出力されること.
 */
@Test
public final void パスワード認証で不正なパスワードを指定して自分セルトークンを取得し認証フォームにエラーメッセージが出力されること() {

    // 認証前のアカウントの最終ログイン時刻を取得しておく
    Long lastAuthenticatedTime = AuthTestCommon.getAccountLastAuthenticated(Setup.TEST_CELL1, "account2");

    String addbody = "&username=account2&password=dummypassword";

    DcResponse res = requesttoAuthz(addbody);

    assertEquals(HttpStatus.SC_OK, res.getStatusCode());
    // アカウントの最終ログイン時刻が更新されていないことの確認
    AuthTestCommon.accountLastAuthenticatedNotUpdatedCheck(Setup.TEST_CELL1, "account2", lastAuthenticatedTime);

    // レスポンスヘッダのチェック
    assertEquals(MediaType.TEXT_HTML + ";charset=UTF-8", res.getFirstHeader(HttpHeaders.CONTENT_TYPE));

    // レスポンスボディのチェック
    checkHtmlBody(res, "PS-AU-0004", Setup.TEST_CELL1);
    AuthTestCommon.waitForAccountLock();
}
 
源代码17 项目: armeria   文件: FileServiceTest.java
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testClassPathGet(String baseUri) throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final String lastModified;
        final String etag;
        try (CloseableHttpResponse res = hc.execute(new HttpGet(baseUri + "/foo.txt"))) {
            assert200Ok(res, "text/plain", "foo");
            lastModified = header(res, HttpHeaders.LAST_MODIFIED);
            etag = header(res, HttpHeaders.ETAG);
        }

        assert304NotModified(hc, baseUri, "/foo.txt", etag, lastModified);

        // Confirm file service paths are cached when cache is enabled.
        if (baseUri.contains("/cached")) {
            assertThat(PathAndQuery.cachedPaths()).contains("/cached/foo.txt");
        }
    }
}
 
源代码18 项目: io   文件: ImplicitFlowTest.java
/**
 * トークン認証でredirect_uriの指定が無い場合302が返却されること.
 */
@Test
public final void トークン認証でredirect_uriの指定が無い場合302が返却されること() {

    String transCellAccessToken = getTcToken();

    // トークン認証
    String addbody = "&assertion=" + transCellAccessToken;
    String clientId = UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1);
    String body = "response_type=token&client_id=" + clientId
            + "&state=" + DEFAULT_STATE + addbody;
    DcResponse res = requesttoAuthzWithBody(Setup.TEST_CELL2, body);

    assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, res.getStatusCode());

    assertEquals(UrlUtils.cellRoot(Setup.TEST_CELL2) + "__html/error?code=PR400-AZ-0003",
            res.getFirstHeader(HttpHeaders.LOCATION));
}
 
源代码19 项目: cloud-odata-java   文件: RequestContentTypeTest.java
@Test
public void wildcardContentType() throws Exception {
  HttpPost post = new HttpPost(URI.create(getEndpoint().toString() + "Rooms"));
  post.setHeader(HttpHeaders.CONTENT_TYPE, HttpContentType.WILDCARD);
  final HttpResponse response = getHttpClient().execute(post);
  assertEquals(HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE.getStatusCode(), response.getStatusLine().getStatusCode());
}
 
@Test
public void testInvalidArchive() throws Exception {
    File f = Os.newTempFile("osgi", "zip");

    Response response = client().path("/catalog/bundles")
            .header(HttpHeaders.CONTENT_TYPE, "application/x-zip")
            .post(Streams.readFully(new FileInputStream(f)));

    assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
    Asserts.assertStringContainsIgnoreCase(response.readEntity(String.class), "zip file is empty");
}
 
/**
 * PropertyのTypeがEdmDateTimeでDefaultValueがSYSUTCDATETIMEの場合正常に作成されること.
 */
@Test
public final void PropertyのTypeがEdmDateTimeでDefaultValueがSYSUTCDATETIMEの場合正常に作成されること() {
    String locationUrl = UrlUtils.property(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, propName,
            PROPERTY_ENTITYTYPE_NAME);
    try {
        // リクエストパラメータ設定
        DcRequest req = DcRequest.post(PropertyUtils.REQUEST_URL);
        req.header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
        req.addJsonBody(PropertyUtils.PROPERTY_NAME_KEY, propName);
        req.addJsonBody(PropertyUtils.PROPERTY_ENTITYTYPE_NAME_KEY, PROPERTY_ENTITYTYPE_NAME);
        req.addJsonBody(PropertyUtils.PROPERTY_TYPE_KEY, EdmSimpleType.DATETIME.getFullyQualifiedTypeName());
        req.addJsonBody(PropertyUtils.PROPERTY_NULLABLE_KEY, null);
        req.addJsonBody(PropertyUtils.PROPERTY_DEFAULT_VALUE_KEY, "SYSUTCDATETIME()");
        req.addJsonBody(PropertyUtils.PROPERTY_COLLECTION_KIND_KEY, null);
        req.addJsonBody(PropertyUtils.PROPERTY_IS_KEY_KEY, null);
        req.addJsonBody(PropertyUtils.PROPERTY_UNIQUE_KEY_KEY, null);

        // リクエスト実行
        DcResponse response = request(req);

        // レスポンスチェック
        Map<String, Object> expected = new HashMap<String, Object>();
        expected.put(PropertyUtils.PROPERTY_NAME_KEY, propName);
        expected.put(PropertyUtils.PROPERTY_ENTITYTYPE_NAME_KEY, PROPERTY_ENTITYTYPE_NAME);
        expected.put(PropertyUtils.PROPERTY_TYPE_KEY, EdmSimpleType.DATETIME.getFullyQualifiedTypeName());
        expected.put(PropertyUtils.PROPERTY_NULLABLE_KEY, true);
        expected.put(PropertyUtils.PROPERTY_DEFAULT_VALUE_KEY, "SYSUTCDATETIME()");
        expected.put(PropertyUtils.PROPERTY_COLLECTION_KIND_KEY, Property.COLLECTION_KIND_NONE);
        expected.put(PropertyUtils.PROPERTY_IS_KEY_KEY, false);
        expected.put(PropertyUtils.PROPERTY_UNIQUE_KEY_KEY, null);
        assertEquals(HttpStatus.SC_CREATED, response.getStatusCode());
        checkResponseBody(response.bodyAsJson(), locationUrl, PropertyUtils.NAMESPACE, expected);
    } finally {
        // 作成したPropertyを削除
        assertEquals(HttpStatus.SC_NO_CONTENT, deleteOdataResource(locationUrl).getStatusCode());
    }
}
 
源代码22 项目: cloud-odata-java   文件: RequestContentTypeTest.java
@Test
public void validTextPlainContentType() throws Exception {
  HttpPut put = new HttpPut(URI.create(getEndpoint().toString() + "Rooms('1')/Seats/$value"));
  put.setHeader(HttpHeaders.CONTENT_TYPE, HttpContentType.TEXT_PLAIN);
  final HttpResponse response = getHttpClient().execute(put);
  // We expect an internal server error due to the incomplete processor implementation.
  assertEquals(HttpStatusCodes.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusLine().getStatusCode());
}
 
源代码23 项目: tutorials   文件: HttpClientAuthLiveTest.java
@Test
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException {
    final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
    final String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
    final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
    final String authHeader = "Basic " + new String(encodedAuth);
    request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

    client = HttpClientBuilder.create().build();
    response = client.execute(request);

    final int statusCode = response.getStatusLine().getStatusCode();
    assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
 
源代码24 项目: cloud-odata-java   文件: ContentNegotiationTest.java
@Test
public void browserIssue95() throws Exception {
  final HttpResponse response = callUri("Employees",
      HttpHeaders.ACCEPT, "application/atomsvc+xml;q=0.9, application/json;q=0.8, */*;q=0.1",
      HttpStatusCodes.OK);
  checkMediaType(response, HttpContentType.APPLICATION_JSON);
}
 
源代码25 项目: io   文件: MoveCollectionTest.java
/**
 * ServiceコレクションのMOVEで存在するServiceソースファイルに上書きモードで移動した場合に400エラーとなること.
 */
@Test
public final void ServiceコレクションのMOVEで存在するServiceソースファイルに上書きモードで移動した場合に400エラーとなること() {
    final String srcColName = "srcCol";
    final String srcUrl = UrlUtils.box(CELL_NAME, BOX_NAME, srcColName);
    final String destColName = "destCol";
    final String destUrl = UrlUtils.box(CELL_NAME, BOX_NAME, destColName, FILE_NAME);
    try {
        // 事前準備
        DavResourceUtils.createServiceCollection(AbstractCase.BEARER_MASTER_TOKEN, HttpStatus.SC_CREATED,
                CELL_NAME, BOX_NAME, srcColName);
        DavResourceUtils.createServiceCollection(AbstractCase.BEARER_MASTER_TOKEN, HttpStatus.SC_CREATED,
                CELL_NAME, BOX_NAME, destColName);
        DavResourceUtils.createWebDavFile(TOKEN, CELL_NAME,
                BOX_NAME + "/" + destColName + "/__src/" + FILE_NAME, FILE_BODY, MediaType.TEXT_PLAIN,
                HttpStatus.SC_CREATED);

        // 移動
        DcRequest req = DcRequest.move(srcUrl);
        req.header(HttpHeaders.AUTHORIZATION, AbstractCase.BEARER_MASTER_TOKEN);
        req.header(HttpHeaders.DESTINATION, destUrl);
        req.header(HttpHeaders.OVERWRITE, "T");
        DcResponse response = AbstractCase.request(req);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
        // TODO Serviceコレクション配下への移動の制限追加時にエラーコードのチェックをする
        // DcCoreException expectedException = DcCoreException.Dav.RESOURCE_PROHIBITED_TO_OVERWRITE;
        // ODataCommon.checkErrorResponseBody(response, expectedException.getCode(),
        // expectedException.getMessage());
    } finally {
        DavResourceUtils.deleteCollection(CELL_NAME, BOX_NAME, srcColName, TOKEN, -1);
        DavResourceUtils.deleteWebDavFile(CELL_NAME, TOKEN, BOX_NAME, destColName + "/__src/" + FILE_NAME);
        DavResourceUtils.deleteCollection(CELL_NAME, BOX_NAME, destColName, TOKEN, -1);
    }
}
 
源代码26 项目: io   文件: MoveServiceSourceTest.java
/**
 * ServiceSourceのMOVEで移動先の1階層目の親リソースが存在しない場合409エラーとなること.
 */
@Test
public final void ServiceSourceのMOVEで移動先の1階層目の親リソースが存在しない場合409エラーとなること() {
    final String colName = "serviceColforMOVE";
    final String invalidColName = "invalidCol";
    final String destination = UrlUtils.box(CELL_NAME, BOX_NAME, invalidColName, FILE_NAME);
    try {
        // 事前準備
        DavResourceUtils.createServiceCollection(AbstractCase.BEARER_MASTER_TOKEN, HttpStatus.SC_CREATED,
                CELL_NAME, BOX_NAME, colName);
        DavResourceUtils.createWebDavFile(TOKEN, CELL_NAME,
                BOX_NAME + "/" + colName + "/__src/" + FILE_NAME, FILE_BODY, MediaType.TEXT_PLAIN,
                HttpStatus.SC_CREATED);

        // Fileの移動
        String url = UrlUtils.box(CELL_NAME, BOX_NAME, colName + "/__src/" + FILE_NAME);
        DcRequest req = DcRequest.move(url);
        req.header(HttpHeaders.AUTHORIZATION, AbstractCase.BEARER_MASTER_TOKEN);
        req.header(HttpHeaders.DESTINATION, destination);
        req.header(HttpHeaders.OVERWRITE, "T");

        // リクエスト実行
        DcResponse response = AbstractCase.request(req);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_CONFLICT);
        DcCoreException expectedException = DcCoreException.Dav.HAS_NOT_PARENT.params(invalidColName);
        ODataCommon.checkErrorResponseBody(response, expectedException.getCode(), expectedException.getMessage());
    } finally {
        DavResourceUtils.deleteWebDavFile(CELL_NAME, TOKEN, BOX_NAME, colName + "/__src/" + FILE_NAME);
        DavResourceUtils.deleteCollection(CELL_NAME, BOX_NAME, colName, TOKEN, -1);
    }
}
 
源代码27 项目: io   文件: PropertyCreateValidateTest.java
/**
 * PropertyのIsKeyがfalseの場合_正常に作成できること.
 */
@Test
public final void PropertyのIsKeyがfalseの場合_正常に作成できること() {
    String locationUrl =
            UrlUtils.property(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, propName,
                    PROPERTY_ENTITYTYPE_NAME);
    try {
        // リクエストパラメータ設定
        DcRequest req = DcRequest.post(PropertyUtils.REQUEST_URL);
        req.header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
        req.addJsonBody(PropertyUtils.PROPERTY_NAME_KEY, propName);
        req.addJsonBody(PropertyUtils.PROPERTY_ENTITYTYPE_NAME_KEY, PROPERTY_ENTITYTYPE_NAME);
        req.addJsonBody(PropertyUtils.PROPERTY_TYPE_KEY, EdmSimpleType.STRING.getFullyQualifiedTypeName());
        req.addJsonBody(PropertyUtils.PROPERTY_NULLABLE_KEY, null);
        req.addJsonBody(PropertyUtils.PROPERTY_DEFAULT_VALUE_KEY, null);
        req.addJsonBody(PropertyUtils.PROPERTY_COLLECTION_KIND_KEY, null);
        req.addJsonBody(PropertyUtils.PROPERTY_IS_KEY_KEY, false);
        req.addJsonBody(PropertyUtils.PROPERTY_UNIQUE_KEY_KEY, null);

        // リクエスト実行
        DcResponse response = request(req);

        // レスポンスチェック
        Map<String, Object> expected = new HashMap<String, Object>();
        expected.put(PropertyUtils.PROPERTY_NAME_KEY, propName);
        expected.put(PropertyUtils.PROPERTY_ENTITYTYPE_NAME_KEY, PROPERTY_ENTITYTYPE_NAME);
        expected.put(PropertyUtils.PROPERTY_TYPE_KEY, EdmSimpleType.STRING.getFullyQualifiedTypeName());
        expected.put(PropertyUtils.PROPERTY_NULLABLE_KEY, true);
        expected.put(PropertyUtils.PROPERTY_DEFAULT_VALUE_KEY, null);
        expected.put(PropertyUtils.PROPERTY_COLLECTION_KIND_KEY, Property.COLLECTION_KIND_NONE);
        expected.put(PropertyUtils.PROPERTY_IS_KEY_KEY, false);
        expected.put(PropertyUtils.PROPERTY_UNIQUE_KEY_KEY, null);
        assertEquals(HttpStatus.SC_CREATED, response.getStatusCode());
        checkResponseBody(response.bodyAsJson(), locationUrl, PropertyUtils.NAMESPACE, expected);
    } finally {
        // 作成したPropertyを削除
        assertEquals(HttpStatus.SC_NO_CONTENT, deleteOdataResource(locationUrl).getStatusCode());
    }
}
 
源代码28 项目: torrssen2   文件: TelegramService.java
public boolean sendMessage(String inToken, String chatId, String message) {
    boolean ret = false;

    baseUrl = "https://api.telegram.org/bot" + inToken + "/sendMessage";
    
    List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
    httpClient = HttpClientBuilder.create().setDefaultHeaders(headers).build();

    HttpPost httpPost = new HttpPost(baseUrl);
    CloseableHttpResponse response = null;

    log.debug("token:" + inToken);
    log.debug("chatId: " + chatId);

    try {
        JSONObject params = new JSONObject();
        params.put("chat_id", chatId);
        params.put("text", message);
        params.put("parse_mode", "HTML");
        httpPost.setEntity(new StringEntity(params.toString(), StandardCharsets.UTF_8));

        response = httpClient.execute(httpPost);

        log.debug("telegram-send-message-response-code: " + response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() == 200) {
            ret = true;
        } 
    } catch (IOException e) {
        log.error(e.getMessage());
    } finally {
        HttpClientUtils.closeQuietly(response);
    }

    return ret;
}
 
源代码29 项目: olingo-odata2   文件: RequestContentTypeTest.java
@Test
public void wildcardContentType() throws Exception {
  HttpPost post = new HttpPost(URI.create(getEndpoint().toString() + "Rooms"));
  post.setHeader(HttpHeaders.CONTENT_TYPE, HttpContentType.WILDCARD);
  final HttpResponse response = getHttpClient().execute(post);
  assertEquals(HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE.getStatusCode(), response.getStatusLine().getStatusCode());
}
 
源代码30 项目: io   文件: MoveCollectionTest.java
/**
 * WebDAVコレクションのMOVEで存在するWebDAVコレクションに上書きモードで移動した場合に400エラーとなること. <br/>
 * TODO コレクションの上書きを実装した場合は、正常終了(204)となる。
 */
@Test
public final void WebDAVコレクションのMOVEで存在するWebDAVコレクションに上書きモードで移動した場合に400エラーとなること() {
    final String srcColName = "srcCol";
    final String srcUrl = UrlUtils.box(CELL_NAME, BOX_NAME, srcColName);
    final String destColName = "destCol";
    final String destUrl = UrlUtils.box(CELL_NAME, BOX_NAME, destColName);
    try {
        // 事前準備
        DavResourceUtils.createWebDavCollection(TOKEN, HttpStatus.SC_CREATED, CELL_NAME, BOX_NAME, srcColName);
        DavResourceUtils.createWebDavCollection(TOKEN, HttpStatus.SC_CREATED, CELL_NAME, BOX_NAME, destColName);

        // 移動
        DcRequest req = DcRequest.move(srcUrl);
        req.header(HttpHeaders.AUTHORIZATION, AbstractCase.BEARER_MASTER_TOKEN);
        req.header(HttpHeaders.DESTINATION, destUrl);
        req.header(HttpHeaders.OVERWRITE, "T");
        DcResponse response = AbstractCase.request(req);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
        DcCoreException expectedException = DcCoreException.Dav.RESOURCE_PROHIBITED_TO_OVERWRITE;
        ODataCommon.checkErrorResponseBody(response, expectedException.getCode(), expectedException.getMessage());

        // 存在確認
        TResponse res = DavResourceUtils.propfind(TOKEN, CELL_NAME, BOX_NAME, "1", HttpStatus.SC_MULTI_STATUS);
        assertContainsHrefUrl(srcUrl, res);
        assertContainsHrefUrl(destUrl, res);
    } finally {
        DavResourceUtils.deleteCollection(CELL_NAME, BOX_NAME, srcColName, TOKEN, -1);
        DavResourceUtils.deleteCollection(CELL_NAME, BOX_NAME, destColName, TOKEN, -1);
    }
}