本文整理汇总了Java中com.fasterxml.jackson.databind.node.ObjectNode.putObject方法的典型用法代码示例。如果您正苦于以下问题:Java ObjectNode.putObject方法的具体用法?Java ObjectNode.putObject怎么用?Java ObjectNode.putObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.fasterxml.jackson.databind.node.ObjectNode
的用法示例。
在下文中一共展示了ObjectNode.putObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: setInPath
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
private void setInPath(ObjectNode obj, JsonPointer path, JsonNode value) {
String key = path.getMatchingProperty();
path = path.tail();
if (path.matches()) {
if (!obj.has(key)) {
obj.set(key, value);
} else if (canMerge(obj, value, key)) {
merge(obj, value, key);
} else if (canAdd(obj, value)) {
add(obj, value);
} else {
throw badStructure();
}
} else {
obj = obj.has(key) ? (ObjectNode) obj.get(key) : obj.putObject(key);
setInPath(obj, path, value);
}
}
示例2: onDeviceAttributesUpdate
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
@Override
public MqttDeliveryFuture onDeviceAttributesUpdate(String deviceName, List<KvEntry> attributes) {
final int msgId = msgIdSeq.incrementAndGet();
log.trace("[{}][{}] Updating device attributes: {}", deviceName, msgId, attributes);
checkDeviceConnected(deviceName);
ObjectNode node = newNode();
ObjectNode deviceNode = node.putObject(deviceName);
attributes.forEach(kv -> putToNode(deviceNode, kv));
final int packSize = attributes.size();
MqttMessage msg = new MqttMessage(toBytes(node));
msg.setId(msgId);
return publishAsync(GATEWAY_ATTRIBUTES_TOPIC, msg,
token -> {
log.debug("[{}][{}] Device attributes were delivered!", deviceName, msgId);
attributesCount.addAndGet(packSize);
},
error -> log.warn("[{}][{}] Failed to report device attributes!", deviceName, msgId, error));
}
示例3: reportStats
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
private void reportStats() {
if (tbClient == null) {
log.info("Can't report stats because client was not initialized yet!");
return;
}
ObjectNode node = newNode();
node.put("ts", System.currentTimeMillis());
ObjectNode valuesNode = node.putObject("values");
valuesNode.put("devicesOnline", devices.size());
valuesNode.put("attributesUploaded", attributesCount.getAndSet(0));
valuesNode.put("telemetryUploaded", telemetryCount.getAndSet(0));
if (error != null) {
valuesNode.put("latestError", JsonTools.toString(error));
error = null;
}
MqttMessage msg = new MqttMessage(toBytes(node));
msg.setId(msgIdSeq.incrementAndGet());
publishAsync(DEVICE_TELEMETRY_TOPIC, msg,
token -> log.info("Gateway statistics {} reported!", node),
error -> log.warn("Failed to report gateway statistics!", error));
}
示例4: addDummyMetricAttributes
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
private void addDummyMetricAttributes ( int requestedSampleSize, int skipFirstItems,
int numServices, int numGraphs, ObjectNode rootNode ) {
ObjectNode descNode = rootNode.putObject( "attributes" );
descNode.put( "id", "dummy_99" );
descNode.put( "metricName", "System Resource" );
descNode.put( "description", "Contains usr,sys,io, and load level metrics" );
descNode.put( "hostName", Application.getHOST_NAME() );
descNode.put( "sampleInterval", 99 );
descNode.put( "samplesRequested", requestedSampleSize );
descNode.put( "samplesOffset", skipFirstItems );
descNode.put( "currentTimeMillis", System.currentTimeMillis() );
descNode.put( "cpuCount", osStats.getAvailableProcessors() );
ObjectNode graphsArray = descNode.putObject( "graphs" );
for ( int i = 0; i < numGraphs; i++ ) {
String graphName = "DummyGraph" + i;
ObjectNode resourceGraph = graphsArray.putObject( graphName );
for ( int j = 0; j < numServices; j++ ) {
resourceGraph.put( graphName + "Service" + j, "Service " + j );
}
}
}
示例5: reportStats
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
private void reportStats() {
if (tbClient == null) {
log.info("Can't report stats because client was not initialized yet!");
return;
}
ObjectNode node = newNode();
node.put("ts", System.currentTimeMillis());
ObjectNode valuesNode = node.putObject("values");
valuesNode.put("devicesOnline", devices.size());
valuesNode.put("attributesUploaded", attributesCount.getAndSet(0));
valuesNode.put("telemetryUploaded", telemetryCount.getAndSet(0));
if (error != null) {
valuesNode.put("latestError", JsonTools.toString(error));
error = null;
}
MqttMessage msg = new MqttMessage(toBytes(node));
msg.setId(msgIdSeq.incrementAndGet());
publishAsync(DEVICE_TELEMETRY_TOPIC, msg, token -> log.info("Gateway statistics {} reported!", node),
error -> log.warn("Failed to report gateway statistics!", error));
}
示例6: addNagiosStateMessage
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
/**
*
* Only agents use state
*
* @param stateNode
* @param State
* @param message
*/
private void addNagiosStateMessage ( ObjectNode errorNode, String monitor, String state, String message ) {
ObjectNode stateNode = (ObjectNode) errorNode.get( "states" );
if ( stateNode != null ) {
ObjectNode item = stateNode.putObject( monitor );
item.put( "status", state );
item.put( "message", message );
}
}
示例7: encodeCriterion
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
@Override
public ObjectNode encodeCriterion(ObjectNode root, Criterion criterion) {
OduSignalId oduSignalId = ((OduSignalIdCriterion) criterion).oduSignalId();
ObjectNode child = root.putObject(CriterionCodec.ODU_SIGNAL_ID);
child.put(CriterionCodec.TRIBUTARY_PORT_NUMBER, oduSignalId.tributaryPortNumber());
child.put(CriterionCodec.TRIBUTARY_SLOT_LEN, oduSignalId.tributarySlotLength());
child.put(CriterionCodec.TRIBUTARY_SLOT_BITMAP, HexString.toHexString(oduSignalId.tributarySlotBitmap()));
return root;
}
示例8: merge
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
private JsonNode merge(JsonNode container, JsonNode value, String key) {
ObjectNode into = container.isMissingNode() ? JsonOverlay.jsonObject() : (ObjectNode) container;
ObjectNode result = into;
if (key != null) {
into = into.has(key) ? (ObjectNode) into.get(key) : into.putObject(key);
}
if (!value.isMissingNode()) {
ObjectNode from = (ObjectNode) value;
for (Entry<String, JsonNode> field : JsonOverlay.iterable(from.fields())) {
into.set(field.getKey(), field.getValue());
}
}
return result;
}
示例9: addDummyMetricData
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
private void addDummyMetricData ( int numSamples, int numServices, int numGraphs,
ObjectNode metricsNode ) {
futureOffset = futureOffset + numSamples; // for repeated calls, push
// the offset so timestamps
// are not duplicated ;
ObjectNode dataNode = metricsNode.putObject( "data" );
ArrayNode timeStampNode = dataNode.putArray( "timeStamp" );
long currMs = System.currentTimeMillis() + (futureOffset * 1000);
for ( int i = 0; i < numSamples; i++ ) {
// java script needs specialty classes to deal with longs. Must pass
// in as string
timeStampNode.add( Long.toString( currMs + i * 1000 ) );
}
for ( int i = 0; i < numGraphs; i++ ) {
String graphName = "DummyGraph" + i;
for ( int j = 0; j < numServices; j++ ) {
ArrayNode serviceNode = dataNode.putArray( graphName + "Service" + j );
for ( int k = 0; k < numSamples; k++ ) {
serviceNode.add( k );
}
}
}
}
示例10: executeLogRotateForAllServices
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
public void executeLogRotateForAllServices () {
// TODO Auto-generated method stub
StringBuilder servicesWithLongRotations = new StringBuilder();
StringBuilder configurationResults = new StringBuilder();
StringBuilder rotationResults = new StringBuilder();
ObjectNode dailyReport = jacksonMapper.createObjectNode();
ArrayNode serviceArray = dailyReport.putArray( "summary" );
Split timerForAllServices = SimonManager.getStopwatch( LOG_ROLLER_ALL ).start();
logger.info( "Starting service log rotations" );
// Generate the log configuration file
csapApp.getActiveModel()
.getServicesOnHost( Application.getHOST_NAME() )
.filter( CSAP.not( ServiceInstance::isScript ) )
.filter( CSAP.not( ServiceInstance::isRemoteCollection ) )
.map( this::generateDefaultRotateConfig )
.forEach( configurationResults::append );
if ( configurationResults.length() != previousLogConfigurationLength ) {
logger.info( "Configuration Update: Old:{} New:{} \n {}",
previousLogConfigurationLength, configurationResults.length(),
configurationResults.toString() );
}
previousLogConfigurationLength = configurationResults.length();
// Run the log rotation for each service
csapApp.getActiveModel()
.getServicesOnHost( Application.getHOST_NAME() )
.filter( CSAP.not( ServiceInstance::isScript ) )
.filter( CSAP.not( ServiceInstance::isRemoteCollection ) )
.map( service -> logRotateService( service, serviceArray, servicesWithLongRotations ) )
.forEach( rotationResults::append );
if ( rotationResults.length() != previousLogRotationLength ) {
logger.info( "Log Status Update: {}", rotationResults.toString() );
}
previousLogRotationLength = rotationResults.length();
timerForAllServices.stop();
int nowDay = (Calendar.getInstance()).get( Calendar.DAY_OF_WEEK );
if ( lastDay != nowDay ) {
// Publish summary to event service
StopwatchSample dailySample = SimonManager.getStopwatch( LOG_ROLLER_ALL ).sampleIncrement( "daily" );
ObjectNode dailyServiceJson = dailyReport.putObject( "Total" );
dailyServiceJson.put( "Count", dailySample.getCounter() );
dailyServiceJson.put( "MeanSeconds", Math.round( dailySample.getMean() / NANOS_IN_SECOND ) );
dailyServiceJson.put( "TotalSeconds", Math.round( dailySample.getTotal() / NANOS_IN_SECOND ) );
csapApp.getEventClient().publishEvent( CsapEventClient.CSAP_REPORTS_CATEGORY + "/logRotate",
"Daily Summary", null, dailyReport );
}
lastDay = nowDay;
if ( servicesWithLongRotations.length() > 0 ) {
logger.warn( "\n *** Services with rotations taking more then 3 seconds:\n {}", servicesWithLongRotations );
csapApp.getEventClient().publishEvent(
CsapEventClient.CSAP_SYSTEM_CATEGORY + "/logrotate", "Service with rotations",
servicesWithLongRotations.toString() );
}
}
示例11: statusForAdminOrAgent
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
public ObjectNode statusForAdminOrAgent ( double alertLevel ) {
ObjectNode healthJson = jacksonMapper.createObjectNode();
ObjectNode errorNode = buildErrorsForAdminOrAgent( alertLevel );
ObjectNode vmNode = healthJson.putObject( "vm" );
if ( errorNode.size() == 0 ) {
healthJson.put( "Healthy", true );
} else {
healthJson.put( "Healthy", false );
healthJson.set( VALIDATION_ERRORS, errorNode );
}
ObjectNode serviceToRuntimeNode = getHostLoadCpuAndMore();
;
vmNode.put( "cpuCount", Integer.parseInt(
serviceToRuntimeNode
.path( "cpuCount" )
.asText() ) );
double newKB = Math.round( Double.parseDouble(
serviceToRuntimeNode
.path( "cpuLoad" )
.asText() )
* 10.0 )
/ 10.0;
vmNode.put( "cpuLoad", newKB );
vmNode.put( "host", Application.getHOST_NAME() );
vmNode.put( "packageName", getActiveModel().getReleasePackageName() );
vmNode.put( "capabilityName", getName() );
vmNode.put( "lifecycle", getCurrentLifeCycle() );
int totalServicesActive = 0;
int totalServices = 0;
for ( ServiceInstance instance : getServicesOnHost() ) {
if ( !instance.isScript() ) { // Scripts should be ignored
totalServices++;
if ( instance.isRunning() ) {
totalServicesActive++;
}
}
}
ObjectNode serviceNode = healthJson.putObject( "services" );
serviceNode.put( "total", totalServices );
serviceNode.put( "active", totalServicesActive );
return healthJson;
}
示例12: updateMpCache
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
private ObjectNode updateMpCache () {
ObjectNode mpNode = jacksonMapper.createObjectNode();
String mpResult = "";
List<String> parmList = Arrays.asList( "bash", "-c",
"mpstat -P ALL 2 1| grep -i average | sed 's/ */ /g'" );
mpResult = osCommandRunner.executeString( null, parmList );
logger.debug( "mpResult: {}", mpResult );
if ( Application.isRunningOnDesktop() ) {
updateCachesWithTestData();
mpResult = Application.getContents( new File( getClass()
.getResource( "/linux/mpResults.txt" ).getFile() ) );
}
// Skip past the header
mpResult = mpResult.substring( mpResult.indexOf( "Average" ) );
String[] mpLines = mpResult.split( LINE_SEPARATOR );
for ( int i = 0; i < mpLines.length; i++ ) {
String curline = mpLines[i].trim();
String[] cols = curline.split( " " );
if ( cols.length < 11 || cols[1].equalsIgnoreCase( "cpu" )
|| cols[0].startsWith( "_" ) ) {
logger.debug( "Skipping line: {}", curline );
continue;
}
String name = cols[1];
ObjectNode cpuNode = mpNode.putObject( name );
cpuNode.put( "time", cols[0] + cols[1] );
if ( !name.equals( "all" ) ) {
name = "CPU -" + name;
}
cpuNode.put( "cpu", name );
cpuNode.put( "puser", cols[2] );
cpuNode.put( "pnice", cols[3] );
cpuNode.put( "psys", cols[4] );
cpuNode.put( "pio", cols[5] );
cpuNode.put( "pirq", cols[6] );
cpuNode.put( "psoft", cols[7] );
cpuNode.put( "psteal", cols[8] );
cpuNode.put( "pidle", cols[9] );
cpuNode.put( "intr", cols[10] );
}
return mpNode;
}
示例13: getCachedFileSystemInfo
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
public ObjectNode getCachedFileSystemInfo () {
logger.debug( "Entered " );
if ( diskStatisticsCache == null ) {
diskStatisticsCache = CsapSimpleCache.builder(
30,
TimeUnit.SECONDS,
OsManager.class,
"Disk Statistics" );
}
// Use cache
if ( !diskStatisticsCache.isExpired() ) {
logger.debug( "\n\n***** ReUsing DF cache *******\n\n" );
return (ObjectNode) diskStatisticsCache.getCachedObject();
}
// Lets refresh cache
logger.debug( "\n\n***** Refreshing df cache *******\n\n" );
try {
// ps -e --no-heading --sort -pcpu -o
// pid,nlwp,pcpu,rss,ruser,args | sed 's/ */,/g'
List<String> parmList = Arrays.asList( "bash", "-c",
"df -PTh | sed 's/ */ /g'" );
String dfResult = osCommandRunner.executeString( parmList, new File(
"." ) );
logger.debug( "dfResult: {}", dfResult );
if ( Application.isRunningOnDesktop() ) {
if ( csapApp.isDisplayOnDesktop() )
logger.warn( "Application.isRunningOnDesktop() - load test files from eclipse" );
dfResult = Application.getContents( new File( getClass()
.getResource( "/linux/dfResults.txt" ).getFile() ) );
}
ObjectNode svcToStatMap = jacksonMapper.createObjectNode();
String[] dfLines = dfResult.split( System
.getProperty( "line.separator" ) );
int lastCount = 0;
for ( int i = 0; i < dfLines.length; i++ ) {
String curline = dfLines[i].trim();
String[] cols = curline.split( " " );
if ( cols.length < 7 || !cols[6].startsWith( "/" ) ) {
logger.debug( "Skipping line: {}", curline );
continue;
}
ObjectNode fsNode = svcToStatMap.putObject( cols[6] );
fsNode.put( "dev", cols[0] );
fsNode.put( "type", cols[1] );
fsNode.put( "sized", cols[2] );
fsNode.put( "used", cols[3] );
fsNode.put( "avail", cols[4] );
fsNode.put( "usedp", cols[5] );
fsNode.put( "mount", cols[6] );
lastCount++;
}
diskCount = lastCount;
diskStatisticsCache.reset( svcToStatMap );
} catch (Exception e) {
logger.error( "Failed to write output", e );
}
return (ObjectNode) diskStatisticsCache.getCachedObject();
}
示例14: getLastCollectedVals
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
public ObjectNode getLastCollectedVals () {
ObjectNode fullCollectionJson = jacksonMapper.createObjectNode();
if ( !Application.isJvmInManagerMode() ) {
OsSharedResourcesCollector vmCollector = csapApp.getVmSharedCollector( csapApp
.getFirstVmStatsKey() );
fullCollectionJson.set( "vm", vmCollector.getCSVdata( false, null, 1, 0 ).get( "data" ) );
ArrayList<ServiceInstance> svcList = csapApp.getServicesOnHost();
String[] serviceNames = new String[ svcList.size() ];
int i = 0;
for ( ServiceInstance instance : csapApp.getServicesOnHost() ) {
serviceNames[i++] = instance.getServiceName();
}
OsProcessCollector serviceCollector = csapApp.getVmProcessCollector( csapApp
.getFirstSvcStatsKey() );
// fullCollectionJson.set( "process", serviceCollector.getCSVdata(
// false, serviceNames, 1, 0 ).get( "data" ) );
// this will grab all entries stored
fullCollectionJson.set( "process", serviceCollector.getCSVdata( false, null, 1, 0 ).get( "data" ) );
ServiceCollector applicationCollector = csapApp.getServiceCollector( csapApp
.getFirstJmxStatsKey() );
String[] javaJmxServices = csapApp.getActiveModel()
.getServicesOnHost( Application.getHOST_NAME() )
.filter( (ServiceInstance::isPerformJmxCollection) )
.map( ServiceInstance::getServiceName_Port )
.collect( Collectors.toList() )
.stream().toArray( String[]::new );
ObjectNode lastJmx = applicationCollector.getCSVdata( false, javaJmxServices, 1, 0 );
if ( lastJmx.has( "data" ) ) {
fullCollectionJson.set( "jmxCommon", lastJmx.get( "data" ) );
} else {
logger.warn( "JMX collection does not contain data: {}. \n\t Services: {}",
lastJmx.toString(), Arrays.asList( javaJmxServices ) );
fullCollectionJson.set( "jmxCommon", lastJmx );
}
ObjectNode jmxCustom = fullCollectionJson.putObject( "jmxCustom" );
csapApp.getActiveModel()
.getServicesOnHost( Application.getHOST_NAME() )
.filter( ServiceInstance::hasServiceMeters )
.forEach( serviceInstance -> {
String[] serviceArray = { serviceInstance.getServiceName_Port() };
jmxCustom.set( serviceInstance.getServiceName(),
applicationCollector.getCSVdata( false, serviceArray, 1, 0, "custom" )
.get( "data" ) );
} );
} else {
fullCollectionJson.put( "warning", "VM is in manager mode" );
}
return fullCollectionJson;
}
示例15: buildJmxReports
import com.fasterxml.jackson.databind.node.ObjectNode; //导入方法依赖的package包/类
public void buildJmxReports ( boolean isUpdateSummary, int requestedSampleSize, List<String> servicesFilter,
ObjectNode dataNode, int numSamples ) {
ObjectNode currSummary = jacksonMapper.createObjectNode();
// standard JMX collections
for ( String serviceName : servicesFilter ) {
ObjectNode serviceCacheNode = jmxResultsCache
.get( serviceName );
if ( serviceCacheNode != null ) {
String sumName = serviceName;
int index = sumName.indexOf( "_" );
if ( index != -1 ) {
sumName = sumName.substring( 0, index );
}
ObjectNode serviceSummaryJson = currSummary.putObject( sumName );
serviceSummaryJson.put( "numberOfSamples", numSamples );
for ( JmxCommonEnum jmxMetric : JmxCommonEnum.values() ) {
String metricFullName = jmxMetric.value + "_"
+ serviceName;
ArrayNode cacheArray = (ArrayNode) serviceCacheNode
.get( metricFullName );
if ( cacheArray == null ) {
continue;
}
ArrayNode metricArray = dataNode
.putArray( metricFullName );
if ( requestedSampleSize == -1 ) {
metricArray.addAll( cacheArray );
} else {
long metricTotal = 0;
for ( int i = 0; i < requestedSampleSize
&& i < cacheArray.size(); i++ ) {
metricArray.add( cacheArray.get( i ) );
metricTotal += cacheArray
.get( i )
.asLong();
}
serviceSummaryJson.put( jmxMetric.value, metricTotal );
}
}
}
}
addSummary( currSummary, isUpdateSummary );
}