Java Code Examples for com.fasterxml.jackson.databind.node.ObjectNode.put()

The following are Jave code examples for showing how to use put() of the com.fasterxml.jackson.databind.node.ObjectNode class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Equella   File: OAuthApiLockTest.java   View Source Code Vote up 6 votes
private void createOAuth() throws IOException
{
	token = requestToken(OAUTH_CLIENT_ID);
	ObjectNode oauthclient = mapper.createObjectNode();
	oauthclient.put("name", "Random OAuth");
	oauthclient.put("clientId", "clientId");
	oauthclient.put("clientSecret", "clientSecret");
	oauthclient.put("userId", RestTestConstants.USERID_AUTOTEST);
	oauthclient.put("redirectUrl", "default");

	HttpResponse response = postEntity(oauthclient.toString(), context.getBaseUrl() + "api/oauth", token, true);
	assertResponse(response, 201, "Expected oauthclient to be created");

	oauthUri = response.getFirstHeader("Location").getValue();
	getEntity(oauthUri, token);
}
 
Example 2
Project: csap-core   File: DefinitionRequests.java   View Source Code Vote up 6 votes
@GetMapping ( value = "/serviceDockerTemplate" , produces = MediaType.APPLICATION_JSON_VALUE )
public JsonNode getDockerTemplate (
									String templateName )

		throws IOException {

	// templateName = DockerJson.defaultJavaDocker.key
	ObjectNode dockerTemplate = (ObjectNode) dockerHelper.getDockerTemplates().get( templateName );
	String imageName = dockerTemplate.get( "image" ).asText().replaceAll(
		Matcher.quoteReplacement( CSAP.DOCKER_REPOSITORY ),
		Matcher.quoteReplacement( csapApp.getCsapCoreService().getDocker().getTemplateRepository() ) );
	dockerTemplate.put( "image", imageName );

	return dockerTemplate;

}
 
Example 3
Project: athena   File: BgpRoutesListCommand.java   View Source Code Vote up 6 votes
/**
 * Produces JSON object for an AS path.
 *
 * @param mapper the JSON object mapper to use
 * @param asPath the AS path with the data
 * @return JSON object for the AS path
 */
private ObjectNode json(ObjectMapper mapper, BgpRouteEntry.AsPath asPath) {
    ObjectNode result = mapper.createObjectNode();
    ArrayNode pathSegmentsJson = mapper.createArrayNode();
    for (BgpRouteEntry.PathSegment pathSegment : asPath.getPathSegments()) {
        ObjectNode pathSegmentJson = mapper.createObjectNode();
        pathSegmentJson.put("type",
                            BgpConstants.Update.AsPath.typeToString(pathSegment.getType()));
        ArrayNode segmentAsNumbersJson = mapper.createArrayNode();
        for (Long asNumber : pathSegment.getSegmentAsNumbers()) {
            segmentAsNumbersJson.add(asNumber);
        }
        pathSegmentJson.set("segmentAsNumbers", segmentAsNumbersJson);
        pathSegmentsJson.add(pathSegmentJson);
    }
    result.set("pathSegments", pathSegmentsJson);

    return result;
}
 
Example 4
Project: athena   File: StatisticsWebResource.java   View Source Code Vote up 6 votes
/**
 * Gets port statistics of all devices.
 * @onos.rsModel StatisticsPorts
 * @return 200 OK with JSON encoded array of port statistics
 */
@GET
@Path("ports")
@Produces(MediaType.APPLICATION_JSON)
public Response getPortStatistics() {
    final DeviceService service = get(DeviceService.class);
    final Iterable<Device> devices = service.getDevices();
    final ObjectNode root = mapper().createObjectNode();
    final ArrayNode rootArrayNode = root.putArray("statistics");
    for (final Device device : devices) {
        final ObjectNode deviceStatsNode = mapper().createObjectNode();
        deviceStatsNode.put("device", device.id().toString());
        final ArrayNode statisticsNode = deviceStatsNode.putArray("ports");
        final Iterable<PortStatistics> portStatsEntries = service.getPortStatistics(device.id());
        if (portStatsEntries != null) {
            for (final PortStatistics entry : portStatsEntries) {
                statisticsNode.add(codec(PortStatistics.class).encode(entry, this));
            }
        }
        rootArrayNode.add(deviceStatsNode);
    }

    return ok(root).build();
}
 
Example 5
Project: athena   File: DeviceViewMessageHandler.java   View Source Code Vote up 5 votes
@Override
public void process(long sid, ObjectNode payload) {
    String id = string(payload, ID, ZERO_URI);

    DeviceId deviceId = deviceId(id);
    DeviceService service = get(DeviceService.class);
    MastershipService ms = get(MastershipService.class);
    Device device = service.getDevice(deviceId);
    ObjectNode data = objectNode();
    NodeId masterFor = ms.getMasterFor(deviceId);

    data.put(ID, deviceId.toString());
    data.put(NAME, deviceName(device));
    data.put(TYPE, capitalizeFully(device.type().toString()));
    data.put(TYPE_IID, getTypeIconId(device));
    data.put(MFR, device.manufacturer());
    data.put(HW, device.hwVersion());
    data.put(SW, device.swVersion());
    data.put(SERIAL, device.serialNumber());
    data.put(CHASSIS_ID, device.chassisId().toString());
    data.put(MASTER_ID, masterFor != null ? masterFor.toString() : NONE);
    data.put(PROTOCOL, deviceProtocol(device));

    ArrayNode ports = arrayNode();

    List<Port> portList = new ArrayList<>(service.getPorts(deviceId));
    Collections.sort(portList, (p1, p2) -> {
        long delta = p1.number().toLong() - p2.number().toLong();
        return delta == 0 ? 0 : (delta < 0 ? -1 : +1);
    });

    for (Port p : portList) {
        ports.add(portData(p, deviceId));
    }
    data.set(PORTS, ports);

    ObjectNode rootNode = objectNode();
    rootNode.set(DETAILS, data);
    sendMessage(DEV_DETAILS_RESP, 0, rootNode);
}
 
Example 6
Project: csap-core   File: ModelApi.java   View Source Code Vote up 5 votes
@CsapDoc ( notes = {
		"Gets the artifacts configured in application definition",
		"Optional: releasePackage - if not specified, all artifacts in all packages will be returned"
} , linkTests = {
		"All Packages",
		"changeMe package",
} , linkGetParams = {
		"params=none", "releasePackage=changeMe"
} )
@GetMapping ( value={"/artifacts", "/mavenArtifacts"} )
public JsonNode artifacts ( String releasePackage ) {
	
	if ( releasePackage == null ) {
		releasePackage = application.getAllPackages().getReleasePackageName();
	}
	
	if ( application.getModel( releasePackage ) == null ) {
		ObjectNode managerError = jacksonMapper.createObjectNode();
		managerError.put( "error", "Unrecognized package name: " + releasePackage );
		managerError.set( "available", packagesWithCluster() );
		return managerError;
	}
	

	List<String> mavenIds = application.getModel( releasePackage )
		.getServiceConfigStreamInCurrentLC()
		.flatMap( serviceInstancesEntry -> serviceInstancesEntry.getValue().stream() )
		.map( serviceInstance -> serviceInstance.getMavenId() )
		.distinct()
		.filter( version -> version.length() != 0 )
		.collect( Collectors.toList() );

	return jacksonMapper.convertValue( mavenIds, ArrayNode.class );

}
 
Example 7
Project: athena   File: TopoJson.java   View Source Code Vote up 5 votes
private static ObjectNode json(LinkHighlight lh) {
    ObjectNode n = objectNode()
            .put(ID, lh.elementId())
            .put(LABEL, lh.label())
            .put(CSS, lh.cssClasses());
    if (lh.subdued()) {
        n.put(SUBDUE, true);
    }
    return n;
}
 
Example 8
Project: thingsboard-gateway   File: MqttGatewayService.java   View Source Code Vote up 5 votes
@Override
public void onAppliedConfiguration(String configuration) {
    try {
        ObjectNode node = newNode();
        node.put("appliedConfiguration", configuration);
        MqttMessage msg = new MqttMessage(JsonTools.toString(node).getBytes(StandardCharsets.UTF_8));
        tbClient.publish(DEVICE_ATTRIBUTES_TOPIC, msg).waitForCompletion();
    } catch (Exception e) {
        log.warn("Could not publish applied configuration", e);
    }
}
 
Example 9
Project: wherehowsX   File: Dataset.java   View Source Code Vote up 5 votes
public static Result getDatasetVersions(Long datasetId, Integer dbId)
{
    ObjectNode result = Json.newObject();
    result.put("status", "ok");
    result.set("versions", Json.toJson(DatasetsDAO.getDatasetVersions(datasetId, dbId)));
    return ok(result);
}
 
Example 10
Project: jasvorno   File: JasvornoConverterTest.java   View Source Code Vote up 5 votes
@Test
public void matchMapValueOfFloatTypeWithFloatValue() throws JsonProcessingException, IOException {
  Schema schema = SchemaBuilder.map().values().floatType();
  ObjectMapper mapper = new ObjectMapper();
  ObjectNode dataTable = mapper.createObjectNode();
  JsonNode datum = dataTable.put("field1", Float.MAX_VALUE);
  MatchType matchType = new JasvornoConverter(model, UndeclaredFieldBehaviour.NO_MATCH).matchMapValue(datum, schema);
  assertThat(matchType, is(MatchType.FULL));
}
 
Example 11
Project: premier-wherehows   File: Dataset.java   View Source Code Vote up 5 votes
public static Result getDependViews(Long datasetId)
{
    ObjectNode result = Json.newObject();
    List<DatasetDependency> depends = new ArrayList<>();
    DatasetsDAO.getDependencies(datasetId, depends);
    result.put("status", "ok");
    result.set("depends", Json.toJson(depends));
    return ok(result);
}
 
Example 12
Project: wherehowsX   File: FlowController.java   View Source Code Vote up 5 votes
public static Result getFlowOwners(String flowPath) {
  String instance = request().getQueryString("instance");
  ObjectNode resultJson = Json.newObject();

  try {
    List<Map<String, Object>> owners = FlowDao.getFlowOwner(flowPath, instance);
    resultJson.put("return_code", 200);
    resultJson.set("owners", Json.toJson(owners));
  } catch (Exception e) {
    e.printStackTrace();
    resultJson.put("return_code", 404);
    resultJson.put("error_message", e.getMessage());
  }
  return ok(resultJson);
}
 
Example 13
Project: Equella   File: ScormResultsExtension.java   View Source Code Vote up 5 votes
@Override
public void processResultForMultiple(SectionInfo info, SelectionSession session, ObjectNode link, IItem<?> item,
	SelectedResource resource)
{
	String attachmentUuid = resource.getAttachmentUuid();
	if( !Check.isEmpty(attachmentUuid) )
	{
		ItemId itemId = getItemIdForResource(resource);

		IAttachment attachment = itemResolver.getAttachmentForUuid(itemId, attachmentUuid,
			resource.getKey().getExtensionType());
		AttachmentType type = attachment.getAttachmentType();
		if( type.equals(AttachmentType.CUSTOM) )
		{
			final CustomAttachment custom = (CustomAttachment) attachment;
			if( custom.getType().equalsIgnoreCase(ScormUtils.ATTACHMENT_TYPE) )
			{
				link.put("uuid", itemId.getUuid());
				link.put("version", itemId.getVersion());
				link.put("filename", custom.getUrl());

				ItemFile itemFile = itemFileService.getItemFile(itemId, null);
				try( InputStream in = imsService.getImsManifestAsStream(itemFile, custom.getUrl(), true) )
				{
					link.put("scorm", IOUtils.toString(in));
				}
				catch( IOException ex )
				{
					LOGGER.error("Error reading manifest file", ex);
				}
			}
		}
	}
}
 
Example 14
Project: BingoChess   File: Chatter.java   View Source Code Vote up 5 votes
public JsonNode chatterToJSON() {
	ObjectNode obj = mapper.createObjectNode();
	obj.put("handle", handle);
	obj.put("color", 
	String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue()));
	return obj;
}
 
Example 15
Project: BingoChess   File: BingoChess.java   View Source Code Vote up 5 votes
private JsonNode playerToJson(Document doc) {
	if (doc == null) return null;
	ObjectNode obj = mapper.createObjectNode();
	obj.put("name", doc.getString("name"));
	obj.put("tickets",doc.getInteger("tickets").toString());
	obj.put("gold",doc.getInteger("gold").toString());
	obj.put("games",doc.getInteger("games").toString());
	return obj;
}
 
Example 16
Project: athena   File: EncodeCriterionCodecHelper.java   View Source Code Vote up 5 votes
@Override
public ObjectNode encodeCriterion(ObjectNode root, Criterion criterion) {
    OchSignal ochSignal = ((OchSignalCriterion) criterion).lambda();
    ObjectNode child = root.putObject(CriterionCodec.OCH_SIGNAL_ID);

    child.put(CriterionCodec.GRID_TYPE, ochSignal.gridType().name());
    child.put(CriterionCodec.CHANNEL_SPACING, ochSignal.channelSpacing().name());
    child.put(CriterionCodec.SPACING_MULIPLIER, ochSignal.spacingMultiplier());
    child.put(CriterionCodec.SLOT_GRANULARITY, ochSignal.slotGranularity());

    return root;
}
 
Example 17
Project: athena   File: EncodeCriterionCodecHelper.java   View Source Code Vote up 4 votes
@Override
public ObjectNode encodeCriterion(ObjectNode root, Criterion criterion) {
    final IPProtocolCriterion iPProtocolCriterion =
            (IPProtocolCriterion) criterion;
    return root.put(CriterionCodec.PROTOCOL, iPProtocolCriterion.protocol());
}
 
Example 18
Project: aws-sdk-java-v2   File: JsonErrorCodeParserTest.java   View Source Code Vote up 4 votes
private static JsonContent toJsonContent(String errorType) {
    ObjectNode node = MAPPER.createObjectNode();
    node.put(ERROR_FIELD_NAME, errorType);
    return new JsonContent(null, node);
}
 
Example 19
Project: csap-core   File: TrendCache.java   View Source Code Vote up 4 votes
@CachePut ( key = KEY_IS_RESTURL )
public ObjectNode update ( String restUrl, String timerName )
		throws Exception {

	ObjectNode resultsJson = refreshRequiredResponse();

	int reportHash = buildReportHash( restUrl );

	Split allTimer = SimonManager.getStopwatch( "trendCache.reload" ).start();
	timerName = "trendCache.reload." + timerName.replaceAll( "/", "-" ).replaceAll( " ", "-" ).replaceAll( "=", "-" )
		.replaceAll( "\\?", "." ).replaceAll( "&", "." );
	Split trendTimer = SimonManager.getStopwatch( timerName ).start();
	try {

		ObjectNode restResponse = null;

		if ( !csapApp.lifeCycleSettings().isEventPublishEnabled() ) {
			logger.info( "Stubbing out data for trends - add csap events services" );

			restResponse = loadStubDataAndUpdateDateRange() ;
			resultsJson.put( "message", "csap-event-service disabled - using stub data" );
			
		} else {
			restResponse = trendRestTemplate.getForObject( restUrl, ObjectNode.class );
		}

		resultsJson = restResponse;
		if ( resultsJson != null ) {
			resultsJson.put( "source", restUrl );
			resultsJson.put( "updated", shortFormatter.format( new Date() ) );
			resultsJson.put( TrendCacheManager.LAST_UPDATE_TOKEN, System.currentTimeMillis() );

		}

	} catch (Exception e) {
		String reason = CSAP.getCsapFilteredStackTrace( e );
		logger.error( "Failed getting report from url: {}, Reason: {}", restUrl, reason );
		logger.debug( "Stack Trace ", e );
		resultsJson.put( "url", restUrl );
		resultsJson.put( "message", "Error during Access: " + reason );
	}
	trendTimer.stop();
	allTimer.stop();
	resultsJson.put( TrendCacheManager.HASH, reportHash );

	return resultsJson;
}
 
Example 20
Project: athena   File: JsonUtils.java   View Source Code Vote up 3 votes
/**
 * Composes a message structure for the given message type and payload.
 *
 * @param type    message type
 * @param payload message payload
 * @return the object node representation
 */
public static ObjectNode envelope(String type, ObjectNode payload) {
    ObjectNode event = MAPPER.createObjectNode();
    event.put("event", type);
    event.set("payload", payload);
    return event;
}