com.jayway.jsonpath.PathNotFoundException Java Examples

The following examples show how to use com.jayway.jsonpath.PathNotFoundException. 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: JsonPathRule.java    From DBus with Apache License 2.0 6 votes vote down vote up
public List<List<String>> transform(List<List<String>> datas, List<RuleGrammar> grammar, Rules ruleType) throws Exception {
    List<List<String>> retVal = new ArrayList<>();
    for (List<String> data : datas) {
        List<String> ret = new LinkedList<>(data);
        List<ParseResult> prList = ParseRuleGrammar.parse(grammar, data.size(), ruleType);
        for (ParseResult pr : prList) {
            for (int col : pr.getScope()) {
                if (col >= data.size())
                    continue;
                String field = StringUtils.EMPTY;
                try {
                    if (JsonPath.parse(data.get(col)).read(pr.getParamter()) instanceof String) {
                        field = JsonPath.parse(data.get(col)).read(pr.getParamter());
                    } else {
                        field = JSON.toJSONString(JsonPath.parse(data.get(col)).read(pr.getParamter()));
                    }
                } catch (PathNotFoundException e) {
                    field = StringUtils.EMPTY;
                }
                ret.add(field);
            }
        }
        retVal.add(ret);
    }
    return retVal;
}
 
Example #2
Source File: OperationCompleter.java    From rug-cli with GNU General Public License v3.0 6 votes vote down vote up
private void completeBasedOnJsonpathMatches(String kind, List<String> words,
        List<Candidate> candidates) {
    if (ctx != null) {
        try {
            List<String> names = ctx.read(String.format("$.%s[*].name", kind));
            Optional<String> name = names.stream().filter(words::contains).map(String::toString)
                    .findFirst();
            if (name.isPresent()) {
                List<String> parameterNames = ctx.read(String
                        .format("$.%s[?(@.name=='%s')].parameters[*].name", kind, name.get()));
                completeParameters(kind, words, candidates, parameterNames);
                parameterNames = ctx.read(String
                        .format("$.%s[?(@.name=='%s')].mapped_parameters[*].local_key", kind, name.get()));
                completeParameters(kind, words, candidates, parameterNames);
            }
            else {
                names.forEach(n -> candidates.add(new Candidate(n)));
            }
        }
        catch (PathNotFoundException e) {
            // This is ok as it means we don't have the matching operation in the cache
        }
    }
}
 
Example #3
Source File: PackageManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Given a package, return a map of collections where this package is
 * installed to the installed version (which can be {@link PackagePluginHolder#LATEST})
 */
public Map<String, String> getDeployedCollections(String packageName) {
  List<String> allCollections;
  try {
    allCollections = zkClient.getChildren(ZkStateReader.COLLECTIONS_ZKNODE, null, true);
  } catch (KeeperException | InterruptedException e) {
    throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, e);
  }
  Map<String, String> deployed = new HashMap<String, String>();
  for (String collection: allCollections) {
    // Check package version installed
    String paramsJson = PackageUtils.getJsonStringFromUrl(solrClient.getHttpClient(), solrBaseUrl + PackageUtils.getCollectionParamsPath(collection) + "/PKG_VERSIONS?omitHeader=true");
    String version = null;
    try {
      version = JsonPath.parse(paramsJson, PackageUtils.jsonPathConfiguration())
          .read("$['response'].['params'].['PKG_VERSIONS'].['"+packageName+"'])");
    } catch (PathNotFoundException ex) {
      // Don't worry if PKG_VERSION wasn't found. It just means this collection was never touched by the package manager.
    }
    if (version != null) {
      deployed.put(collection, version);
    }
  }
  return deployed;
}
 
Example #4
Source File: PackageManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
public Map<String, SolrPackageInstance> getPackagesDeployed(String collection) {
  Map<String, String> packages = null;
  try {
    NavigableObject result = (NavigableObject) Utils.executeGET(solrClient.getHttpClient(),
        solrBaseUrl + PackageUtils.getCollectionParamsPath(collection) + "/PKG_VERSIONS?omitHeader=true&wt=javabin", Utils.JAVABINCONSUMER);
    packages = (Map<String, String>) result._get("/response/params/PKG_VERSIONS", Collections.emptyMap());
  } catch (PathNotFoundException ex) {
    // Don't worry if PKG_VERSION wasn't found. It just means this collection was never touched by the package manager.
  }
  if (packages == null) return Collections.emptyMap();
  Map<String, SolrPackageInstance> ret = new HashMap<>();
  for (String packageName: packages.keySet()) {
    if (Strings.isNullOrEmpty(packageName) == false && // There can be an empty key, storing the version here
        packages.get(packageName) != null) { // null means the package was undeployed from this package before
      ret.put(packageName, getPackageInstance(packageName, packages.get(packageName)));
    }
  }
  return ret;
}
 
Example #5
Source File: ApiSteps.java    From akita with Apache License 2.0 6 votes vote down vote up
/**
 * В json строке, сохраннённой в переменной, происходит поиск значений по jsonpath из первого столбца таблицы.
 * Полученные значения сохраняются в переменных. Название переменной указывается во втором столбце таблицы.
 * Шаг работает со всеми типами json элементов: объекты, массивы, строки, числа, литералы true, false и null.
 */
@Тогда("^значения из json (?:строки|файла) \"([^\"]*)\", найденные по jsonpath из таблицы, сохранены в переменные$")
@Then("^values from json (?:string|file) named \"([^\"]*)\" has been found via jsonpaths from the table and saved to the variables$")
public void getValuesFromJsonAsString(String jsonVar, DataTable dataTable) {
    String strJson = loadValueFromFileOrPropertyOrVariableOrDefault(jsonVar);
    Gson gsonObject = new Gson();
    ReadContext ctx = JsonPath.parse(strJson, createJsonPathConfiguration());
    boolean error = false;
    for (List<String> row : dataTable.raw()) {
        String jsonPath = row.get(0);
        String varName = row.get(1);
        JsonElement jsonElement;
        try {
            jsonElement = gsonObject.toJsonTree(ctx.read(jsonPath));
        } catch (PathNotFoundException e) {
            error = true;
            continue;
        }
        akitaScenario.setVar(varName, jsonElement.toString());
        akitaScenario.write("JsonPath: " + jsonPath + ", значение: " + jsonElement + ", записано в переменную: " + varName);
    }
    if (error)
        throw new RuntimeException("В json не найдено значение по заданному jsonpath");
}
 
Example #6
Source File: SolrFacetPivotDataReader.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected Object getJSONPathValue(Object o, String jsonPathValue) throws JSONException {
	// can be an array with a single value, a single object or also null (not found)
	Object res = null;
	try {
		if (jsonPathValue.contains(" ")) {
			String initial = "$.";
			jsonPathValue = jsonPathValue.substring(jsonPathValue.indexOf("$") + 2);
			jsonPathValue = "['" + jsonPathValue + "']";
			res = JsonPath.read(o, initial.concat(jsonPathValue));
		} else {
			res = JsonPath.read(o, jsonPathValue);
		}
	} catch (PathNotFoundException e) {
		logger.debug("JPath not found " + jsonPathValue);
	}

	return res;
}
 
Example #7
Source File: CloudTrailEventSupport.java    From fullstop with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the given 'responseElements' and extracts information based on given 'pattern'.<br/>
 * If 'responseElements' is null or empty you can handle the {@link IllegalArgumentException} raised or got an empty
 * list.
 */
public static List<String> read(final String responseElements, final String pattern,
                                final boolean emptyListOnNullOrEmptyResponse) {
    if (isNullOrEmpty(responseElements) && emptyListOnNullOrEmptyResponse) {
        return emptyList();
    }

    try {
        return JsonPath.read(responseElements, pattern);
    } catch (final PathNotFoundException e) {
        if (emptyListOnNullOrEmptyResponse) {
            return emptyList();
        } else {
            throw e;
        }
    }
}
 
Example #8
Source File: JSONRecordFactory.java    From rmlmapper-java with MIT License 6 votes vote down vote up
/**
 * This method returns the records from a JSON document based on an iterator.
 * @param document the document from which records need to get.
 * @param iterator the used iterator.
 * @return a list of records.
 * @throws IOException
 */
@Override
List<Record> getRecordsFromDocument(Object document, String iterator) throws IOException {
    List<Record> records = new ArrayList<>();

    Configuration conf = Configuration.builder()
            .options(Option.AS_PATH_LIST).build();

    try {
        List<String> pathList = JsonPath.using(conf).parse(document).read(iterator);

        for(String p :pathList) {
            records.add(new JSONRecord(document, p));
        }
    } catch(PathNotFoundException e) {
        logger.warn(e.getMessage(), e);
    }

    return records;
}
 
Example #9
Source File: JacksonJsonPathQuery.java    From camunda-spin with Apache License 2.0 6 votes vote down vote up
public SpinJsonNode element() {
  try {
    Object result = query.read(spinJsonNode.toString(), dataFormat.getJsonPathConfiguration());
    JsonNode node;
    if (result != null) {
      node = dataFormat.createJsonNode(result);
    } else {
      node = dataFormat.createNullJsonNode();
    }
    return dataFormat.createWrapperInstance(node);
  } catch(PathNotFoundException pex) {
    throw LOG.unableToEvaluateJsonPathExpressionOnNode(spinJsonNode, pex);
  } catch (ClassCastException cex) {
    throw LOG.unableToCastJsonPathResultTo(SpinJsonNode.class, cex);
  } catch(InvalidPathException iex) {
    throw LOG.invalidJsonPath(SpinJsonNode.class, iex);
  }
}
 
Example #10
Source File: SqlJsonFunctionsTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testJsonApiCommonSyntax() {
  assertJsonApiCommonSyntax("{\"foo\": \"bar\"}", "$.foo",
      contextMatches(
          JsonFunctions.JsonPathContext.withJavaObj(JsonFunctions.PathMode.STRICT, "bar")));
  assertJsonApiCommonSyntax("{\"foo\": \"bar\"}", "lax $.foo",
      contextMatches(
          JsonFunctions.JsonPathContext.withJavaObj(JsonFunctions.PathMode.LAX, "bar")));
  assertJsonApiCommonSyntax("{\"foo\": \"bar\"}", "strict $.foo",
      contextMatches(
          JsonFunctions.JsonPathContext.withJavaObj(JsonFunctions.PathMode.STRICT, "bar")));
  assertJsonApiCommonSyntax("{\"foo\": \"bar\"}", "lax $.foo1",
      contextMatches(
          JsonFunctions.JsonPathContext.withJavaObj(JsonFunctions.PathMode.LAX, null)));
  assertJsonApiCommonSyntax("{\"foo\": \"bar\"}", "strict $.foo1",
      contextMatches(
          JsonFunctions.JsonPathContext.withStrictException(
              new PathNotFoundException("No results for path: $['foo1']"))));
  assertJsonApiCommonSyntax("{\"foo\": 100}", "lax $.foo",
      contextMatches(
          JsonFunctions.JsonPathContext.withJavaObj(JsonFunctions.PathMode.LAX, 100)));
}
 
Example #11
Source File: JsonPathEvaluator.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public QueryResult<String> evaluate(EvaluationContext context) {
    DocumentContext documentContext = getDocumentContext(context);

    final JsonPath compiledJsonPath = getJsonPath(context);

    Object result = null;
    try {
        result = documentContext.read(compiledJsonPath);
    } catch (PathNotFoundException pnf) {
        // it is valid for a path not to be found, keys may not be there
        // do not spam the error log for this, instead we can log debug if enabled
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("PathNotFoundException for JsonPath " + compiledJsonPath.getPath(), pnf);
        }
        return EMPTY_RESULT;
    } catch (Exception e) {
        // a failure for something *other* than path not found however, should at least be
        // logged.
        LOGGER.error("Exception while reading JsonPath " + compiledJsonPath.getPath(), e);
        return EMPTY_RESULT;
    }

    return new StringQueryResult(getResultRepresentation(result, EMPTY_RESULT.getValue()));
}
 
Example #12
Source File: TestSimpleXJoinResultsFactory.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Test(expected=PathNotFoundException.class)
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNoJoinIdsAtPath() throws IOException {
  NamedList args = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_TYPE, SimpleXJoinResultsFactory.Type.JSON.toString());
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_ROOT_URL, getClass().getResource("results.json").toString());
  
  NamedList globalPaths = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_GLOBAL_FIELD_PATHS, globalPaths);
  globalPaths.add("total", "$.count");
  
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_JOIN_ID_PATH, "$.no.ids.at.this.path");
  
  SimpleXJoinResultsFactory factory = new SimpleXJoinResultsFactory();
  factory.init(args);
  
  SolrParams params = new ModifiableSolrParams();
  XJoinResults<String> results = factory.getResults(params);
  
  assertEquals(0, IteratorUtils.toArray(results.getJoinIds().iterator()).length);
}
 
Example #13
Source File: TestSimpleXJoinResultsFactory.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Test(expected=PathNotFoundException.class)
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNoJoinIdsAtPath() throws IOException {
  NamedList args = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_TYPE, SimpleXJoinResultsFactory.Type.JSON.toString());
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_ROOT_URL, getClass().getResource("results.json").toString());
  
  NamedList globalPaths = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_GLOBAL_FIELD_PATHS, globalPaths);
  globalPaths.add("total", "$.count");
  
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_JOIN_ID_PATH, "$.no.ids.at.this.path");
  
  SimpleXJoinResultsFactory factory = new SimpleXJoinResultsFactory();
  factory.init(args);
  
  SolrParams params = new ModifiableSolrParams();
  XJoinResults<String> results = factory.getResults(params);
  
  assertEquals(0, IteratorUtils.toArray(results.getJoinIds().iterator()).length);
}
 
Example #14
Source File: SqlJsonFunctionsTest.java    From Quicksql with MIT License 6 votes vote down vote up
@Test public void testJsonApiCommonSyntax() {
  assertJsonApiCommonSyntax("{\"foo\": \"bar\"}", "lax $.foo",
      contextMatches(
          JsonFunctions.JsonPathContext.withJavaObj(JsonFunctions.PathMode.LAX, "bar")));
  assertJsonApiCommonSyntax("{\"foo\": \"bar\"}", "strict $.foo",
      contextMatches(
          JsonFunctions.JsonPathContext.withJavaObj(JsonFunctions.PathMode.STRICT, "bar")));
  assertJsonApiCommonSyntax("{\"foo\": \"bar\"}", "lax $.foo1",
      contextMatches(
          JsonFunctions.JsonPathContext.withJavaObj(JsonFunctions.PathMode.LAX, null)));
  assertJsonApiCommonSyntax("{\"foo\": \"bar\"}", "strict $.foo1",
      contextMatches(
          JsonFunctions.JsonPathContext.withStrictException(
              new PathNotFoundException("No results for path: $['foo1']"))));
  assertJsonApiCommonSyntax("{\"foo\": 100}", "lax $.foo",
      contextMatches(
          JsonFunctions.JsonPathContext.withJavaObj(JsonFunctions.PathMode.LAX, 100)));
}
 
Example #15
Source File: TestSimpleXJoinResultsFactory.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Test(expected=PathNotFoundException.class)
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNoJoinIdsAtPath() throws IOException {
  NamedList args = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_TYPE, SimpleXJoinResultsFactory.Type.JSON.toString());
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_ROOT_URL, getClass().getResource("results.json").toString());
  
  NamedList globalPaths = new NamedList();
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_GLOBAL_FIELD_PATHS, globalPaths);
  globalPaths.add("total", "$.count");
  
  args.add(SimpleXJoinResultsFactory.INIT_PARAM_JOIN_ID_PATH, "$.no.ids.at.this.path");
  
  SimpleXJoinResultsFactory factory = new SimpleXJoinResultsFactory();
  factory.init(args);
  
  SolrParams params = new ModifiableSolrParams();
  XJoinResults<String> results = factory.getResults(params);
  
  assertEquals(0, IteratorUtils.toArray(results.getJoinIds().iterator()).length);
}
 
Example #16
Source File: SimpleAPIHotProcessor.java    From hot-crawler with MIT License 6 votes vote down vote up
@Override
protected List<Info> getInfoDataByJson(String json) {
    List<Info> infoList = new ArrayList<>();
    if (json != null && checkJsonPathList(this.titleJsonPaths, this.urlJsonPaths)){
        for (int i = 0; i < titleJsonPaths.size(); i++){
            try {
                List<String> titles = JsonPath.read(json, this.titleJsonPaths.get(i));
                List<String> urls = JsonPath.read(json, this.urlJsonPaths.get(i));
                infoList.addAll(getInfoListByTitlesAndUrls(titles, urls));
            }catch(PathNotFoundException e){
                log.error("Json path error!", e);
            }
        }
    }
    return infoList;
}
 
Example #17
Source File: RequesterUtils.java    From AuTe-Framework with Apache License 2.0 6 votes vote down vote up
static boolean tryUsePolling(Step step, ClientResponse clientResponse) {
    Assert.notNull(clientResponse, "client response must not be null");
    String content = clientResponse.getContent();
    log.debug("trying use polling {} {}", step, content);
    if (!step.getUsePolling()) {
        return false;
    }
    boolean retry = true;
    try {
        if (checkByJsonPath(content, step)) {
            log.info("Required attribute for polling found in path {}. Stop polling", step.getPollingJsonXPath());
            retry = false;
        }
    } catch (PathNotFoundException | IllegalArgumentException e) {
        log.info("Required attribute for polling not found in path {}. Continue polling", step.getPollingJsonXPath());
        retry = true;
    }
    log.debug("trying use polling? Is - {}", retry);
    return retry;
}
 
Example #18
Source File: KibanaUtils.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
private String getDefaultFromContent(String content, String defaultIfNotSet) {
    try {
        String value = defaultPath.read(content);
        return StringUtils.isNotEmpty(value) ? value : defaultIfNotSet;
    }catch(PathNotFoundException e) {
        return defaultIfNotSet;
    }
}
 
Example #19
Source File: HalActuatorEndpointsDiscoverer.java    From microservices-dashboard with Apache License 2.0 5 votes vote down vote up
private Links createLinksFrom(String body, MediaType mediaType) {
	Links links = new Links();
	try {
		Object parseResult = JsonPath.read(body, LINK_PATH);

		if (parseResult instanceof Map) {
			Set<String> rels = ((Map<String, Object>) parseResult).keySet();
			links = extractActuatorEndpoints(body, mediaType, rels);
		}
	}
	catch (PathNotFoundException pnfe) {
		logger.debug("{} not found in response", LINK_PATH, pnfe);
	}
	return links;
}
 
Example #20
Source File: KafkaProducerHelper.java    From zerocode with Apache License 2.0 5 votes vote down vote up
public static String readRecordType(String requestJson, String jsonPath) {
    try {
        return JsonPath.read(requestJson, jsonPath);
    } catch (PathNotFoundException pEx) {
        LOGGER.warn("Could not find path '" + jsonPath + "' in the request. returned default type 'RAW'.");
        return RAW;
    }
}
 
Example #21
Source File: HelperJsonUtils.java    From zerocode with Apache License 2.0 5 votes vote down vote up
public static Object readJsonPathOrElseNull(String requestJson, String jsonPath) {
    try {
        return JsonPath.read(requestJson, jsonPath);
    } catch (PathNotFoundException pEx) {
        LOGGER.debug("No " + jsonPath + " was present in the request. returned null.");
        return null;
    }
}
 
Example #22
Source File: HttpApiExecutorImpl.java    From zerocode with Apache License 2.0 5 votes vote down vote up
private Object readJsonPathOrElseNull(String requestJson, String jsonPath) {
    try {
        return JsonPath.read(requestJson, jsonPath);
    } catch (PathNotFoundException pEx) {
        LOGGER.debug("No " + jsonPath + " was present in the request. returned null.");
        return null;
    }
}
 
Example #23
Source File: ContextMatcher.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private Object findObjectValue(String contextObjectAsJson) {
    try {
        return JsonPath.parse(contextObjectAsJson).read(object.getObjectKeyPath());
    } catch (PathNotFoundException e) {
        return null;
    }
}
 
Example #24
Source File: JsonResponseValidationStepsTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
private void verifyPathNotFoundExceptionRecording(String nonExistingJsonPath)
{
    verify(softAssert).recordFailedAssertion((Exception) argThat(
        arg -> arg instanceof PathNotFoundException && ("No results for path: " + nonExistingJsonPath)
                .equals(((PathNotFoundException) arg).getMessage())));
    verifyNoMoreInteractions(softAssert);
}
 
Example #25
Source File: JsonBodyVerificationBuilder.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private static Object retrieveObjectByPath(Object body, String path) {
	try {
		return JsonPath.parse(body).read(path);
	}
	catch (PathNotFoundException e) {
		throw new IllegalStateException("Entry for the provided JSON path <" + path
				+ "> doesn't exist in the body <" + JsonOutput.toJson(body) + ">", e);
	}
}
 
Example #26
Source File: UDPMessageEncoderTest.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
static <T> T tryRead(String json, String jsonPath) {
  try {
    return JsonPath.compile(jsonPath).read(json);
  } catch (PathNotFoundException e) {
    return null;
  }
}
 
Example #27
Source File: JsonFunctionsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMissingPathIsNullOrThrows(){
    try {
        // TODO is there a way to force this to return null if not found?
        // for me (Alex) it throws but for others it seems to return null
        Object obj = JsonFunctions.getPath("$.europe.spain.malaga").apply(europeMap());
        Assert.assertNull(obj);
    } catch (PathNotFoundException e) {
        // not unexpected
    }
}
 
Example #28
Source File: JsonPathHelper.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
public String updateJsonPathWithValue(String json, String jsonPath, Object value) {
    if(null != getJsonPath(json, jsonPath)) {
        return parseJson(json).set(jsonPath, value).jsonString();
    } else {
        throw new PathNotFoundException("No result for: " + jsonPath + " IN: " + json);
    }
}
 
Example #29
Source File: ApiSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * В json строке, сохраннённой в переменной, происходит поиск значений по jsonpath из первого столбца таблицы.
 * Полученные значения сравниваются с ожидаемым значением во втором столбце таблицы.
 * Шаг работает со всеми типами json элементов: объекты, массивы, строки, числа, литералы true, false и null.
 */
@Тогда("^в json (?:строке|файле) \"([^\"]*)\" значения, найденные по jsonpath, равны значениям из таблицы$")
@Then("^values from json (?:string|file) named \"([^\"]*)\" found via jsonpath are equal to the values from the table$")
public void checkValuesInJsonAsString(String jsonVar, DataTable dataTable) {
    String strJson = loadValueFromFileOrPropertyOrVariableOrDefault(jsonVar);
    Gson gsonObject = new Gson();
    JsonParser parser = new JsonParser();
    ReadContext ctx = JsonPath.parse(strJson, createJsonPathConfiguration());
    boolean error = false;
    for (List<String> row : dataTable.raw()) {
        String jsonPath = row.get(0);
        JsonElement actualJsonElement;
        try {
            actualJsonElement = gsonObject.toJsonTree(ctx.read(jsonPath));
        } catch (PathNotFoundException e) {
            error = true;
            continue;
        }
        JsonElement expectedJsonElement = parser.parse(row.get(1));
        if (!actualJsonElement.equals(expectedJsonElement)) {
            error = true;
        }
        akitaScenario.write("JsonPath: " + jsonPath + ", ожидаемое значение: " + expectedJsonElement + ", фактическое значение: " + actualJsonElement);
    }
    if (error)
        throw new RuntimeException("Ожидаемые и фактические значения в json не совпадают");
}
 
Example #30
Source File: JsonResponseValidationSteps.java    From vividus with Apache License 2.0 5 votes vote down vote up
private <T> Optional<Optional<T>> getDataByJsonPathSafely(String json, String jsonPath, boolean recordFail)
{
    try
    {
        return Optional.of(Optional.ofNullable(JsonPathUtils.getData(json, jsonPath)));
    }
    catch (PathNotFoundException e)
    {
        if (recordFail)
        {
            softAssert.recordFailedAssertion(e);
        }
        return Optional.empty();
    }
}