Search in sources :

Example 1 with DocumentContext

use of com.jayway.jsonpath.DocumentContext in project spring-boot-admin by codecentric.

the class ApplicationTest method test_json_format.

@Test
public void test_json_format() throws JsonProcessingException, IOException {
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
    Application app = Application.create("test").withHealthUrl("http://health").withServiceUrl("http://service").withManagementUrl("http://management").build();
    DocumentContext json = JsonPath.parse(objectMapper.writeValueAsString(app));
    assertThat((String) json.read("$.name")).isEqualTo("test");
    assertThat((String) json.read("$.serviceUrl")).isEqualTo("http://service");
    assertThat((String) json.read("$.managementUrl")).isEqualTo("http://management");
    assertThat((String) json.read("$.healthUrl")).isEqualTo("http://health");
}
Also used : DocumentContext(com.jayway.jsonpath.DocumentContext) Application(de.codecentric.boot.admin.client.registration.Application) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 2 with DocumentContext

use of com.jayway.jsonpath.DocumentContext in project selenium-tests by Wikia.

the class CreateCategory method execute.

public CategoryPill.Data execute(final CreateCategoryContext context) {
    JSONObject jsonObject = new JSONObject(ImmutableMap.builder().put("name", context.getCategoryName()).put("parentId", PARENT_ID).put("siteId", context.getSiteId()).build());
    String response;
    try {
        response = remoteOperation.execute(buildUrl(context), jsonObject);
    } catch (RemoteException e) {
        PageObjectLogging.logError("error: ", e);
        throw new CategoryNotCreated("Could not create a new category.", e);
    }
    DocumentContext json = JsonPath.parse(response);
    CategoryPill.Data data = new CategoryPill.Data(json.read("$.id"), json.read("$.name"));
    data.setDisplayOrder(json.read("$.displayOrder"));
    return data;
}
Also used : JSONObject(org.json.JSONObject) CategoryPill(com.wikia.webdriver.elements.mercury.components.discussions.common.category.CategoryPill) RemoteException(com.wikia.webdriver.common.remote.RemoteException) DocumentContext(com.jayway.jsonpath.DocumentContext)

Example 3 with DocumentContext

use of com.jayway.jsonpath.DocumentContext in project nifi by apache.

the class SplitJson method onTrigger.

@Override
public void onTrigger(final ProcessContext processContext, final ProcessSession processSession) {
    FlowFile original = processSession.get();
    if (original == null) {
        return;
    }
    final ComponentLog logger = getLogger();
    DocumentContext documentContext;
    try {
        documentContext = validateAndEstablishJsonContext(processSession, original);
    } catch (InvalidJsonException e) {
        logger.error("FlowFile {} did not have valid JSON content.", new Object[] { original });
        processSession.transfer(original, REL_FAILURE);
        return;
    }
    final JsonPath jsonPath = JSON_PATH_REF.get();
    Object jsonPathResult;
    try {
        jsonPathResult = documentContext.read(jsonPath);
    } catch (PathNotFoundException e) {
        logger.warn("JsonPath {} could not be found for FlowFile {}", new Object[] { jsonPath.getPath(), original });
        processSession.transfer(original, REL_FAILURE);
        return;
    }
    if (!(jsonPathResult instanceof List)) {
        logger.error("The evaluated value {} of {} was not a JSON Array compatible type and cannot be split.", new Object[] { jsonPathResult, jsonPath.getPath() });
        processSession.transfer(original, REL_FAILURE);
        return;
    }
    List resultList = (List) jsonPathResult;
    Map<String, String> attributes = new HashMap<>();
    final String fragmentId = UUID.randomUUID().toString();
    attributes.put(FRAGMENT_ID.key(), fragmentId);
    attributes.put(FRAGMENT_COUNT.key(), Integer.toString(resultList.size()));
    for (int i = 0; i < resultList.size(); i++) {
        Object resultSegment = resultList.get(i);
        FlowFile split = processSession.create(original);
        split = processSession.write(split, (out) -> {
            String resultSegmentContent = getResultRepresentation(resultSegment, nullDefaultValue);
            out.write(resultSegmentContent.getBytes(StandardCharsets.UTF_8));
        });
        attributes.put(SEGMENT_ORIGINAL_FILENAME.key(), split.getAttribute(CoreAttributes.FILENAME.key()));
        attributes.put(FRAGMENT_INDEX.key(), Integer.toString(i));
        processSession.transfer(processSession.putAllAttributes(split, attributes), REL_SPLIT);
    }
    original = copyAttributesToOriginal(processSession, original, fragmentId, resultList.size());
    processSession.transfer(original, REL_ORIGINAL);
    logger.info("Split {} into {} FlowFiles", new Object[] { original, resultList.size() });
}
Also used : StandardValidators(org.apache.nifi.processor.util.StandardValidators) FRAGMENT_INDEX(org.apache.nifi.flowfile.attributes.FragmentAttributes.FRAGMENT_INDEX) CapabilityDescription(org.apache.nifi.annotation.documentation.CapabilityDescription) ValidationContext(org.apache.nifi.components.ValidationContext) HashMap(java.util.HashMap) EventDriven(org.apache.nifi.annotation.behavior.EventDriven) SystemResource(org.apache.nifi.annotation.behavior.SystemResource) ComponentLog(org.apache.nifi.logging.ComponentLog) AtomicReference(java.util.concurrent.atomic.AtomicReference) StringUtils(org.apache.commons.lang3.StringUtils) SideEffectFree(org.apache.nifi.annotation.behavior.SideEffectFree) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ArrayList(java.util.ArrayList) InvalidJsonException(com.jayway.jsonpath.InvalidJsonException) HashSet(java.util.HashSet) FRAGMENT_COUNT(org.apache.nifi.flowfile.attributes.FragmentAttributes.FRAGMENT_COUNT) WritesAttributes(org.apache.nifi.annotation.behavior.WritesAttributes) Relationship(org.apache.nifi.processor.Relationship) Map(java.util.Map) Requirement(org.apache.nifi.annotation.behavior.InputRequirement.Requirement) FragmentAttributes.copyAttributesToOriginal(org.apache.nifi.flowfile.attributes.FragmentAttributes.copyAttributesToOriginal) ValidationResult(org.apache.nifi.components.ValidationResult) FlowFile(org.apache.nifi.flowfile.FlowFile) FRAGMENT_ID(org.apache.nifi.flowfile.attributes.FragmentAttributes.FRAGMENT_ID) Collection(java.util.Collection) ProcessContext(org.apache.nifi.processor.ProcessContext) Set(java.util.Set) ProcessSession(org.apache.nifi.processor.ProcessSession) UUID(java.util.UUID) WritesAttribute(org.apache.nifi.annotation.behavior.WritesAttribute) SEGMENT_ORIGINAL_FILENAME(org.apache.nifi.flowfile.attributes.FragmentAttributes.SEGMENT_ORIGINAL_FILENAME) JsonPath(com.jayway.jsonpath.JsonPath) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) InputRequirement(org.apache.nifi.annotation.behavior.InputRequirement) OnScheduled(org.apache.nifi.annotation.lifecycle.OnScheduled) SupportsBatching(org.apache.nifi.annotation.behavior.SupportsBatching) DocumentContext(com.jayway.jsonpath.DocumentContext) SystemResourceConsideration(org.apache.nifi.annotation.behavior.SystemResourceConsideration) Tags(org.apache.nifi.annotation.documentation.Tags) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) CoreAttributes(org.apache.nifi.flowfile.attributes.CoreAttributes) Collections(java.util.Collections) ProcessorInitializationContext(org.apache.nifi.processor.ProcessorInitializationContext) FlowFile(org.apache.nifi.flowfile.FlowFile) HashMap(java.util.HashMap) JsonPath(com.jayway.jsonpath.JsonPath) ComponentLog(org.apache.nifi.logging.ComponentLog) InvalidJsonException(com.jayway.jsonpath.InvalidJsonException) ArrayList(java.util.ArrayList) List(java.util.List) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) DocumentContext(com.jayway.jsonpath.DocumentContext)

Example 4 with DocumentContext

use of com.jayway.jsonpath.DocumentContext in project vft-capture by videofirst.

the class CaptureControllerTest method shouldStop.

// FIXME - error states
// ===========================================
// [ /api/captures/stop ] POST
// ===========================================
@Test
public void shouldStop() throws JSONException {
    startVideo(CAPTURE_START_PARAMS_MIN);
    ResponseEntity<String> response = stopVideo();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    String expectedJson = "{" + "    'state': 'stopped'," + "    'categories': {" + "        'organisation': 'Acme'," + "        'product': 'Moon Rocket'," + "        'module': 'UI'" + "    }," + "    'feature': 'Bob Feature'," + "    'scenario': 'Dave Scenario'," + "    'format': 'avi'" + "}";
    JSONAssert.assertEquals(expectedJson, response.getBody(), false);
    DocumentContext json = JsonPath.parse(response.getBody());
    JsonPathAssert.assertThat(json).jsonPathAsString("$.started").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.finished").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.durationSeconds").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.folder").startsWith("acme/moon-rocket/ui/bob-feature/dave-scenario/");
    JsonPathAssert.assertThat(json).jsonPathAsString("$.id").isNotNull().hasSize(26);
    JsonPathAssert.assertThat(json).jsonPathAsString("$.capture.x").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.capture.y").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.capture.width").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.capture.height").isNotNull();
    Map<String, String> environmentMap = json.read("$.environment");
    assertThat(environmentMap.get("java.awt.graphicsenv")).isNotEmpty();
}
Also used : DocumentContext(com.jayway.jsonpath.DocumentContext) Test(org.junit.Test)

Example 5 with DocumentContext

use of com.jayway.jsonpath.DocumentContext in project vft-capture by videofirst.

the class CaptureControllerTest method shouldFinishWithMaxParams.

@Test
public void shouldFinishWithMaxParams() throws JSONException {
    startVideo(CAPTURE_START_PARAMS_MAX);
    ResponseEntity<String> response = finishVideo(CAPTURE_FINISH_PARAMS_MAX);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    String expectedJson = "{" + "    'state': 'finished'," + "    'categories': {" + "        'organisation': 'Google'," + "        'product': 'Search'," + "        'module': 'Web App'" + "    }," + "    'feature': 'Advanced Search'," + "    'scenario': 'Search by Country!'," + "    'format': 'avi'," + "    'meta': {" + "        'version': '1.2.3-beta'," + "        'author': 'Bob'," + "        'extra': 'stuff'" + "    }," + "    'description': 'even more awesome description'," + "    'testStatus': 'fail'," + "    'testError': 'awesome error'," + "    'testStackTrace': 'co.videofirst.vft.capture.exception.InvalidStateException: Current state is idle'," + "    'testLogs': [{" + "        'ts': '2015-01-02T12:13:14'," + "        'cat': 'browser'," + "        'tier': 'L1'," + "        'log': 'awesome log 1'" + "    }, {" + "        'ts': '2016-02-03T16:17:18'," + "        'cat': 'server'," + "        'tier': 'L2'," + "        'log': 'awesome log 2'" + "    }]" + "}";
    JSONAssert.assertEquals(expectedJson, response.getBody(), false);
    DocumentContext json = JsonPath.parse(response.getBody());
    JsonPathAssert.assertThat(json).jsonPathAsString("$.started").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.finished").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.durationSeconds").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.folder").startsWith("google/search/web-app/advanced-search/search-by-country/");
    JsonPathAssert.assertThat(json).jsonPathAsString("$.id").isNotNull().hasSize(26);
    JsonPathAssert.assertThat(json).jsonPathAsString("$.capture.x").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.capture.y").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.capture.width").isNotNull();
    JsonPathAssert.assertThat(json).jsonPathAsString("$.capture.height").isNotNull();
    Map<String, String> environmentMap = json.read("$.environment");
    assertThat(environmentMap.get("java.awt.graphicsenv")).isNotEmpty();
}
Also used : DocumentContext(com.jayway.jsonpath.DocumentContext) Test(org.junit.Test)

Aggregations

DocumentContext (com.jayway.jsonpath.DocumentContext)146 Test (org.junit.Test)106 HashMap (java.util.HashMap)14 BaseTest (com.jayway.jsonpath.BaseTest)12 Map (java.util.Map)12 PathNotFoundException (com.jayway.jsonpath.PathNotFoundException)8 JsonPath (com.jayway.jsonpath.JsonPath)7 File (java.io.File)7 List (java.util.List)7 JsonPathAssert (com.revinate.assertj.json.JsonPathAssert)6 Query (org.graylog.plugins.views.search.Query)6 MessageList (org.graylog.plugins.views.search.searchtypes.MessageList)6 Time (org.graylog.plugins.views.search.searchtypes.pivot.buckets.Time)6 Values (org.graylog.plugins.views.search.searchtypes.pivot.buckets.Values)6 DateTime (org.joda.time.DateTime)6 Configuration (com.jayway.jsonpath.Configuration)5 ArrayList (java.util.ArrayList)5 Test (org.junit.jupiter.api.Test)5 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)5 InvalidJsonException (com.jayway.jsonpath.InvalidJsonException)4