com.fasterxml.jackson.databind.node.ArrayNode Java Examples

The following examples show how to use com.fasterxml.jackson.databind.node.ArrayNode. 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: BasicHostConfig.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the auxLocations of the host.
 *
 * @return auxLocations of the host or null if none specified
 * @throws IllegalArgumentException if auxLocations are set but empty or not
 *                                  specified with correct format
 */
public Set<HostLocation> auxLocations() {
    if (!object.has(AUX_LOCATIONS)) {
        return null; //no auxLocations are specified
    }

    ImmutableSet.Builder<HostLocation> auxLocationsSetBuilder = ImmutableSet.<HostLocation>builder();

    ArrayNode auxLocationNodes = (ArrayNode) object.path(AUX_LOCATIONS);
    auxLocationNodes.forEach(n -> {
        ConnectPoint cp = ConnectPoint.deviceConnectPoint((n.asText()));
        auxLocationsSetBuilder.add(new HostLocation(cp, 0));
    });

    return auxLocationsSetBuilder.build();
}
 
Example #2
Source File: ListGraphs.java    From constellation with Apache License 2.0 6 votes vote down vote up
@Override
public void callService(final PluginParameters parameters, final InputStream in, final OutputStream out) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final ArrayNode root = mapper.createArrayNode();
    final Map<String, Graph> graphs = GraphNode.getAllGraphs();
    graphs.entrySet().forEach(entry -> {
        final String id = entry.getKey();
        final Graph graph = entry.getValue();
        final ObjectNode obj = mapper.createObjectNode();
        obj.put("id", id);
        obj.put("name", GraphNode.getGraphNode(id).getDisplayName());
        final Schema schema = graph.getSchema();
        obj.put("schema", schema != null ? schema.getFactory().getName() : null);
        root.add(obj);
    });

    mapper.writeValue(out, root);
}
 
Example #3
Source File: ModelsResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void internalDeleteNodeByNameFromBPMNModel(JsonNode editorJsonNode, String propertyName) {
    JsonNode childShapesNode = editorJsonNode.get("childShapes");
    if (childShapesNode != null && childShapesNode.isArray()) {
        ArrayNode childShapesArrayNode = (ArrayNode) childShapesNode;
        for (JsonNode childShapeNode : childShapesArrayNode) {
            // Properties
            ObjectNode properties = (ObjectNode) childShapeNode.get("properties");
            if (properties != null && properties.has(propertyName)) {
                JsonNode propertyNode = properties.get(propertyName);
                if (propertyNode != null) {
                    properties.remove(propertyName);
                }
            }

            // Potential nested child shapes
            if (childShapeNode.has("childShapes")) {
                internalDeleteNodeByNameFromBPMNModel(childShapeNode, propertyName);
            }

        }
    }
}
 
Example #4
Source File: TestJacksonArrayFormatter.java    From yosegi with Apache License 2.0 6 votes vote down vote up
@Test
public void T_write_equalsSetValue_withNestingObjectFromParser() throws IOException {
  JacksonArrayFormatter formatter = new JacksonArrayFormatter();
  JsonNode node = formatter.writeParser( new TestParentParser( false ) );
  assertTrue( ( node instanceof ArrayNode ) );

  ArrayNode parentNode = (ArrayNode)node;
  assertEquals( parentNode.size() , 1 );

  JsonNode childNode = parentNode.get(0);
  assertTrue( ( childNode instanceof ObjectNode ) );
  ObjectNode objNode = (ObjectNode)childNode;

  assertEquals( objNode.size() , 3 );
  assertTrue( objNode.get("key1").isTextual() );
  assertTrue( objNode.get("key2").isTextual() );
  assertTrue( objNode.get("key3").isTextual() );
  assertEquals( objNode.get("key1").asText() , "a" );
  assertEquals( objNode.get("key2").asText() , "b" );
  assertEquals( objNode.get("key3").asText() , "c" );
}
 
Example #5
Source File: MapRestServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void setData(ObjectNode mainNode, ArrayNode arrayNode)
    throws AxelorException, JSONException {

  mainNode.put("status", 0);
  mainNode.set("data", arrayNode);
  Optional<Address> optionalAddress = Beans.get(UserService.class).getUserActiveCompanyAddress();

  if (optionalAddress.isPresent()) {
    Optional<Pair<BigDecimal, BigDecimal>> latLong =
        Beans.get(AddressService.class).getOrUpdateLatLong(optionalAddress.get());

    if (latLong.isPresent()) {
      JsonNodeFactory factory = JsonNodeFactory.instance;
      ObjectNode objectNode = factory.objectNode();
      objectNode.put("lat", latLong.get().getLeft());
      objectNode.put("lng", latLong.get().getRight());
      mainNode.set("company", objectNode);
    }
  }
}
 
Example #6
Source File: KafkaStorageHttpService.java    From zipkin-storage-kafka with Apache License 2.0 6 votes vote down vote up
@Get("/autocompleteTags/:key")
@ProducesJson
public JsonNode getAutocompleteValues(@Param("key") String key) {
  try {
    if (!storage.traceSearchEnabled) return MAPPER.createArrayNode();
    ReadOnlyKeyValueStore<String, Set<String>> autocompleteTagsStore =
        storage.getTraceStorageStream().store(AUTOCOMPLETE_TAGS_STORE_NAME,
            QueryableStoreTypes.keyValueStore());
    Set<String> values = autocompleteTagsStore.get(key);
    ArrayNode array = MAPPER.createArrayNode();
    if (values != null) values.forEach(array::add);
    return array;
  } catch (InvalidStateStoreException e) {
    LOG.debug("State store is not ready", e);
    throw e;
  }
}
 
Example #7
Source File: Pods.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
static ObjectNode createJSONErrorString(String str) {
	ObjectNode outJSON = JSON_OBJECT_MAPPER.createObjectNode();
	outJSON.put("prefix", "Error");
	outJSON.put("message", Boolean.TRUE);
	outJSON.put("tag", "syntax");
	outJSON.put("symbol", "General");
	outJSON.put("text", "<math><mrow><mtext>" + str + "</mtext></mrow></math>");

	ObjectNode resultsJSON = JSON_OBJECT_MAPPER.createObjectNode();
	resultsJSON.putNull("line");
	resultsJSON.putNull("result");

	ArrayNode temp = JSON_OBJECT_MAPPER.createArrayNode();
	temp.add(outJSON);
	resultsJSON.putPOJO("out", temp);

	temp = JSON_OBJECT_MAPPER.createArrayNode();
	temp.add(resultsJSON);
	ObjectNode json = JSON_OBJECT_MAPPER.createObjectNode();
	json.putPOJO("results", temp);
	return json;
}
 
Example #8
Source File: JsonConfigWriter.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the auth config from the auth annotation. Subclasses may override
 * to add additional information to the auth config.
 */
private void convertApiAuth(ObjectNode root, ApiAuthConfig config) {
  ObjectNode authConfig = objectMapper.createObjectNode();

  authConfig.put("allowCookieAuth", config.getAllowCookieAuth());

  List<String> blockedRegions = config.getBlockedRegions();
  if (!blockedRegions.isEmpty()) {
    ArrayNode blockedRegionsNode = objectMapper.createArrayNode();
    for (String region : blockedRegions) {
      blockedRegionsNode.add(region);
    }
    authConfig.set("blockedRegions", blockedRegionsNode);
  }

  root.set("auth", authConfig);
}
 
Example #9
Source File: PiTableModelCodec.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public ObjectNode encode(PiTableModel table, CodecContext context) {

    ObjectNode result = context.mapper().createObjectNode();

    result.put(NAME, table.id().toString());
    result.put(MAX_SIZE, table.maxSize());
    result.put(HAS_COUNTERS, table.counters().size() > 0);
    result.put(SUPPORT_AGING, table.supportsAging());

    ArrayNode matchFields = result.putArray(MATCH_FIELDS);
    table.matchFields().forEach(matchField -> {
        ObjectNode matchFieldData =
                context.encode(matchField, PiMatchFieldModel.class);
        matchFields.add(matchFieldData);
    });

    ArrayNode actions = result.putArray(ACTIONS);
    table.actions().forEach(action -> {
        actions.add(action.id().toString());
    });

    return result;
}
 
Example #10
Source File: JsonFilterSpecMapper.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
private Object deserializeJsonFilterValue(ResourceInformation resourceInformation, PathSpec attributePath, JsonNode jsonNode, QueryContext queryContext) {
	QueryPathSpec resolvedPath = pathResolver.resolve(resourceInformation, attributePath.getElements(), QueryPathResolver.NamingType.JSON, "filter", queryContext);
	resolvedPath.verifyFilterable();

	Class valueType = ClassUtils.getRawType(resolvedPath.getValueType());
	ObjectReader reader = context.getObjectMapper().readerFor(valueType);
	try {
		if (jsonNode instanceof ArrayNode) {
			List values = new ArrayList();
			for (JsonNode elementNode : jsonNode) {
				values.add(reader.readValue(elementNode));
			}
			return values;
		}
		return reader.readValue(jsonNode);
	}
	catch (IOException e) {
		throw new ParametersDeserializationException("failed to parse value " + jsonNode + " to type " + valueType);
	}
}
 
Example #11
Source File: JsonExport.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
protected JsonNode toJson(Revision currentRevision) {
    ArrayNode revisions = mapper.createArrayNode();
    while (currentRevision != null) {
        ObjectNode rev = mapper.createObjectNode();
        rev.putPOJO("id", currentRevision.getIdentifier());
        if (currentRevision.getGeneratedAtTime() != null) {
            rev.putPOJO("generatedAtTime", currentRevision.getGeneratedAtTime());
        }
        currentRevision = currentRevision.getPreviousRevision();
        if (currentRevision != null) {
            rev.putPOJO("wasRevisionOf", currentRevision.getIdentifier());
        }
        revisions.add(rev);
    }
    return revisions;
}
 
Example #12
Source File: EncodeConstraintCodecHelper.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Encodes a link type constraint.
 *
 * @return JSON ObjectNode representing the constraint
 */
private ObjectNode encodeLinkTypeConstraint() {
    checkNotNull(constraint, "Link type constraint cannot be null");

    final LinkTypeConstraint linkTypeConstraint =
            (LinkTypeConstraint) constraint;

    final ObjectNode result = context.mapper().createObjectNode()
            .put(ConstraintCodec.INCLUSIVE, linkTypeConstraint.isInclusive());

    final ArrayNode jsonTypes = result.putArray(ConstraintCodec.TYPES);

    if (linkTypeConstraint.types() != null) {
        for (Link.Type type : linkTypeConstraint.types()) {
            jsonTypes.add(type.name());
        }
    }

    return result;
}
 
Example #13
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns object property IRIs in the ontology identified by the provided IDs.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return object properties in the ontology identified by the provided IDs.
 */
@GET
@Path("{recordId}/object-properties")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Gets the object properties in the identified ontology.")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getObjectPropertiesInOntology(@Context ContainerRequestContext context,
                                              @PathParam("recordId") String recordIdStr,
                                              @QueryParam("branchId") String branchIdStr,
                                              @QueryParam("commitId") String commitIdStr) {
    try {
        ArrayNode result = doWithOntology(context, recordIdStr, branchIdStr, commitIdStr,
                this::getObjectPropertyArray, true);
        return Response.ok(result.toString()).build();
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #14
Source File: InPlaceMapOverriderTest.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Test
public void testApply_ObjectArray_PastEnd() {

    Map<String, String> props = Collections.singletonMap("a[2]", "50");
    InPlaceMapOverrider overrider = new InPlaceMapOverrider(props);

    JsonNode node = YamlReader.read("a:\n" +
            "  - 1\n" +
            "  - 5");
    overrider.apply(node);

    ArrayNode array = (ArrayNode) node.get("a");
    assertEquals(3, array.size());
    assertEquals(1, array.get(0).asInt());
    assertEquals(5, array.get(1).asInt());
    assertEquals(50, array.get(2).asInt());
}
 
Example #15
Source File: ControlMetricsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns disk metrics of all resources.
 *
 * @return disk metrics of all resources
 * @onos.rsModel DiskMetrics
 */
@GET
@Path("disk_metrics")
@Produces(MediaType.APPLICATION_JSON)
public Response diskMetrics() {
    ObjectNode root = mapper().createObjectNode();
    ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
    ClusterService clusterService = get(ClusterService.class);
    NodeId localNodeId = clusterService.getLocalNode().id();
    ArrayNode diskNodes = root.putArray("disks");
    monitorService.availableResourcesSync(localNodeId, DISK).forEach(name -> {
        ObjectNode diskNode = mapper().createObjectNode();
        ObjectNode valueNode = mapper().createObjectNode();

        metricsStats(monitorService, localNodeId, DISK_METRICS, name, valueNode);
        diskNode.put("name", name);
        diskNode.set("value", valueNode);

        diskNodes.add(diskNode);
    });

    return ok(root).build();
}
 
Example #16
Source File: MappingTreatmentCodec.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public ObjectNode encode(MappingTreatment treatment, CodecContext context) {
    checkNotNull(treatment, "Mapping treatment cannot be null");

    final ObjectNode result = context.mapper().createObjectNode();
    final ArrayNode jsonInstructions = result.putArray(INSTRUCTIONS);

    final JsonCodec<MappingInstruction> instructionCodec =
            context.codec(MappingInstruction.class);

    final JsonCodec<MappingAddress> addressCodec =
            context.codec(MappingAddress.class);

    for (final MappingInstruction instruction : treatment.instructions()) {
        jsonInstructions.add(instructionCodec.encode(instruction, context));
    }

    result.set(ADDRESS, addressCodec.encode(treatment.address(), context));

    return result;
}
 
Example #17
Source File: JsonUtils.java    From search-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
public static List<Object> parserArrayNode(ArrayNode arrayNode) {
    List<Object> list = new ArrayList<Object>();
    for (int i = 0; i < arrayNode.size(); i++) {
        JsonNode n = arrayNode.get(i);
        if (n.isValueNode()) {
            list.add(parserValue(n));
        } else if (n.isObject()) {
            list.add(parserMap((ObjectNode) n));
        }
    }
    return list;
}
 
Example #18
Source File: PointsSerializerTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void serializeSizesPoints_resultJsonHasSizes() throws IOException {
  //when
  points.setSize(Arrays.asList(11, 22, 33));
  pointsSerializer.serialize(points, jgen, new DefaultSerializerProvider.Impl());
  jgen.flush();
  //then
  JsonNode actualObj = mapper.readTree(sw.toString());
  Assertions.assertThat(actualObj.has("sizes")).isTrue();
  ArrayNode arrayNode = (ArrayNode) actualObj.get("sizes");
  Assertions.assertThat(arrayNode.get(1).asInt()).isEqualTo(22);
}
 
Example #19
Source File: TestJacksonParserToJsonObject.java    From yosegi with Apache License 2.0 5 votes vote down vote up
@Test
public void T_getFromAraryParser_equalsSetValue_withNull() throws IOException {
  JsonNode node = JacksonParserToJsonObject.getFromArrayParser( null );
  assertTrue( ( node instanceof ArrayNode ) );
  ArrayNode arrayNode = (ArrayNode)node;

  assertEquals( arrayNode.size() , 0 );
}
 
Example #20
Source File: ModelResource.java    From plumdo-work with Apache License 2.0 5 votes vote down vote up
private String createModelJson(Model model) {
    ObjectNode editorNode = objectMapper.createObjectNode();
    editorNode.put("id", "canvas");
    editorNode.put("resourceId", "canvas");
    ObjectNode stencilSetNode = objectMapper.createObjectNode();
    stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
    editorNode.set("stencilset", stencilSetNode);
    ObjectNode propertiesNode = objectMapper.createObjectNode();
    propertiesNode.put("process_id", model.getKey());
    propertiesNode.put("name", model.getName());
    propertiesNode.put("process_version", "v1.0");
    propertiesNode.put("process_author", getUserName(Authentication.getUserId()));
    editorNode.set("properties", propertiesNode);

    ArrayNode childShapeArray = objectMapper.createArrayNode();
    editorNode.set("childShapes", childShapeArray);
    ObjectNode childNode = objectMapper.createObjectNode();
    childShapeArray.add(childNode);
    ObjectNode boundsNode = objectMapper.createObjectNode();
    childNode.set("bounds", boundsNode);
    ObjectNode lowerRightNode = objectMapper.createObjectNode();
    boundsNode.set("lowerRight", lowerRightNode);
    lowerRightNode.put("x", 130);
    lowerRightNode.put("y", 193);
    ObjectNode upperLeftNode = objectMapper.createObjectNode();
    boundsNode.set("upperLeft", upperLeftNode);
    upperLeftNode.put("x", 100);
    upperLeftNode.put("y", 163);
    childNode.set("childShapes", objectMapper.createArrayNode());
    childNode.set("dockers", objectMapper.createArrayNode());
    childNode.set("outgoing", objectMapper.createArrayNode());
    childNode.put("resourceId", "startEvent1");
    ObjectNode stencilNode = objectMapper.createObjectNode();
    childNode.set("stencil", stencilNode);
    stencilNode.put("id", "StartNoneEvent");
    return editorNode.toString();
}
 
Example #21
Source File: PinotSchemaRestletResource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/schemas")
@ApiOperation(value = "List all schema names", notes = "Lists all schema names")
public String listSchemaNames() {
  List<String> schemaNames = _pinotHelixResourceManager.getSchemaNames();
  ArrayNode ret = JsonUtils.newArrayNode();

  if (schemaNames != null) {
    for (String schema : schemaNames) {
      ret.add(schema);
    }
  }
  return ret.toString();
}
 
Example #22
Source File: BasedXYGraphicsSerializerTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void serializeBasesOfBasedXYGraphics_resultJsonHasBases() throws IOException {
  //when
  area.setBase(Arrays.asList(11, 22, 33));
  basedXYGraphicsSerializer.serialize(area, jgen, new DefaultSerializerProvider.Impl());
  jgen.flush();
  //then
  JsonNode actualObj = mapper.readTree(sw.toString());
  Assertions.assertThat(actualObj.has("bases")).isTrue();
  ArrayNode arrayNode = (ArrayNode) actualObj.get("bases");
  Assertions.assertThat(arrayNode.get(1).asInt()).isEqualTo(22);
}
 
Example #23
Source File: MonitoringController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Gives suggestions when a Monitor searches for Learners and staff members.
    */
   @RequestMapping("/autocomplete")
   @ResponseBody
   public String autocomplete(HttpServletRequest request, HttpServletResponse response) throws Exception {

long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID);
if (!securityService.isLessonMonitor(lessonId, getUserId(), "autocomplete in monitoring", false)) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson");
    return null;
}

String searchPhrase = request.getParameter("term");
boolean isOrganisationSearch = WebUtil.readStrParam(request, "scope").equalsIgnoreCase("organisation");

Collection<User> users = null;
if (isOrganisationSearch) {
    // search for Learners in the organisation
    Map<User, Boolean> result = lessonService.getUsersWithLessonParticipation(lessonId, Role.LEARNER,
	    searchPhrase, MonitoringController.USER_PAGE_SIZE, null, true);
    users = result.keySet();
} else {
    // search for Learners in the lesson
    users = lessonService.getLessonLearners(lessonId, searchPhrase, MonitoringController.USER_PAGE_SIZE, null,
	    true);
}

ArrayNode responseJSON = JsonNodeFactory.instance.arrayNode();
for (User user : users) {
    ObjectNode userJSON = JsonNodeFactory.instance.objectNode();
    userJSON.put("label", user.getFirstName() + " " + user.getLastName() + " " + user.getLogin());
    userJSON.put("value", user.getUserId());

    responseJSON.add(userJSON);
}

response.setContentType("application/json;charset=utf-8");
return responseJSON.toString();
   }
 
Example #24
Source File: NamedQueries.java    From amazon-neptune-tools with Apache License 2.0 5 votes vote down vote up
public static NamedQueries fromJson(JsonNode json) {
    String name = json.path("name").textValue();
    ArrayNode queries = (ArrayNode) json.path("queries");

    List<String> collection = new ArrayList<>();

    for (JsonNode query : queries) {
        collection.add(query.textValue());
    }

    return new NamedQueries(name, collection);
}
 
Example #25
Source File: RegexURLNormalizer.java    From storm-crawler with Apache License 2.0 5 votes vote down vote up
/** Populates a List of Rules off of JsonNode. */
private List<Rule> readRules(ArrayNode rulesList) {
    List<Rule> rules = new ArrayList<>();
    for (JsonNode regexNode : rulesList) {
        if (regexNode == null || regexNode.isNull()) {
            LOG.warn("bad config: 'regex' element is null");
            continue;
        }
        JsonNode patternNode = regexNode.get("pattern");
        JsonNode substitutionNode = regexNode.get("substitution");

        String substitutionValue = "";
        if (substitutionNode != null) {
            substitutionValue = substitutionNode.asText();
        }
        if (patternNode != null
                && StringUtils.isNotBlank(patternNode.asText())) {
            Rule rule = createRule(patternNode.asText(), substitutionValue);
            if (rule != null) {
                rules.add(rule);
            }
        }
    }
    if (rules.size() == 0) {
        rules = EMPTY_RULES;
    }
    return rules;
}
 
Example #26
Source File: LinkMapperTests.java    From initializr with Apache License 2.0 5 votes vote down vote up
@Test
void mergeSeveralLinksInArray() {
	List<Link> links = new ArrayList<>();
	links.add(Link.create("a", "https://example.com", "some description"));
	links.add(Link.create("a", "https://example.com/2"));
	ObjectNode model = LinkMapper.mapLinks(links);
	assertThat(model).hasSize(1);
	assertThat(model.has("a")).isTrue();
	ArrayNode linksModel = (ArrayNode) model.get("a");
	assertThat(linksModel).hasSize(2);
	assertThat(linksModel.get(0).get("href").textValue()).isEqualTo("https://example.com");
	assertThat(linksModel.get(1).get("href").textValue()).isEqualTo("https://example.com/2");
}
 
Example #27
Source File: LdTemplateController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Helper method to create a Vote tool content. Title, instructions and answers (Array of String) are required.
    * Other fields are optional.
    */
   protected Long createVoteToolContent(UserDTO user, String title, String instructions, ArrayNode answers,
    Boolean showResults) throws IOException {

ObjectNode toolContentJSON = createStandardToolContent(title, instructions, null, null, null, null);
toolContentJSON.set(RestTags.ANSWERS, answers);
toolContentJSON.put("showResults", showResults);
return createToolContent(user, LdTemplateController.VOTE_TOOL_SIGNATURE, toolContentJSON);
   }
 
Example #28
Source File: WampMessages.java    From jawampa with Apache License 2.0 5 votes vote down vote up
@Override
public WampMessage fromObjectArray(ArrayNode messageNode) throws WampError {
    if (messageNode.size() != 3
            || !messageNode.get(1).canConvertToLong()
            || !messageNode.get(2).canConvertToLong())
        throw new WampError(ApplicationError.INVALID_MESSAGE);

    long requestId = messageNode.get(1).asLong();
    long publicationId = messageNode.get(2).asLong();

    return new PublishedMessage(requestId, publicationId);
}
 
Example #29
Source File: JsonUtilTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void getArrayNode_nullValue() {
  final String jsonStr = "{\"test\": null }";
  final ObjectNode rootNode = JsonUtil.objectNodeFromString(jsonStr);

  final Optional<ArrayNode> maybeTestNode = JsonUtil.getArrayNode(rootNode, "test");
  assertThat(maybeTestNode).isEmpty();
}
 
Example #30
Source File: ServerReader.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a list of {@link Server} OpenAPI nodes.
 * 
 * @param node the json array
 * @return a List of Server models
 */
public static Optional<List<Server>> readServers(final JsonNode node) {
    if (node != null && node.isArray()) {
        IoLogging.log.jsonArray("Server");
        ArrayNode nodes = (ArrayNode) node;
        List<Server> rval = new ArrayList<>(nodes.size());
        for (JsonNode serverNode : nodes) {
            rval.add(readServer(serverNode));
        }
        return Optional.of(rval);
    }
    return Optional.empty();
}