下面列出了怎么用org.apache.http.HttpStatus的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@Deployment(resources = { "org/flowable/rest/service/api/runtime/ProcessInstanceVariableResourceTest.testProcess.bpmn20.xml" })
public void testGetProcessInstanceInstantVariable() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
Instant now = Instant.now();
Instant nowWithoutNanos = now.truncatedTo(ChronoUnit.MILLIS);
runtimeService.setVariable(processInstance.getId(), "variable", now);
CloseableHttpResponse response = executeRequest(
new HttpGet(
SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_VARIABLE, processInstance.getId(), "variable")),
HttpStatus.SC_OK);
JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
closeResponse(response);
assertThat(responseNode).isNotNull();
assertThatJson(responseNode)
.when(Option.IGNORING_EXTRA_FIELDS)
.isEqualTo("{"
+ " name: 'variable',"
+ " type: 'instant',"
+ " value: '" + nowWithoutNanos.toString() + "'"
+ "}");
}
/**
* WebDAVコレクションのMOVEで存在するBoxを指定した場合に400エラーとなること.
*/
@Test
public final void WebDAVコレクションのMOVEで存在するBoxを指定した場合に400エラーとなること() {
final String srcColName = "davColforMOVE";
final String destUrl = UrlUtils.box(CELL_NAME, BOX_NAME);
try {
// 事前準備
DavResourceUtils.createWebDavCollection(TOKEN, HttpStatus.SC_CREATED, CELL_NAME, BOX_NAME, srcColName);
// 移動
TResponse response = DavResourceUtils.moveWebDav(TOKEN, CELL_NAME, BOX_NAME + "/" + srcColName, destUrl,
HttpStatus.SC_BAD_REQUEST);
DcCoreException expectedException = DcCoreException.Dav.INVALID_REQUEST_HEADER.params(
HttpHeaders.DESTINATION, destUrl);
ODataCommon.checkErrorResponseBody(response, expectedException.getCode(), expectedException.getMessage());
} finally {
DavResourceUtils.deleteCollection(CELL_NAME, BOX_NAME, srcColName, TOKEN, -1);
}
}
/**
* Basic認証ーCell制御オブジェクトの更新. <br />
* (共通ロジックのためBoxのみ実施)
* @throws DcException リクエスト失敗
*/
@Test
public final void Basic認証ーCell制御オブジェクトの更新() throws DcException {
String testBox = "BasicTestBox";
String newBox = "BasicTestBoxNew";
try {
// 事前準備
BoxUtils.create(cellName, testBox, AbstractCase.MASTER_TOKEN_NAME);
// 401エラーとなること
DcResponse dcRes = BoxUtils.updateWithAuthSchema(cellName, testBox, newBox, authorization);
assertThat(dcRes.getStatusCode()).isEqualTo(HttpStatus.SC_UNAUTHORIZED);
AuthTestCommon.checkAuthenticateHeader(dcRes, OAuth2Helper.Scheme.BEARER, cellName);
// ACL all-all の場合正常終了すること
setAclPriviriegeAllPrincipalAll(cellName);
dcRes = BoxUtils.updateWithAuthSchema(cellName, testBox, newBox, authorization);
assertThat(dcRes.getStatusCode()).isEqualTo(HttpStatus.SC_NO_CONTENT);
AuthTestCommon.checkAuthenticateHeaderNotExists(dcRes);
} finally {
BoxUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, testBox, -1);
BoxUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, newBox, -1);
}
}
/**
* Checks if the returned "data" array (child-node of root-json node returned by invoking a GET on the given url) contains entries with the given ID's.
*/
protected void assertResultsPresentInDataResponse(String url, String... expectedResourceIds) throws IOException {
int numberOfResultsExpected = expectedResourceIds.length;
// Do the actual call
CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);
// Check status and size
JsonNode dataNode = objectMapper.readTree(response.getEntity().getContent()).get("data");
closeResponse(response);
assertThat(numberOfResultsExpected).isEqualTo(dataNode.size());
// Check presence of ID's
List<String> toBeFound = new ArrayList<>(Arrays.asList(expectedResourceIds));
for (JsonNode aDataNode : dataNode) {
String id = aDataNode.get("id").textValue();
toBeFound.remove(id);
}
assertThat(toBeFound).as("Not all expected ids have been found in result, missing: " + StringUtils.join(toBeFound, ", ")).isEmpty();
}
/**
* Test suspending already suspended process definition. POST repository/process-definitions/{processDefinitionId}
*/
@Test
@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testSuspendAlreadySuspendedProcessDefinition() throws Exception {
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
repositoryService.suspendProcessDefinitionById(processDefinition.getId());
processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
assertThat(processDefinition.isSuspended()).isTrue();
ObjectNode requestNode = objectMapper.createObjectNode();
requestNode.put("action", "suspend");
HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_DEFINITION, processDefinition.getId()));
httpPut.setEntity(new StringEntity(requestNode.toString()));
CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_CONFLICT);
closeResponse(response);
}
/**
* Checks if the returned "data" array (child-node of root-json node returned by invoking a GET on the given url) contains entries with the given ID's.
*/
protected void assertResultsPresentInDataResponse(String url, String... expectedResourceIds) throws JsonProcessingException, IOException {
int numberOfResultsExpected = expectedResourceIds.length;
// Do the actual call
CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);
// Check status and size
JsonNode dataNode = objectMapper.readTree(response.getEntity().getContent()).get("data");
closeResponse(response);
assertThat(dataNode).hasSize(numberOfResultsExpected);
// Check presence of ID's
List<String> toBeFound = new ArrayList<>(Arrays.asList(expectedResourceIds));
Iterator<JsonNode> it = dataNode.iterator();
while (it.hasNext()) {
String id = it.next().get("id").textValue();
toBeFound.remove(id);
}
assertThat(toBeFound).as("Not all expected ids have been found in result, missing: " + StringUtils.join(toBeFound, ", ")).isEmpty();
}
/**
* Acceptにimage/jpegを指定してCell取得した場合にjsonフォーマットでレスポンスが返却されること. $format → json Accept → image/jpeg
*/
@Test
public final void $formatがjsonでacceptがjpegでCell取得した場合にjsonフォーマットでレスポンスが返却されること() {
String url = getUrl(this.cellId);
// $format json
// Acceptヘッダ image/jpeg
HashMap<String, String> headers = new HashMap<String, String>();
headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
headers.put(HttpHeaders.ACCEPT, "image/jpeg");
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);
}
/**
* ComplexTypeの更新時Nameが指定されていない場合400になること.
*/
@Test
public final void ComplexTypeの更新時Nameが指定されていない場合400になること() {
String complexTypeName = "testComplexType";
try {
// ComplexTypeの作成
ComplexTypeUtils.create(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, complexTypeName,
HttpStatus.SC_CREATED);
// ComplexTypeの更新(400になること)
TResponse res = ComplexTypeUtils.update(MASTER_TOKEN_NAME, Setup.TEST_CELL1, Setup.TEST_BOX1,
Setup.TEST_ODATA, complexTypeName, new JSONObject(), HttpStatus.SC_BAD_REQUEST);
res.checkErrorResponse(DcCoreException.OData.INPUT_REQUIRED_FIELD_MISSING.getCode(),
DcCoreException.OData.INPUT_REQUIRED_FIELD_MISSING.params("Name").getMessage());
} finally {
ComplexTypeUtils.delete(MASTER_TOKEN_NAME, Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA,
complexTypeName, -1);
}
}
/**
* Cellの更新のNameが__ctlの場合に400が返却されること.
*/
@SuppressWarnings("unchecked")
@Test
public final void Cellの更新のNameが__ctlの場合に400が返却されること() {
// 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", "__ctl");
res = updateCell(headers, requestBody);
// Cell更新のレスポンスチェック
assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode());
assertEquals(MediaType.APPLICATION_JSON, res.getResponseHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue());
this.checkErrorResponse(res.bodyAsJson(), "PR400-OD-0006");
}
@Test
public void testDeleteVocabulary() throws Exception {
Resource additionsGraphIRI;
String recordId, branchId, commitId;
ValueFactory vf = getOsgiService(ValueFactory.class);
HttpEntity entity = createFormData("/test-vocabulary.ttl", "Test Vocabulary");
try (CloseableHttpResponse response = uploadFile(createHttpClient(), entity)) {
assertEquals(HttpStatus.SC_CREATED, response.getStatusLine().getStatusCode());
String[] ids = parseAndValidateUploadResponse(response);
recordId = ids[0];
branchId = ids[1];
commitId = ids[2];
additionsGraphIRI = validateOntologyCreated(vf.createIRI(recordId), vf.createIRI(branchId), vf.createIRI(commitId));
}
try (CloseableHttpResponse response = deleteOntology(createHttpClient(), recordId)) {
assertNotNull(response);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
validateOntologyDeleted(vf.createIRI(recordId), vf.createIRI(branchId), vf.createIRI(commitId), additionsGraphIRI);
} catch (IOException | GeneralSecurityException e) {
fail("Exception thrown: " + e.getLocalizedMessage());
}
}
/**
* ComplexPropertyのTypeがEdmDateTimeの場合ユーザデータに最大値より大きい値を指定して400エラーとなること.
*/
@SuppressWarnings("unchecked")
@Test
public final void ComplexPropertyのTypeがEdmDateTimeの場合ユーザデータに最大値より大きい値を指定して400エラーとなること() {
// リクエストボディを設定
JSONObject complexBody = new JSONObject();
complexBody.put(PROP_NAME, "/Date(" + (ODataUtils.DATETIME_MAX + 1) + ")/");
JSONObject body = new JSONObject();
body.put("__id", USERDATA_ID);
body.put(PROP_NAME, complexBody);
try {
createEntities(EdmSimpleType.DATETIME.getFullyQualifiedTypeName());
// ユーザデータ作成
TResponse response = createUserData(body, HttpStatus.SC_BAD_REQUEST,
cellName, boxName, COL_NAME, ENTITY_TYPE_NAME);
JSONObject json = response.bodyAsJson();
String code = json.get("code").toString();
assertEquals("PR400-OD-0006", code);
} finally {
deleteEntities();
}
}
/**
* Look for session cookies.
*
* @return true if session cookies are available
*/
protected boolean isAuthenticated(ResponseWrapper getRequest) {
boolean authenticated = false;
if (getRequest.getStatusCode() == HttpStatus.SC_OK
&& "/ews/services.wsdl".equalsIgnoreCase(getRequest.getURI().getPath())) {
// direct EWS access returned wsdl
authenticated = true;
} else {
// check cookies
for (Cookie cookie : httpClientAdapter.getCookies()) {
// Exchange 2003 cookies
if (cookie.getName().startsWith("cadata") || "sessionid".equals(cookie.getName())
// Exchange 2007 cookie
|| "UserContext".equals(cookie.getName())
) {
authenticated = true;
break;
}
}
}
return authenticated;
}
/**
* UserDataに前方一致検索クエリに整数値を指定した場合ステータスコード400が返却されること.
*/
@Test
public final void UserDataに前方一致検索クエリに整数値を指定した場合ステータスコード400が返却されること() {
// ユーザデータの一覧取得
String sdEntityTypeName = "SalesDetail";
Http.request("box/odatacol/list.txt")
.with("cell", cellName)
.with("box", boxName)
.with("collection", colName)
.with("entityType", sdEntityTypeName)
.with("query", "?\\$filter=startswith%28number%2c1%29")
.with("accept", MediaType.APPLICATION_JSON)
.with("token", DcCoreConfig.getMasterToken())
.returns()
.statusCode(HttpStatus.SC_BAD_REQUEST)
.debug();
}
/**
* Relation新規登録時_Box.Nameに__ctlを指定した場合400になること.
*/
@Test
public void Relation新規登録時Box名に__ctlを指定した場合400になること() {
String relationName = testRelationName;
String boxname = "__ctl";
String locationHeader = null;
try {
TResponse res = createRelation(relationName, boxname);
res.statusCode(HttpStatus.SC_BAD_REQUEST);
locationHeader = res.getLocationHeader();
} finally {
if (locationHeader != null) {
deleteOdataResource(locationHeader);
}
}
}
/**
* ComplexTypePropertyの_ComplexTypeNameが空文字の場合_BadRequestが返却されること.
*/
@Test
public final void ComplexTypePropertyの_ComplexTypeNameが空文字の場合_BadRequestが返却されること() {
// リクエストパラメータ設定
DcRequest req = DcRequest.post(ComplexTypePropertyUtils.CTP_REQUEST_URL);
req.header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_NAME_KEY, CT_PROPERTY_NAME);
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_COMPLEXTYPE_NAME_KEY, "");
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_TYPE_KEY,
EdmSimpleType.STRING.getFullyQualifiedTypeName());
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_NULLABLE_KEY, null);
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_DEFAULT_VALUE_KEY, null);
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_COLLECTION_KIND_KEY, null);
// リクエスト実行
DcResponse response = request(req);
// レスポンスチェック
assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode());
checkErrorResponse(
response.bodyAsJson(),
DcCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.getCode(),
DcCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(
ComplexTypePropertyUtils.CT_PROPERTY_COMPLEXTYPE_NAME_KEY).getMessage());
}
private void chownFile( String user, String password, String file, String owner, String group, int status ) {
driver.getMock( "WEBHDFS" )
.expect()
.method( "PUT" )
.pathInfo( "/v1" + file )
.queryParam( "op", "SETOWNER" )
.queryParam( "user.name", user )
.queryParam( "owner", owner )
.queryParam( "group", group )
.respond()
.status( HttpStatus.SC_OK );
given()
//.log().all()
.auth().preemptive().basic( user, password )
.header( "X-XSRF-Header", "jksdhfkhdsf" )
.queryParam( "op", "SETOWNER" )
.queryParam( "owner", owner )
.queryParam( "group", group )
.then()
//.log().all()
.statusCode( status )
.when().put( driver.getUrl("WEBHDFS") + "/v1" + file + ( driver.isUseGateway() ? "" : "?user.name=" + user ) );
driver.assertComplete();
}
/**
* Test getting a single event definition. GET event-registry-repository/event-definitions/{eventDefinitionResource}
*/
@EventDeploymentAnnotation(resources = { "org/flowable/eventregistry/rest/service/api/repository/simpleEvent.event" })
public void testGetEventDefinition() throws Exception {
EventDefinition eventDefinition = repositoryService.createEventDefinitionQuery().singleResult();
HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX + EventRestUrls.createRelativeResourceUrl(EventRestUrls.URL_EVENT_DEFINITION, eventDefinition.getId()));
CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);
JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
closeResponse(response);
assertThatJson(responseNode)
.when(Option.IGNORING_EXTRA_FIELDS)
.isEqualTo("{"
+ "id: '" + eventDefinition.getId() + "',"
+ "url: '" + httpGet.getURI().toString() + "',"
+ "key: '" + eventDefinition.getKey() + "',"
+ "version: " + eventDefinition.getVersion() + ","
+ "name: '" + eventDefinition.getName() + "',"
+ "description: " + eventDefinition.getDescription() + ","
+ "deploymentId: '" + eventDefinition.getDeploymentId() + "',"
+ "deploymentUrl: '" + SERVER_URL_PREFIX + EventRestUrls
.createRelativeResourceUrl(EventRestUrls.URL_DEPLOYMENT, eventDefinition.getDeploymentId()) + "',"
+ "resourceName: '" + eventDefinition.getResourceName() + "',"
+ "category: " + eventDefinition.getCategory()
+ "}");
}
/**
* 移動元の親にall権限を持つアカウントでServiceコレクションのMOVEをした場合201となること.
* @throws JAXBException ACLのパース失敗
*/
@Test
public void 移動元の親にall権限を持つアカウントでServiceコレクションのMOVEをした場合201となること() throws JAXBException {
String token;
String path = String.format("%s/%s/%s", BOX_NAME, SRC_COL_NAME, COL_NAME);
String destination = UrlUtils.box(CELL_NAME, BOX_NAME, DST_COL_NAME, COL_NAME);
String srcColPath = SRC_COL_NAME + "/" + COL_NAME;
// 事前準備
setDefaultAcl(SRC_COL_NAME); // 移動元:親コレクション: 全ロールに対して read / write
setPrincipalAllAcl(DST_COL_NAME); // 移動先:親コレクション: 全ロールに対して all
DavResourceUtils.createServiceCollection(
BEARER_MASTER_TOKEN, HttpStatus.SC_CREATED, CELL_NAME, BOX_NAME, srcColPath);
// all権限→201
token = getToken(ACCOUNT_ALL_PRIVILEGE);
DavResourceUtils.moveWebDav(token, CELL_NAME, path, destination, HttpStatus.SC_CREATED);
}
@Test
public void returnUrlLengthValidationFailure() {
String returnUrl = "https://example.com?something=" + "aVeryLongString12345".repeat(100);
given().port(app.getLocalPort())
.body(Map.of("return_url", returnUrl, "reference", "test reference"))
.accept(JSON)
.contentType(JSON)
.header(AUTHORIZATION, "Bearer " + API_KEY)
.post("/v1/directdebit/mandates")
.then()
.statusCode(HttpStatus.SC_UNPROCESSABLE_ENTITY)
.body("size()", is(3))
.body("field", is("return_url"))
.body("code", is("P0102"))
.body("description", is("Invalid attribute value: return_url. Must be less than or equal to 2000 characters length"));
}
/**
* ユーザデータの一覧を作成.
* @param index インデックス番号
* @return TResponse レスポンス情報
*/
@SuppressWarnings("unchecked")
public TResponse createData(int index) {
// リクエストボディを設定
JSONObject body = new JSONObject();
body.put("__id", USERDATA_ID_PREFIX + String.valueOf(index));
body.put("dynamicProperty", "dynamicPropertyValue");
body.put("secondDynamicProperty", "secondDynamicPropertyValue");
body.put("nullProperty", null);
body.put("intProperty", 123);
body.put("floatProperty", 123.123);
body.put("trueProperty", true);
body.put("falseProperty", false);
body.put("nullStringProperty", "null");
body.put("intStringProperty", "123");
body.put("floatStringProperty", "123.123");
body.put("trueStringProperty", "true");
body.put("falseStringProperty", "false");
// ユーザデータ作成
return createUserData(body, HttpStatus.SC_CREATED);
}
@Parameters({"admin-username", "admin-password", "test-username", "test-password", "broker-hostname",
"broker-port"})
@Test
public void testCloseConnectionWithUnAuthorizedUSer(String adminUserName, String adminPassword, String
testUsername, String testPassword, String hostName, String port) throws Exception {
connections.add(createConnection(2, adminUserName, adminPassword, hostName, port));
ConnectionMetadata[] connectionMetadataBeforeClosing = getConnections(adminUserName, adminPassword);
Assert.assertEquals(connectionMetadataBeforeClosing.length, 1,
"Incorrect connection count before closing connection.");
//Send delete request with invalid connection identifier
HttpDelete httpDelete = new HttpDelete(apiBasePath + CONNECTIONS_API_PATH + "/"
+ connectionMetadataBeforeClosing[0].getId());
ClientHelper.setAuthHeader(httpDelete, testUsername, testPassword);
CloseableHttpResponse connectionCloseResponse = client.execute(httpDelete);
Assert.assertEquals(connectionCloseResponse.getStatusLine().getStatusCode(), HttpStatus.SC_FORBIDDEN,
"Incorrect status code while closing connections");
}
/**
* ユーザODataのNavigationProperty経由一覧取得でexpandに最大プロパティ数を指定した場合正常に取得できること.
*/
@Test
public final void ユーザODataのNavigationProperty経由一覧取得でexpandに最大プロパティ数を指定した場合正常に取得できること() {
String cell = Setup.TEST_CELL1;
String box = Setup.TEST_BOX1;
String collection = Setup.TEST_ODATA;
String fromEntity = "SalesDetail";
String toEntity = "Sales";
String expandEntity1 = "Price";
String expandEntity2 = "Product";
String fromUserDataId = "userdata000";
// NP経由一覧取得($expand)
String expands = String.format("?\\$expand=_%s,_%s", expandEntity1, expandEntity2);
UserDataUtils.listViaNP(cell, box, collection, fromEntity, fromUserDataId, toEntity, expands,
HttpStatus.SC_OK);
}
public void handleValidationRequest(Context ctx) {
ValidationRequest request = ctx.bodyAsClass(ValidationRequest.class);
ValidationResponse response = null;
try {
response = ValidationService.validateSources(request, myValidationEngine);
ObjectMapper Obj = new ObjectMapper();
/*
* TODO
* Write file contents to temp files to pass to validator instead of creating our own endpoint.
* Create File => new temp file
* Use Option => DeleteOnShutdown
*/
String jsonStr = Obj.writeValueAsString(response);
ctx.status(200).json(jsonStr);
} catch (Exception e) {
ctx.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).result(e.getLocalizedMessage());
}
}
/**
* Keyあり取得時にexpandにアンダースコアのみを指定した場合に400が返却されること.
*/
@Test
public final void Keyあり取得時にexpandにアンダースコアのみを指定した場合に400が返却されること() {
try {
// データ作成
createData();
// $expandを指定してデータを取得
Http.request("box/odatacol/list.txt")
.with("cell", Setup.TEST_CELL1)
.with("box", Setup.TEST_BOX1)
.with("collection", Setup.TEST_ODATA)
.with("entityType", navPropName + "('" + fromUserDataId + "')")
.with("query", "?\\$expand=_")
.with("accept", MediaType.APPLICATION_JSON)
.with("token", DcCoreConfig.getMasterToken())
.returns()
.statusCode(HttpStatus.SC_BAD_REQUEST)
.debug();
} finally {
// データ削除
deleteData();
}
}
private <T> T requestResponse(String url, Object request, Class<T> responseClass) {
HttpPost post = new HttpPost(url);
try {
post.setEntity(new StringEntity(gson.toJson(request), ContentType.APPLICATION_JSON));
HttpResponse response = httpClient.execute(httpHost, post);
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
throw new RuntimeIOException("Unexpected response code: " + status);
}
return gson.fromJson(EntityUtils.toString(response.getEntity()), responseClass);
} catch (IOException e) {
throw new RuntimeIOException("HTTP error: " + e, e);
}
}
public static String executeHttpRequest(CloseableHttpClient httpClient, HttpRequestBase request,
String encoding) throws IOException {
try {
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
if (status >= HttpStatus.SC_OK
&& status < HttpStatus.SC_MULTIPLE_CHOICES) {
return IOUtils.toString(response.getEntity().getContent(),
encoding);
} else {
logger.error("the response status code {} is illegal", status);
throw new GeneralRuntimeException(
HttpClientConstants.HTTP_RESPONSE_STATUS_ERROR.toString());
}
} finally {
httpClient.close();
}
}
@Test
public void testDlsDateMathQuery() throws Exception {
final Settings settings = Settings.builder().put(ConfigConstants.OPENDISTRO_SECURITY_UNSUPPORTED_ALLOW_NOW_IN_DLS,true).build();
setup(settings);
HttpResponse res;
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("/logstash/_search?pretty", encodeBasicHeader("date_math", "password"))).getStatusCode());
System.out.println(res.getBody());
Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation"));
Assert.assertTrue(res.getBody().contains("\"failed\" : 0"));
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("/logstash/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode());
System.out.println(res.getBody());
Assert.assertTrue(res.getBody().contains("\"value\" : 3,\n \"relation"));
Assert.assertTrue(res.getBody().contains("\"failed\" : 0"));
}
public <T> Object processResponse(HttpResponse response, Class<T> c, String purposeStr)
throws IOException {
HttpEntity httpEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
try {
if (statusCode == HttpStatus.SC_OK) {
if (c != null) {
Reader reader = new InputStreamReader(httpEntity.getContent());
T entityVal = new Gson().fromJson(reader, c);
return entityVal;
}
return null;
} else {
String errorMsg = formatErrorMsg(purposeStr, response);
LOG.error(errorMsg);
throw new IOException(errorMsg);
}
} catch (IOException e) {
LOG.error("read response entity", e);
throw new IOException("read response entity", e);
} finally {
closeResponseEntity(response);
}
}
@Test
public void testFields2() throws Exception {
setup();
String query = FileHelper.loadFile("dlsfls/flsquery2.json");
HttpResponse res;
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executePostRequest("/deals/_search?pretty=true", query, encodeBasicHeader("admin", "admin"))).getStatusCode());
Assert.assertTrue(res.getBody().contains("secret"));
Assert.assertTrue(res.getBody().contains("@timestamp"));
Assert.assertTrue(res.getBody().contains("\"timestamp"));
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executePostRequest("/deals/_search?pretty=true", query, encodeBasicHeader("fls_fields", "password"))).getStatusCode());
Assert.assertFalse(res.getBody().contains("customer"));
Assert.assertFalse(res.getBody().contains("secret"));
Assert.assertFalse(res.getBody().contains("timestamp"));
Assert.assertTrue(res.getBody().contains("numfield5"));
}
/**
* relation_jsonがJSON形式でない場合に異常終了すること.
*/
@Test
public final void relation_jsonがJSON形式でない場合に異常終了すること() {
// JSONファイルの解析エラーー
String reqCell = Setup.TEST_CELL1;
String reqPath = INSTALL_TARGET;
TResponse res = null;
File barFile = new File(RESOURCE_PATH + BAR_FILE_NO_JSON_FORM);
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);
}