org.apache.http.HttpHeaders Java Examples

The following examples show how to use org.apache.http.HttpHeaders. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ImplicitFlowTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * トークン認証で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));
}
 
Example #2
Source File: TestThriftSpnegoHttpFallbackServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #3
Source File: RealmsAPI.java    From FishingBot with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: UpdateTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #5
Source File: BarInstallTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example #6
Source File: BarInstallTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #7
Source File: ReadTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #8
Source File: CellUtils.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * __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);
}
 
Example #9
Source File: ComplexTypeCreateTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #10
Source File: BarInstallTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example #11
Source File: MoveFileTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #12
Source File: ImplicitFlowTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * パスワード認証で不正なパスワードを指定して自分セルトークンを取得し認証フォームにエラーメッセージが出力されること.
 */
@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();
}
 
Example #13
Source File: BaseSpringRestTestCase.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #14
Source File: EntryJsonCreateInlineTest.java    From cloud-odata-java with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #15
Source File: BrooklynPropertiesSecurityFilterTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@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));
    }
}
 
Example #16
Source File: MoveFileTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #17
Source File: CMODataAbapClient.java    From devops-cm-client with Apache License 2.0 6 votes vote down vote up
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();
    }
  }
}
 
Example #18
Source File: FileServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@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");
        }
    }
}
 
Example #19
Source File: MoveFileHeaderValidateTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * FileのMOVEでDepthヘッダにinfinityを指定した場合に正常に移動できること.
 */
@Test
public final void FileのMOVEでDepthヘッダにinfinityを指定した場合に正常に移動できること() {
    final String depth = "infinity";
    final String destFileName = "destFile.txt";
    final String destination = UrlUtils.box(CELL_NAME, BOX_NAME, destFileName);
    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);
        req.header(HttpHeaders.DEPTH, depth);

        // リクエスト実行
        DcResponse response = AbstractCase.request(req);
        assertEquals(HttpStatus.SC_CREATED, response.getStatusCode());

        // 移動元のファイルが存在しないこと
        DavResourceUtils.getWebDav(CELL_NAME, TOKEN, BOX_NAME, FILE_NAME, HttpStatus.SC_NOT_FOUND);
        // 移動先のファイルが存在すること
        DavResourceUtils.getWebDav(CELL_NAME, TOKEN, BOX_NAME, destFileName, HttpStatus.SC_OK);
    } finally {
        DavResourceUtils.deleteWebDavFile(CELL_NAME, TOKEN, BOX_NAME, FILE_NAME);
        DavResourceUtils.deleteWebDavFile(CELL_NAME, TOKEN, BOX_NAME, destFileName);
    }
}
 
Example #20
Source File: EntryJsonCreateInlineTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void createEntryRoomWithInlineFeedEmployee() throws Exception {
  String content = "{\"d\":{\"__metadata\":{\"id\":\"" + getEndpoint() + "Rooms('1')\","
      + "\"uri\":\"" + getEndpoint() + "Rooms('1')\",\"type\":\"RefScenario.Room\","
      + "\"etag\":\"W/\\\"3\\\"\"},"
      + "\"Id\":\"1\",\"Name\":\"Room 104\",\"Seats\":4,\"Version\":2,"
      + "\"nr_Employees\":{\"results\":[{"
      + "\"__metadata\":{"
      + "\"id\":\"" + getEndpoint() + "Employees('1')\","
      + "\"type\":\"RefScenario.Employee\","
      + "\"content_type\":\"image/jpeg\","
      + "\"media_src\":\"" + getEndpoint() + "Employees('1')/$value\","
      + "\"edit_media\":\"" + getEndpoint() + "Employees('1')/$value\"},"
      + " \"EmployeeName\": \"Walter Winter\","
      + "\"ManagerId\": \"1\","
      + "\"RoomId\": \"1\","
      + "\"TeamId\": \"1\","
      + "\"Age\": 52,"
      + "\"Location\":{\"City\":{\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"},"
      + "              \"Country\":\"Germany\"},"
      + "\"ImageUrl\": \"" + getEndpoint() + "Employees('1')/$value\"}]},"
      + "\"nr_Building\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('1')/nr_Building\"}}}}";

  HttpResponse response =
      postUri("Rooms", content, HttpContentType.APPLICATION_JSON, HttpHeaders.ACCEPT,
          HttpContentType.APPLICATION_JSON, HttpStatusCodes.CREATED);
  checkMediaType(response, HttpContentType.APPLICATION_JSON);

  String body = getBody(response);
  LinkedTreeMap<?, ?> map = getLinkedTreeMap(body);
  assertEquals("104", map.get("Id"));
  assertEquals("Room 104", map.get("Name"));

  @SuppressWarnings("unchecked")
  LinkedTreeMap<String, String> metadataMap = (LinkedTreeMap<String, String>) map.get("__metadata");
  assertNotNull(metadataMap);
  assertEquals(getEndpoint() + "Rooms('104')", metadataMap.get("id"));
  assertEquals("RefScenario.Room", metadataMap.get("type"));
  assertEquals(getEndpoint() + "Rooms('104')", metadataMap.get("uri"));
}
 
Example #21
Source File: MessageApproveTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 関係登録で存在しないメッセージIDを指定した場合404エラーとなること.
 */
@Test
public final void 関係登録で存在しないメッセージIDを指定した場合404エラーとなること() {

    try {
        // 存在しない__idを設定
        String messageId = "dummyMessageId";

        // メッセージ承認にする
        DcRestAdapter rest = new DcRestAdapter();

        // リクエストヘッダをセット
        HashMap<String, String> requestheaders = new HashMap<String, String>();
        requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);

        // approved
        String requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId);
        DcResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }",
                requestheaders);
        assertEquals(HttpStatus.SC_NOT_FOUND, res.getStatusCode());
        checkErrorResponse(res.bodyAsJson(), DcCoreException.OData.NO_SUCH_ENTITY.getCode());

        // rejected
        requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId);
        res = rest.post(requestUrl, "{\"Command\":\"rejected\" }",
                requestheaders);
        assertEquals(HttpStatus.SC_NOT_FOUND, res.getStatusCode());
        checkErrorResponse(res.bodyAsJson(), DcCoreException.OData.NO_SUCH_ENTITY.getCode());

    } catch (DcException e) {
        e.printStackTrace();
    }
}
 
Example #22
Source File: ODataCommon.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * リクエストボディに管理情報である場合のパターンのテスト.
 * @param req DcRequestオブジェクト
 * @param keyName 管理キー名
 */
public void cellErrorBodyDateCtl(DcRequest req, String keyName) {
    // Cellを作成
    String[] key = {"Name", keyName };
    String[] value = {"testCell", "/Date(0)/" };
    req.header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN).addJsonBody(key, value);
    this.res = request(req);

    // Cell作成のレスポンスチェック
    // 400になることを確認
    assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode());

}
 
Example #23
Source File: RequestContentTypeTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #24
Source File: MoveFileHeaderValidateTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * FileのMOVEでDepthヘッダにinfinity以外の文字列を指定した場合に400エラーとなること.
 */
@Test
public final void FileのMOVEでDepthヘッダにinfinity以外の文字列を指定した場合に400エラーとなること() {
    final String depth = "1";
    final String destFileName = "destFile.txt";
    final String destination = UrlUtils.box(CELL_NAME, BOX_NAME, destFileName);
    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);
        req.header(HttpHeaders.DEPTH, depth);

        // リクエスト実行
        DcResponse response = AbstractCase.request(req);
        assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode());
        DcCoreException expectedException = DcCoreException.Dav.INVALID_DEPTH_HEADER.params(depth);
        ODataCommon.checkErrorResponseBody(response, expectedException.getCode(), expectedException.getMessage());

        // 移動元のファイルが存在すること
        DavResourceUtils.getWebDav(CELL_NAME, TOKEN, BOX_NAME, FILE_NAME, HttpStatus.SC_OK);
        // 移動先のファイルが存在しないこと
        DavResourceUtils.getWebDav(CELL_NAME, TOKEN, BOX_NAME, destFileName, HttpStatus.SC_NOT_FOUND);
    } finally {
        DavResourceUtils.deleteWebDavFile(CELL_NAME, TOKEN, BOX_NAME, FILE_NAME);
        DavResourceUtils.deleteWebDavFile(CELL_NAME, TOKEN, BOX_NAME, destFileName);
    }
}
 
Example #25
Source File: MoveCollectionTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * ServiceコレクションのMOVEで存在するWebDAVコレクションに上書き禁止モードで移動した場合に412エラーとなること.
 */
@Test
public final void ServiceコレクションのMOVEで存在するWebDAVコレクションに上書き禁止モードで移動した場合に412エラーとなること() {
    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.createServiceCollection(AbstractCase.BEARER_MASTER_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, "F");
        DcResponse response = AbstractCase.request(req);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_PRECONDITION_FAILED);
        DcCoreException expectedException = DcCoreException.Dav.DESTINATION_ALREADY_EXISTS;
        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);
    }
}
 
Example #26
Source File: ElasticRestClient.java    From embedded-elasticsearch with Apache License 2.0 5 votes vote down vote up
private void performBulkRequest(String requestUrl, String bulkRequestBody) {
    HttpPost request = new HttpPost(requestUrl);
    request.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
    request.setEntity(new StringEntity(bulkRequestBody, UTF_8));
    httpClient.execute(request, (Consumer<CloseableHttpResponse>) response -> assertOk(response, "Request finished with error"));
    refresh();
}
 
Example #27
Source File: HttpClientHeadersLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenConfigOnRequest_whenRequestHasCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException {
    client = HttpClients.custom().build();
    final HttpGet request = new HttpGet(SAMPLE_URL);
    request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Firefox/26.0");
    response = client.execute(request);
}
 
Example #28
Source File: UpdateTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * Cell更新の正常リクエストで204が返却されること.
 */
@SuppressWarnings("unchecked")
@Test
public final void Cell更新の正常リクエストで204が返却されること() {
    // リクエストヘッダを設定する
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
    headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    headers.put(HttpHeaders.IF_MATCH, eTag);

    // リクエストボディを設定する
    JSONObject requestBody = new JSONObject();
    String updateCellName = "cellname" + Long.toString(Calendar.getInstance().getTimeInMillis());
    requestBody.put("Name", updateCellName);

    // リクエストを実行する
    res = updateCell(headers, requestBody);
    cellNameToDelete = updateCellName;

    // __publishedを取得する
    DcResponse getResp = restGet(getUrl(updateCellName));
    String resPublished = ODataCommon.getPublished(getResp);

    // Cell更新のレスポンスチェック
    assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode());
    assertEquals(published, resPublished);
}
 
Example #29
Source File: PropertyCreateValidateTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * PropertyのCollectionKindがNoneの場合_正常に作成できること.
 */
@Test
public final void PropertyのCollectionKindがNoneの場合_正常に作成できること() {
    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, true);
        req.addJsonBody(PropertyUtils.PROPERTY_DEFAULT_VALUE_KEY, null);
        req.addJsonBody(PropertyUtils.PROPERTY_COLLECTION_KIND_KEY, Property.COLLECTION_KIND_NONE);
        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.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を削除
        deleteOdataResource(locationUrl).getStatusCode();
    }
}
 
Example #30
Source File: BoxUrlTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * BoxRead権限のあるユーザーでschema指定がある場合に302が返却されること.
 */
@Test
public final void BoxRead権限のあるユーザーでschema指定がある場合に302が返却されること() {
    try {
        String aclXml = String.format("<D:acl xmlns:D='DAV:' xml:base='%s/%s/__role/__/'>",
                UrlUtils.getBaseUrl(), Setup.TEST_CELL1)
                + "  <D:ace>"
                + "    <D:principal>"
                + "      <D:href>role1</D:href>"
                + "    </D:principal>"
                + "    <D:grant>"
                + "      <D:privilege><D:read/></D:privilege>"
                + "    </D:grant>"
                + "  </D:ace>"
                + "</D:acl>";
        beforeACLTest(aclXml);

        DcRestAdapter rest = new DcRestAdapter();
        DcResponse res = null;

        HashMap<String, String> requestheaders = new HashMap<String, String>();
        String token = ResourceUtils.getMyCellLocalToken(Setup.TEST_CELL1, "account1", "password1");
        requestheaders.put(HttpHeaders.AUTHORIZATION, "Bearer " + token);

        res = rest.getAcceptEncodingGzip(
                UrlUtils.boxUrl(Setup.TEST_CELL1, UrlUtils.cellRoot("boxUrlTestSchema")),
                requestheaders);
        assertEquals(HttpStatus.SC_OK, res.getStatusCode());
        assertEquals(UrlUtils.boxRoot(Setup.TEST_CELL1, "boxUrlTest"), res.getFirstHeader(HttpHeaders.LOCATION));
    } catch (DcException e) {
        fail(e.getMessage());
    } finally {
        afterACLTest();
    }
}