Java Code Examples for org.apache.http.HttpHeaders

The following examples show how to use org.apache.http.HttpHeaders. These examples are extracted from open source projects. 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 Project: brooklyn-server   Author: apache   File: BrooklynPropertiesSecurityFilterTest.java    License: 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 #2
Source Project: cloud-odata-java   Author: SAP   File: EntryJsonCreateInlineTest.java    License: 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 #3
Source Project: io   Author: fujitsu-pio   File: MoveFileTest.java    License: 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 #4
Source Project: io   Author: fujitsu-pio   File: BarInstallTest.java    License: 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 #5
Source Project: io   Author: fujitsu-pio   File: BarInstallTest.java    License: 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 #6
Source Project: FishingBot   Author: MrKinau   File: RealmsAPI.java    License: 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 #7
Source Project: devops-cm-client   Author: SAP   File: CMODataAbapClient.java    License: 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 #8
Source Project: flowable-engine   Author: flowable   File: BaseSpringRestTestCase.java    License: 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 #9
Source Project: io   Author: fujitsu-pio   File: MoveFileTest.java    License: 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 #10
Source Project: hbase   Author: apache   File: TestThriftSpnegoHttpFallbackServer.java    License: 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 #11
Source Project: io   Author: fujitsu-pio   File: UpdateTest.java    License: 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 #12
Source Project: io   Author: fujitsu-pio   File: BarInstallTest.java    License: 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 #13
Source Project: io   Author: fujitsu-pio   File: ReadTest.java    License: 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 #14
Source Project: io   Author: fujitsu-pio   File: CellUtils.java    License: 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 #15
Source Project: io   Author: fujitsu-pio   File: ComplexTypeCreateTest.java    License: 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 #16
Source Project: io   Author: fujitsu-pio   File: ImplicitFlowTest.java    License: 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 #17
Source Project: armeria   Author: line   File: FileServiceTest.java    License: 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 #18
Source Project: io   Author: fujitsu-pio   File: ImplicitFlowTest.java    License: 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 #19
Source Project: cloud-odata-java   Author: SAP   File: RequestContentTypeTest.java    License: 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 #20
Source Project: brooklyn-server   Author: apache   File: BundleAndTypeResourcesTest.java    License: Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #21
Source Project: io   Author: fujitsu-pio   File: PropertyCreateValidateDefaultValueTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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());
    }
}
 
Example #22
Source Project: cloud-odata-java   Author: SAP   File: RequestContentTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #23
Source Project: tutorials   Author: eugenp   File: HttpClientAuthLiveTest.java    License: MIT License 5 votes vote down vote up
@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));
}
 
Example #24
Source Project: cloud-odata-java   Author: SAP   File: ContentNegotiationTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #25
Source Project: io   Author: fujitsu-pio   File: MoveCollectionTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #26
Source Project: io   Author: fujitsu-pio   File: MoveServiceSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #27
Source Project: io   Author: fujitsu-pio   File: PropertyCreateValidateTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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());
    }
}
 
Example #28
Source Project: torrssen2   Author: tarpha   File: TelegramService.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example #29
Source Project: olingo-odata2   Author: apache   File: RequestContentTypeTest.java    License: 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 #30
Source Project: io   Author: fujitsu-pio   File: MoveCollectionTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}