Java Code Examples for com.fasterxml.jackson.databind.JsonNode#path()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#path() . 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: FeatureDecoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
protected List<AbstractFeature> parseSampledFeatures(JsonNode node)
        throws DecodingException {
    final JsonNode sfnode = node.path(JSONConstants.SAMPLED_FEATURE);
    if (sfnode.isArray()) {
        ArrayList<AbstractFeature> features = new ArrayList<>(sfnode.size());
        for (JsonNode n : sfnode) {
            features.add(parseSamplingFeature(n));
        }
        return features;
    } else {
        final SamplingFeature sff = parseSamplingFeature(sfnode);
        if (sff == null) {
            return Collections.emptyList();
        } else {
            return Collections.<AbstractFeature> singletonList(sff);
        }
    }
}
 
Example 2
Source File: MonitoringExportService.java    From support-diagnostics with Apache License 2.0 6 votes vote down vote up
private void validateClusterId(String clusterId, MonitoringExportConfig config, RestClient client, String monitoringUri) {
    String clusterIdQuery = config.queries.get("cluster_id_check");
    clusterIdQuery = clusterIdQuery.replace("{{clusterId}}", clusterId);

    RestResult restResult = new RestResult(client.execPost(monitoringUri, clusterIdQuery), monitoringUri);
    if (restResult.getStatus() != 200) {
        logger.error(Constants.CONSOLE,  "Cluster Id validation failed with status: {}, reason: {}.", restResult.getStatus(), restResult.getReason());
        throw new DiagnosticException("clusterQueryError");
    }

    JsonNode nodeResult = JsonYamlUtils.createJsonNodeFromString(restResult.toString());
    JsonNode hitsNode = nodeResult.path("hits");
    long hitCount = hitsNode.path("total").asLong(0);
    if (hitCount <= 0) {
        throw new DiagnosticException("noClusterIdFound");
    }

}
 
Example 3
Source File: AnnotationApiConfigGeneratorTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private void verifyEndpoint3Schema(JsonNode root) {
  JsonNode schemas = root.path("descriptor").path("schemas");
  JsonNode foo = schemas.path("Bar");
  verifyObjectSchema(foo, "Bar", "object");
  verifyObjectPropertySchema(foo, "name", "string");
  verifyObjectPropertySchema(foo, "value", "integer");
  JsonNode foos = schemas.path("BarCollection");
  verifyArraySchemaRef(foos.path("properties").path("items"), "Bar");

  verifyEmptyMethodRequest(root, Endpoint3.class.getName() + ".listBars");
  verifyMethodResponseRef(root, Endpoint3.class.getName() + ".listBars", "BarCollection");
  verifyEmptyMethodRequest(root, Endpoint3.class.getName() + ".getBar");
  verifyMethodResponseRef(root, Endpoint3.class.getName() + ".getBar", "Bar");
  verifyMethodRequestRef(root, Endpoint3.class.getName() + ".insertBar", "Bar");
  verifyMethodResponseRef(root, Endpoint3.class.getName() + ".insertBar", "Bar");
  verifyMethodRequestRef(root, Endpoint3.class.getName() + ".updateBar", "Bar");
  verifyMethodResponseRef(root, Endpoint3.class.getName() + ".updateBar", "Bar");
  verifyEmptyMethodRequest(root, Endpoint3.class.getName() + ".removeBar");
  verifyEmptyMethodResponse(root, Endpoint3.class.getName() + ".removeBar");
}
 
Example 4
Source File: RelatedPartyJSONDecoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@Override
public RelatedParty decodeJSON(JsonNode node, boolean validate)
        throws DecodingException {
    RelatedParty relatedParty = new RelatedParty();
    relatedParty.setContact(decodeJsonToNillable(node.path(AQDJSONConstants.CONTACT), Contact.class));
    relatedParty.setIndividualName(
            parseNillable(node.path(AQDJSONConstants.INDIVIDUAL_NAME)).map(this::parseFreeText));
    relatedParty.setOrganisationName(
            parseNillable(node.path(AQDJSONConstants.ORGANISATION_NAME)).map(this::parseFreeText));
    relatedParty.setPositionName(
            parseNillable(node.path(AQDJSONConstants.POSITION_NAME)).map(this::parseFreeText));
    for (JsonNode n : node.path(AQDJSONConstants.ROLES)) {
        relatedParty.addRole(parseNillableReference(n));
    }
    return relatedParty;
}
 
Example 5
Source File: ContentFormatters.java    From template-compiler with Apache License 2.0 6 votes vote down vote up
private static String getAltTextFromContentItem(JsonNode contentItemNode) {
  JsonNode title = contentItemNode.path("title");
  if (isTruthy(title)) {
    return title.asText();
  }

  JsonNode body = contentItemNode.path("body");
  if (isTruthy(body)) {
    String text = PluginUtils.removeTags(body.asText());
    if (text.length() > 0) {
      return text;
    }
  }

  JsonNode filename = contentItemNode.path("filename");
  if (isTruthy(filename)) {
    return filename.asText();
  }

  return "";
}
 
Example 6
Source File: RdbEventRecordHandler.java    From DataLink with Apache License 2.0 5 votes vote down vote up
private void handleResult(String response, List<JsonNode> nothingUpdatedActionList,
                          List<JsonNode> explicitErrorActionList) {
    JsonNode json = JsonUtils.parse(response);
    if (!json.path("errors").asBoolean()) {
        if (!(json.path("errors") instanceof BooleanNode)) {
            LOGGER.error("@@@@@@@@ this is a node " + json.path("errors").toString());
            LOGGER.error("######## this is a error " + json.toString());
            LOGGER.error("======== this is a error " + response);
        }
        return;
    }

    for (JsonNode action : json.path("items")) {
        if (action.path("index").hasNonNull("error")) {
            // 写入失败
            explicitErrorActionList.add(action.path("index"));
        } else if (action.path("update").hasNonNull("error")) {
            // 更新失败
            int status = action.path("update").path("status").asInt();
            if (status == 404) {
                // 0 rows affected, 这种错误以写入模式重试
                nothingUpdatedActionList.add(action.path("update"));
            } else {
                explicitErrorActionList.add(action.path("update"));
            }
        }
    }
}
 
Example 7
Source File: ContentFormatters.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
private static void outputImageMeta(JsonNode image, StringBuilder buf, String preferredAltText) {
  if (image.isMissingNode()) {
    return;
  }

  JsonNode componentKey = image.path("componentKey");
  String focalPoint = getFocalPoint(image);
  String origSize = image.path("originalSize").asText();
  String assetUrl = image.path("assetUrl").asText();

  String altText = preferredAltText != null ? preferredAltText : getAltTextFromContentItem(image);

  if (isLicensedAssetPreview(image)) {
    buf.append("data-licensed-asset-preview=\"true\" ");
  }

  if (!componentKey.isMissingNode()) {
    buf.append("data-component-key=\"").append(componentKey.asText()).append("\" ");
  }

  buf.append("data-src=\"").append(assetUrl).append("\" ");
  buf.append("data-image=\"").append(assetUrl).append("\" ");
  buf.append("data-image-dimensions=\"").append(origSize).append("\" ");
  buf.append("data-image-focal-point=\"").append(focalPoint).append("\" ");
  buf.append("alt=\"");
  PluginUtils.escapeHtmlAttribute(altText, buf);
  buf.append("\" ");
}
 
Example 8
Source File: Group.java    From TinCanJava with Apache License 2.0 5 votes vote down vote up
public Group(JsonNode jsonNode) {
    super(jsonNode);
    
    JsonNode memberNode = jsonNode.path("member");
    if (! memberNode.isMissingNode()) {
        this.members = new ArrayList<Agent>();
        Iterator it = memberNode.elements();
        while(it.hasNext()) {
            this.members.add(Agent.fromJson((JsonNode) it.next()));
        }
    }
}
 
Example 9
Source File: AnnotationApiConfigGeneratorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndpointWithNoPublicMethods() throws Exception {
  String apiConfigSource = g.generateConfig(Endpoint2.class).get("myapi-v1.api");

  JsonNode root = objectMapper.readValue(apiConfigSource, JsonNode.class);

  JsonNode methods = root.path("methods");
  assertNull(methods.findValue("api2.foos.invisible0"));
  assertNull(methods.findValue("api2.foos.invisible1"));
}
 
Example 10
Source File: TestOpticOnTriples.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnionWithWhereDistinct() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
  System.out.println("In testUnionWithWhereDistinct method");

  // Create a new Plan.
  RowManager rowMgr = client.newRowManager();
  PlanBuilder p = rowMgr.newPlanBuilder();
  PlanPrefixer players = p.prefixer("http://marklogic.com/baseball/players");
  PlanPrefixer team = p.prefixer("http://marklogic.com/mlb/team/");

  PlanColumn playerAgeCol = p.col("player_age");
  PlanColumn playerIdCol = p.col("player_id");
  PlanColumn playerNameCol = p.col("player_name");
  PlanColumn playerTeamCol = p.col("player_team");
  PlanColumn teamIdCol = p.col("team_id");
  PlanColumn teamNameCol = p.col("team_name");
  PlanColumn teamCityCol = p.col("team_city");
  ModifyPlan player_plan = p.fromTriples(
      p.pattern(playerIdCol, players.iri("age"), playerAgeCol),
      p.pattern(playerIdCol, players.iri("name"), playerNameCol),
      p.pattern(playerIdCol, players.iri("team"), playerTeamCol)
      );
  ModifyPlan team_plan = p.fromTriples(
      p.pattern(teamIdCol, team.iri("name"), teamNameCol),
      p.pattern(teamIdCol, team.iri("city"), teamCityCol)
      );
  ModifyPlan output = player_plan.union(team_plan)
      .whereDistinct();
  JacksonHandle jacksonHandle = new JacksonHandle();
  jacksonHandle.setMimetype("application/json");

  rowMgr.resultDoc(output, jacksonHandle);
  JsonNode jsonResults = jacksonHandle.get();
  JsonNode jsonBindingsNodes = jsonResults.path("rows");
  // Should have 13 nodes returned.
  assertEquals("Thirteen nodes not returned from testUnionWithWhereDistinct method ", 13, jsonBindingsNodes.size());
}
 
Example 11
Source File: JsonRowDecoder.java    From presto with Apache License 2.0 5 votes vote down vote up
private static JsonNode locateNode(JsonNode tree, DecoderColumnHandle columnHandle)
{
    String mapping = columnHandle.getMapping();
    checkState(mapping != null, "No mapping for %s", columnHandle.getName());

    JsonNode currentNode = tree;
    for (String pathElement : Splitter.on('/').omitEmptyStrings().split(mapping)) {
        if (!currentNode.has(pathElement)) {
            return MissingNode.getInstance();
        }
        currentNode = currentNode.path(pathElement);
    }
    return currentNode;
}
 
Example 12
Source File: Agent.java    From TinCanJava with Apache License 2.0 5 votes vote down vote up
protected Agent(JsonNode jsonNode) {
    this();

    JsonNode nameNode = jsonNode.path("name");
    if (! nameNode.isMissingNode()) {
        this.setName(nameNode.textValue());
    }

    JsonNode mboxNode = jsonNode.path("mbox");
    if (! mboxNode.isMissingNode()) {
        this.setMbox(mboxNode.textValue());
    }

    JsonNode mboxSHA1SumNode = jsonNode.path("mbox_sha1sum");
    if (! mboxSHA1SumNode.isMissingNode()) {
        this.setMboxSHA1Sum(mboxSHA1SumNode.textValue());
    }

    JsonNode openIDNode = jsonNode.path("openid");
    if (! openIDNode.isMissingNode()) {
        this.setOpenID(openIDNode.textValue());
    }

    JsonNode acctNode = jsonNode.path("account");
    if (! acctNode.isMissingNode()) {
        this.setAccount(new AgentAccount(acctNode));
    }
}
 
Example 13
Source File: TestOpticOnViews.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
@Test
public void testjoinInnerGroupBy() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
  System.out.println("In testjoinInnerGroupBy method");
  RowManager rowMgr = client.newRowManager();
  PlanBuilder p = rowMgr.newPlanBuilder();
  ModifyPlan plan1 = p.fromView("opticFunctionalTest", "detail")
      .orderBy(p.col( "id"));
  ModifyPlan plan2 = p.fromView("opticFunctionalTest", "master")
      .orderBy(p.schemaCol("opticFunctionalTest", "master", "id"));
  ModifyPlan plan3 = plan1.joinInner(plan2)
      .where(
          p.eq(
              p.schemaCol("opticFunctionalTest", "master", "id"),
              p.col( "masterId")
              )
      )
      .groupBy(p.schemaCol("opticFunctionalTest", "master", "name"), p.sum(p.col("DetailSum"), p.col( "amount")))
      .orderBy(p.desc(p.col("DetailSum")));
  JacksonHandle jacksonHandle = new JacksonHandle();
  jacksonHandle.setMimetype("application/json");

  rowMgr.resultDoc(plan3, jacksonHandle);
  JsonNode jsonResults = jacksonHandle.get();
  JsonNode jsonBindingsNodes = jsonResults.path("rows");
  // Should have 2 nodes returned.
  assertEquals("Two nodes not returned from testjoinInnerGroupBy method ", 2, jsonBindingsNodes.size());
  // Verify first node.
  JsonNode first = jsonBindingsNodes.path(0);

  assertEquals("Element 1 opticFunctionalTest.master.name value incorrect", "Master 2", first.path("opticFunctionalTest.master.name").path("value").asText());
  assertEquals("Element 1 DetailSum value incorrect", "120.12", first.path("DetailSum").path("value").asText());
  // Verify second node.
  JsonNode second = jsonBindingsNodes.path(1);
  assertEquals("Element 2 opticFunctionalTest.master.name value incorrect", "Master 1", second.path("opticFunctionalTest.master.name").path("value").asText());
  assertEquals("Element 2 DetailSum value incorrect", "90.09", second.path("DetailSum").path("value").asText());
}
 
Example 14
Source File: ContentPredicates.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
@Override
public boolean apply(Context ctx, Arguments args) throws CodeExecuteException {
  JsonNode excerpt = ctx.node().path("excerpt");
  JsonNode html = excerpt.path("html");
  String text = "";
  if (html.isTextual()) {
    text = html.asText();
  } else if (excerpt.isTextual()) {
    text = excerpt.asText();
  }
  text = PluginUtils.removeTags(text);
  text = Patterns.WHITESPACE_NBSP.matcher(text).replaceAll("");
  return text.length() > 0;
}
 
Example 15
Source File: ApiConnection.java    From Wikidata-Toolkit with Apache License 2.0 4 votes vote down vote up
/**
 * Extracts warnings that are returned in an API response.
 *
 * @param root
 *            root node of the JSON result
 */
List<String> getWarnings(JsonNode root) {
	ArrayList<String> warnings = new ArrayList<>();

	if (root.has("warnings")) {
		JsonNode warningNode = root.path("warnings");
		Iterator<Map.Entry<String, JsonNode>> moduleIterator = warningNode
				.fields();
		while (moduleIterator.hasNext()) {
			Map.Entry<String, JsonNode> moduleNode = moduleIterator.next();
			Iterator<JsonNode> moduleOutputIterator = moduleNode.getValue()
					.elements();
			while (moduleOutputIterator.hasNext()) {
				JsonNode moduleOutputNode = moduleOutputIterator.next();
				if (moduleOutputNode.isTextual()) {
					warnings.add("[" + moduleNode.getKey() + "]: "
							+ moduleOutputNode.textValue());
				} else if (moduleOutputNode.isArray()) {
					Iterator<JsonNode> messageIterator = moduleOutputNode
							.elements();
					while (messageIterator.hasNext()) {
						JsonNode messageNode = messageIterator.next();
						warnings.add("["
								+ moduleNode.getKey()
								+ "]: "
								+ messageNode.path("html").path("*")
										.asText(messageNode.toString()));
					}
				} else {
					warnings.add("["
							+ moduleNode.getKey()
							+ "]: "
							+ "Warning was not understood. Please report this to Wikidata Toolkit. JSON source: "
							+ moduleOutputNode.toString());
				}
			}

		}
	}

	return warnings;
}
 
Example 16
Source File: PinpointWebSocketMessageConverter.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
private PinpointWebSocketMessage readSend(JsonNode root) throws JsonProcessingException {
    String command = root.path(COMMAND).asText();
    JsonNode resultNode = root.path(PARAMETERS);
    Map parameterMap = readMap(resultNode);
    return new SendMessage(command, parameterMap);
}
 
Example 17
Source File: TestOpticOnLexicons.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Test
public void testRestrictedXPathPredicateMath() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
  System.out.println("In testRestrictedXPathPredicateMath method");

  // Create a new Plan.
  RowManager rowMgr = client.newRowManager();
  PlanBuilder p = rowMgr.newPlanBuilder();

  Map<String, CtsReferenceExpr> index1 = new HashMap<String, CtsReferenceExpr>();
  index1.put("uri1", p.cts.uriReference());
  index1.put("city", p.cts.jsonPropertyReference("city"));
  index1.put("popularity", p.cts.jsonPropertyReference("popularity"));
  index1.put("date", p.cts.jsonPropertyReference("date"));
  index1.put("distance", p.cts.jsonPropertyReference("distance"));
  index1.put("point", p.cts.jsonPropertyReference("latLonPoint"));

  Map<String, CtsReferenceExpr> index2 = new HashMap<String, CtsReferenceExpr>();
  index2.put("uri2", p.cts.uriReference());
  index2.put("cityName", p.cts.jsonPropertyReference("cityName"));
  index2.put("cityTeam", p.cts.jsonPropertyReference("cityTeam"));

  // plan1
  ModifyPlan plan1 = p.fromLexicons(index1, "myCity");
  ModifyPlan plan2 = p.fromLexicons(index2, "myTeam");
  
  PlanColumn uriCol1 = p.col("uri1");
  PlanColumn cityCol = p.col("city");
  PlanColumn popCol = p.col("popularity");
  PlanColumn dateCol = p.col("date");
  PlanColumn distCol = p.col("distance");
  PlanColumn pointCol = p.col("point");
  PlanColumn uriCol2 = p.col("uri2");

  PlanColumn cityNameCol = p.col("cityName");
  PlanColumn cityTeamCol = p.col("cityTeam");
  
  ModifyPlan UnnamedNodes = plan1.joinInner(plan2, 
            p.on(p.viewCol("myCity", "city"), p.viewCol("myTeam", "cityName")),
            p.ne(p.col("popularity"), p.xs.intVal(3)))
          .joinDoc(p.col("doc"), p.col("uri1"))            
          .select(uriCol1, cityCol, popCol, dateCol, distCol, pointCol, p.as("nodes", p.xpath("doc", "popularity[math:pow(., 2) eq 4]")), uriCol2, cityNameCol, cityTeamCol)
          .where(p.isDefined(p.col("nodes")))
          .orderBy(p.desc(p.col("distance")));
  
  JacksonHandle jacksonHandle = new JacksonHandle();
  jacksonHandle.setMimetype("application/json");

  rowMgr.resultDoc(UnnamedNodes, jacksonHandle);
  JsonNode jsonResults = jacksonHandle.get();
  JsonNode jsonBindingsNodes = jsonResults.path("rows");    
  // Should have 1 node returned.
  assertEquals("One node not returned from testJoinInnerKeymatchDateSort method ", 1, jsonBindingsNodes.size());
  JsonNode first = jsonBindingsNodes.path(0);
  assertEquals("Row 1 myCity.city value incorrect", "new jersey", first.path("myCity.city").path("value").asText());
}
 
Example 18
Source File: TestOpticOnViews.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Test
public void testjoinInnerWithBindParamsAsString() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
  System.out.println("In testjoinInnerWithBindParamsAsString method");
  RowManager rowMgr = client.newRowManager();
  PlanBuilder p = rowMgr.newPlanBuilder();
  ModifyPlan plan1 = p.fromView("opticFunctionalTest", "detail")
      .orderBy(p.schemaCol("opticFunctionalTest", "detail", "id"));
  ModifyPlan plan2 = p.fromView("opticFunctionalTest", "master")
      .orderBy(p.schemaCol("opticFunctionalTest", "master", "id"));
  PlanParamExpr idParam = p.param("ID");
  ModifyPlan plan3 = plan1.joinInner(plan2)
      .where(
          p.eq(p.schemaCol("opticFunctionalTest", "master", "id"), idParam)
      )
      .orderBy(p.asc(p.schemaCol("opticFunctionalTest", "detail", "id")));
  JacksonHandle jacksonHandle = new JacksonHandle();
  jacksonHandle.setMimetype("application/json");

  rowMgr.resultDoc(plan3.bindParam("ID", 1), jacksonHandle);
  JsonNode jsonResults = jacksonHandle.get();
  JsonNode jsonBindingsNodes = jsonResults.path("rows");
  // Should have 6 nodes returned.
  assertEquals("Six nodes not returned from testjoinInnerWithBind method ", 6, jsonBindingsNodes.size());
  // Verify first node.
  JsonNode first = jsonBindingsNodes.path(0);

  assertEquals("Row 1 opticFunctionalTest.detail.id value incorrect", "1", first.path("opticFunctionalTest.detail.id").path("value").asText());
  assertEquals("Row 1 opticFunctionalTest.master.id value incorrect", "1", first.path("opticFunctionalTest.master.id").path("value").asText());
  assertEquals("Row 1 opticFunctionalTest.detail.masterId value incorrect", "1", first.path("opticFunctionalTest.detail.masterId").path("value").asText());
  assertEquals("Row 1 opticFunctionalTest.detail.name value incorrect", "Detail 1", first.path("opticFunctionalTest.detail.name").path("value").asText());

  // Verify sixth node.
  JsonNode sixth = jsonBindingsNodes.path(5);
  assertEquals("Row 6 opticFunctionalTest.detail.id value incorrect", "6", sixth.path("opticFunctionalTest.detail.id").path("value").asText());
  assertEquals("Row 6 opticFunctionalTest.master.id value incorrect", "1", sixth.path("opticFunctionalTest.master.id").path("value").asText());
  assertEquals("Row 6 opticFunctionalTest.detail.masterId value incorrect", "2", sixth.path("opticFunctionalTest.detail.masterId").path("value").asText());
  assertEquals("Row 6 opticFunctionalTest.detail.name value incorrect", "Detail 6", sixth.path("opticFunctionalTest.detail.name").path("value").asText());

  // Verify with negative value.
  jacksonHandle = new JacksonHandle();
  jacksonHandle.setMimetype("application/json");
  rowMgr.resultDoc(plan3.bindParam("ID", -1), jacksonHandle);
  jsonResults = jacksonHandle.get();
  // Should have null returned.
  assertTrue("No nodes should returned. But found some.", jsonResults == null);

  // Verify with double value.
  PlanParamExpr amtParam = p.param("AMT");
  ModifyPlan planAmt = p.fromView("opticFunctionalTest", "detail")
      .where(p.gt(p.col( "amount"), amtParam)
      )
      .orderBy(p.col( "id"));
  jacksonHandle = new JacksonHandle();
  jacksonHandle.setMimetype("application/json");
  rowMgr.resultDoc(planAmt.bindParam("AMT", 10.1), jacksonHandle);
  jsonResults = jacksonHandle.get().path("rows");
  // Should have 5 rows returned.
  assertEquals("Five rows not returned from testjoinInnerWithBind method ", 5, jsonResults.size());

  assertEquals("Row 1 opticFunctionalTest.detail.amount value incorrect", "20.02", jsonResults.path(0).path("opticFunctionalTest.detail.amount").path("value").asText());
  assertEquals("Row 2 opticFunctionalTest.detail.amount value incorrect", "30.03", jsonResults.path(1).path("opticFunctionalTest.detail.amount").path("value").asText());
  assertEquals("Row 3 opticFunctionalTest.detail.amount value incorrect", "40.04", jsonResults.path(2).path("opticFunctionalTest.detail.amount").path("value").asText());
  assertEquals("Row 4 opticFunctionalTest.detail.amount value incorrect", "50.05", jsonResults.path(3).path("opticFunctionalTest.detail.amount").path("value").asText());
  assertEquals("Row 5 opticFunctionalTest.detail.amount value incorrect", "60.06", jsonResults.path(4).path("opticFunctionalTest.detail.amount").path("value").asText());

  // verify for Strings.
  PlanParamExpr detNameParam = p.param("DETAILNAME");
  ModifyPlan planStringBind = p.fromView("opticFunctionalTest", "detail")
      .where(p.eq(p.col( "name"), detNameParam)
      )
      .orderBy(p.col( "id"));
  jacksonHandle = new JacksonHandle();
  jacksonHandle.setMimetype("application/json");
  rowMgr.resultDoc(planStringBind.bindParam(detNameParam, p.xs.string("Detail 6")), jacksonHandle);
  jsonResults = jacksonHandle.get().path("rows");
  assertEquals("One row not returned from testjoinInnerWithBind method ", 1, jsonResults.size());
  assertEquals("Row 1 opticFunctionalTest.detail.amount value incorrect", "60.06", jsonResults.path(0).path("opticFunctionalTest.detail.amount").path("value").asText());

  // Verify with different types in multiple places.
  ModifyPlan planMultiBind = p.fromView("opticFunctionalTest", "detail")
      .where(p.and(p.eq(p.col( "name"), detNameParam),
          p.eq(p.col( "id"), idParam)
          )
      )
      .orderBy(p.col( "id"));

  jacksonHandle = new JacksonHandle();
  jacksonHandle.setMimetype("application/json");
  rowMgr.resultDoc(planMultiBind.bindParam(detNameParam, p.xs.string("Detail 6")).bindParam("ID", 6), jacksonHandle);
  jsonResults = jacksonHandle.get().path("rows");
  // Should have 1 node returned.
  assertEquals("One row not returned from testjoinInnerWithBind method ", 1, jsonResults.size());
  assertEquals("Row 1 opticFunctionalTest.detail.amount value incorrect", "60.06", jsonResults.path(0).path("opticFunctionalTest.detail.amount").path("value").asText());
}
 
Example 19
Source File: TestOpticOnLexicons.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Test
public void testJoinDocURI() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
  System.out.println("In testJoinDocURI method");

  // Create a new Plan.
  RowManager rowMgr = client.newRowManager();
  PlanBuilder p = rowMgr.newPlanBuilder();
  Map<String, CtsReferenceExpr> index1 = new HashMap<String, CtsReferenceExpr>();
  index1.put("uri1", p.cts.uriReference());
  index1.put("city", p.cts.jsonPropertyReference("city"));
  index1.put("popularity", p.cts.jsonPropertyReference("popularity"));
  index1.put("date", p.cts.jsonPropertyReference("date"));
  index1.put("distance", p.cts.jsonPropertyReference("distance"));
  index1.put("point", p.cts.jsonPropertyReference("latLonPoint"));

  Map<String, CtsReferenceExpr> index2 = new HashMap<String, CtsReferenceExpr>();
  index2.put("uri2", p.cts.uriReference());
  index2.put("cityName", p.cts.jsonPropertyReference("cityName"));
  index2.put("cityTeam", p.cts.jsonPropertyReference("cityTeam"));

  ModifyPlan plan1 = p.fromLexicons(index1, "myCity", p.fragmentIdCol("fragId1"));
  ModifyPlan plan2 = p.fromLexicons(index2, "myTeam", p.fragmentIdCol("fragId2"));

  ExportablePlan output = plan1.joinInner(plan2)
      .where(p.eq(p.viewCol("myCity", "city"), p.col("cityName")))
      .joinDocUri(p.col("doc"), p.fragmentIdCol("fragId1"))
      .orderBy(p.asc(p.col("date")));
  JacksonHandle jacksonHandle = new JacksonHandle();
  jacksonHandle.setMimetype("application/json");

  rowMgr.resultDoc(output, jacksonHandle);
  JsonNode jsonResults = jacksonHandle.get();
  JsonNode jsonBindingsNodes = jsonResults.path("rows");
  // Should have 5 nodes returned.
  assertEquals("Five nodes not returned from testJoinInnerKeymatchDateSort method ", 5, jsonBindingsNodes.size());

  JsonNode node = jsonBindingsNodes.path(0);
  assertEquals("Row 1 myCity.city value incorrect", "new jersey", node.path("myCity.city").path("value").asText());
  assertEquals("Row 1 myCity.date value incorrect", "1971-12-23", node.path("myCity.date").path("value").asText());
  assertEquals("Row 1 myCity.distance value incorrect", "12.9", node.path("myCity.distance").path("value").asText());

  node = jsonBindingsNodes.path(1);
  assertEquals("Row 2 myCity.city value incorrect", "beijing", node.path("myCity.city").path("value").asText());
  assertEquals("Row 2 myCity.date value incorrect", "1981-11-09", node.path("myCity.date").path("value").asText());
  assertEquals("Row 2 myCity.distance value incorrect", "134.5", node.path("myCity.distance").path("value").asText());

  node = jsonBindingsNodes.path(4);
  assertEquals("Row 5 myCity.city value incorrect", "london", node.path("myCity.city").path("value").asText());
  assertEquals("Row 5 myCity.date value incorrect", "2007-01-01", node.path("myCity.date").path("value").asText());
  assertEquals("Row 5 myCity.distance value incorrect", "50.4", node.path("myCity.distance").path("value").asText());
}
 
Example 20
Source File: CommerceUtils.java    From template-compiler with Apache License 2.0 4 votes vote down vote up
public static ProductType getProductType(JsonNode item) {
  JsonNode structuredContent = item.path("structuredContent");
  JsonNode node = structuredContent.path("productType");
  return ProductType.fromCode(node.asInt());
}