Java 类com.fasterxml.jackson.databind.node.ObjectNode 实例源码
项目:athena
文件:RegionCodec.java
@Override
public ObjectNode encode(Region region, CodecContext context) {
checkNotNull(region, NULL_REGION_MSG);
ObjectNode result = context.mapper().createObjectNode()
.put(REGION_ID, region.id().toString())
.put(NAME, region.name())
.put(TYPE, region.type().toString());
ArrayNode masters = context.mapper().createArrayNode();
region.masters().forEach(sets -> {
ArrayNode setsJson = context.mapper().createArrayNode();
sets.forEach(nodeId -> setsJson.add(nodeId.toString()));
masters.add(setsJson);
});
result.set(MASTERS, masters);
return result;
}
项目:iot-edge-greengrass
文件:MqttGatewayService.java
@Override
public void onDeviceRpcResponse(RpcCommandResponse response) {
final int msgId = msgIdSeq.incrementAndGet();
int requestId = response.getRequestId();
String deviceName = response.getDeviceName();
String data = response.getData();
checkDeviceConnected(deviceName);
ObjectNode node = newNode();
node.put("id", requestId);
node.put("device", deviceName);
node.put("data", data);
MqttMessage msg = new MqttMessage(toBytes(node));
msg.setId(msgId);
publishAsync(GATEWAY_RPC_TOPIC, msg,
token -> {
log.debug("[{}][{}] RPC response from device was delivered!", deviceName, requestId);
},
error -> {
log.warn("[{}][{}] Failed to report RPC response from device!", deviceName, requestId, error);
});
}
项目:premier-wherehows
文件:Dataset.java
public static Result getDatasetColumnByID(int datasetId, int columnId)
{
List<DatasetColumn> datasetColumnList = DatasetsDAO.getDatasetColumnByID(datasetId, columnId);
ObjectNode result = Json.newObject();
if (datasetColumnList != null && datasetColumnList.size() > 0)
{
result.put("status", "ok");
result.set("columns", Json.toJson(datasetColumnList));
}
else
{
result.put("status", "error");
result.put("message", "record not found");
}
return ok(result);
}
项目:exam
文件:UserController.java
@Restrict({@Group("TEACHER"), @Group("ADMIN")})
public Result getUsersByRole(String role) {
List<User> users = Ebean.find(User.class)
.where()
.eq("roles.name", role)
.orderBy("lastName")
.findList();
ArrayNode array = JsonNodeFactory.instance.arrayNode();
for (User u : users) {
ObjectNode part = Json.newObject();
part.put("id", u.getId());
part.put("name", String.format("%s %s", u.getFirstName(), u.getLastName()));
array.add(part);
}
return ok(Json.toJson(array));
}
项目:hypergraphql
文件:HGraphQLService.java
private Model getModelFromRemote(String graphQlQuery) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode bodyParam = mapper.createObjectNode();
// bodyParam.set("operationName", null);
// bodyParam.set("variables", null);
bodyParam.put("query", graphQlQuery);
Model model = ModelFactory.createDefaultModel();
try {
HttpResponse<InputStream> response = Unirest.post(url)
.header("Accept", "application/rdf+xml")
.body(bodyParam.toString())
.asBinary();
model.read(response.getBody(), "RDF/XML");
} catch (UnirestException e) {
e.printStackTrace();
}
return model;
}
项目:athena
文件:ControlMetricsWebResource.java
/**
* 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() {
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();
}
项目:athena
文件:ForwardingObjectiveCodecTest.java
/**
* Tests encoding of a ForwardingObjective object.
*/
@Test
public void testForwardingObjectiveEncode() {
Criterion criterion1 = Criteria.matchVlanId(VlanId.ANY);
Criterion criterion2 = Criteria.matchEthType((short) 0x8844);
TrafficSelector selector = DefaultTrafficSelector.builder()
.add(criterion1)
.add(criterion2)
.build();
ForwardingObjective forwardingObj = DefaultForwardingObjective.builder()
.makePermanent()
.fromApp(APP_ID)
.withPriority(60)
.withFlag(ForwardingObjective.Flag.SPECIFIC)
.nextStep(1)
.withSelector(selector)
.add();
ObjectNode forwardingObjJson = forwardingObjectiveCodec.encode(forwardingObj, context);
assertThat(forwardingObjJson, matchesForwardingObjective(forwardingObj));
}
项目:athena
文件:DistributedNetworkConfigStore.java
@Activate
public void activate() {
KryoNamespace.Builder kryoBuilder = new KryoNamespace.Builder()
.register(KryoNamespaces.API)
.register(ConfigKey.class, ObjectNode.class, ArrayNode.class,
JsonNodeFactory.class, LinkedHashMap.class,
TextNode.class, BooleanNode.class,
LongNode.class, DoubleNode.class, ShortNode.class, IntNode.class,
NullNode.class);
configs = storageService.<ConfigKey, JsonNode>consistentMapBuilder()
.withSerializer(Serializer.using(kryoBuilder.build()))
.withName("onos-network-configs")
.withRelaxedReadConsistency()
.build();
configs.addListener(listener);
log.info("Started");
}
项目:wherehowsX
文件:DatasetsDAO.java
public static boolean favorite(int id, String user)
{
ObjectNode resultNode = Json.newObject();
boolean result = false;
Integer userId = UserDAO.getUserIDByUserName(user);
if (userId != null && userId !=0)
{
int row = getJdbcTemplate().update(FAVORITE_A_DATASET, userId, id);
if (row > 0)
{
result = true;
}
}
return result;
}
项目:athena
文件:EncodeInstructionCodecHelper.java
/**
* Encode an L1 modification instruction.
*
* @param result json node that the instruction attributes are added to
*/
private void encodeL1(ObjectNode result) {
L1ModificationInstruction l1Instruction = (L1ModificationInstruction) instruction;
result.put(InstructionCodec.SUBTYPE, l1Instruction.subtype().name());
switch (l1Instruction.subtype()) {
case ODU_SIGID:
final L1ModificationInstruction.ModOduSignalIdInstruction oduSignalIdInstruction =
(L1ModificationInstruction.ModOduSignalIdInstruction) l1Instruction;
OduSignalId oduSignalId = oduSignalIdInstruction.oduSignalId();
ObjectNode child = result.putObject("oduSignalId");
child.put(InstructionCodec.TRIBUTARY_PORT_NUMBER, oduSignalId.tributaryPortNumber());
child.put(InstructionCodec.TRIBUTARY_SLOT_LEN, oduSignalId.tributarySlotLength());
child.put(InstructionCodec.TRIBUTARY_SLOT_BITMAP,
HexString.toHexString(oduSignalId.tributarySlotBitmap()));
break;
default:
log.info("Cannot convert L1 subtype of {}", l1Instruction.subtype());
break;
}
}
项目:csap-core
文件:HostStatusManager.java
public ObjectNode getServiceRuntime ( String hostName, String serviceName_port ) {
if ( hostResponseMap.containsKey( hostName ) ) {
try {
ObjectNode hostRuntime = hostResponseMap.get( hostName );
if ( hostRuntime.has( "error" ) ) {
return null;
} else {
ObjectNode serviceNode = (ObjectNode) hostRuntime
.path( HostKeys.services.jsonId );
if ( serviceNode == null || !serviceNode.has( serviceName_port ) ) {
return null;
}
return (ObjectNode) serviceNode.path( serviceName_port );
}
} catch (Exception e) {
logger.error( "Failed reading", e );
}
}
return null;
}
项目:csap-core
文件:AgentApi.java
@CsapDoc ( notes = { "Host disk usage", "* Agent service only" } )
@GetMapping ( "/diskUsage" )
public ObjectNode diskUsage ()
throws JsonGenerationException, JsonMappingException,
IOException {
ObjectNode diskInfo = jacksonMapper.createObjectNode();
if ( Application.isJvmInManagerMode() ) {
diskInfo.put( "error",
"Disk Usage is only enabled on CsAgent urls. Use /admin/api/hosts, then /CsAgent/api/diskUsage on host. CSAP Command Runner UI can be used to run on all VMS at same time." );
} else {
diskInfo.set( Application.getHOST_NAME(), osManager.getCachedFileSystemInfo() );
}
return diskInfo;
}
项目:athena
文件:GroupCodecTest.java
@Test
public void codecEncodeTest() {
GroupBucket bucket1 = DefaultGroupBucket
.createSelectGroupBucket(DefaultTrafficTreatment.emptyTreatment());
GroupBucket bucket2 = DefaultGroupBucket
.createIndirectGroupBucket(DefaultTrafficTreatment.emptyTreatment());
GroupBuckets buckets = new GroupBuckets(ImmutableList.of(bucket1, bucket2));
DefaultGroup group = new DefaultGroup(
new DefaultGroupId(1),
NetTestTools.did("d1"),
GroupDescription.Type.INDIRECT,
buckets);
MockCodecContext context = new MockCodecContext();
GroupCodec codec = new GroupCodec();
ObjectNode groupJson = codec.encode(group, context);
assertThat(groupJson, matchesGroup(group));
}
项目:BIMplatform
文件:QueryObjectProvider.java
public static QueryObjectProvider fromJsonNode(CatalogService catalogService, VirtualObjectService virtualObjectService, PlatformServer server, JsonNode fullQuery, Integer rid, PackageMetaData packageMetaData) throws JsonParseException, JsonMappingException, IOException, QueryException {
if (fullQuery instanceof ObjectNode) {
JsonQueryObjectModelConverter converter = new JsonQueryObjectModelConverter(packageMetaData);
Query query = converter.parseJson("query", (ObjectNode) fullQuery);
return new QueryObjectProvider(catalogService, virtualObjectService, server, query, rid, packageMetaData);
} else {
throw new QueryException("Query root must be of type object");
}
}
项目:athena
文件:PortCodec.java
/**
* {@inheritDoc}
*
* Note: Result of {@link Port#element()} returned Port object,
* is not a full Device object.
* Only it's DeviceId can be used.
*/
@Override
public Port decode(ObjectNode json, CodecContext context) {
if (json == null || !json.isObject()) {
return null;
}
DeviceId did = DeviceId.deviceId(json.get(ELEMENT).asText());
Device device = new DummyDevice(did);
PortNumber number = portNumber(json.get(PORT_NAME).asText());
boolean isEnabled = json.get(IS_ENABLED).asBoolean();
Type type = Type.valueOf(json.get(TYPE).asText().toUpperCase());
long portSpeed = json.get(PORT_SPEED).asLong();
Annotations annotations = extractAnnotations(json, context);
return new DefaultPort(device, number, isEnabled, type, portSpeed, annotations);
}
项目:premier-wherehows
文件:DatasetsDAO.java
public static boolean unfavorite(int id, String user)
{
ObjectNode resultNode = Json.newObject();
boolean result = false;
Integer userId = UserDAO.getUserIDByUserName(user);
if (userId != null && userId !=0)
{
int row = getJdbcTemplate().update(UNFAVORITE_A_DATASET, userId, id);
if (row > 0)
{
result = true;
}
}
return result;
}
项目:travny
文件:SimpleJsonWriter.java
@Override
protected JsonNode createMapNode(MapSchema mapSchema, Map value) throws IOException {
Preconditions.checkNotNull(mapSchema);
Preconditions.checkNotNull(value);
Schema keySchema = mapSchema.getKeySchema();
switch (keySchema.getType()) {
case RECORD:
case MAP:
case LIST:
return super.createMapNode(mapSchema, value);
}
ObjectNode node = mapper.createObjectNode();
for (Map.Entry e : (Set<Map.Entry>) value.entrySet()) {
Object k = e.getKey();
Object v = e.getValue();
JsonNode val = serializeValue(mapSchema.getValueSchema(), v);
node.set(keyToString(mapSchema.getKeySchema(), k), val);
}
return node;
}
项目:marklogic-rdf4j
文件:ConnectedRESTQA.java
public static void addRangeElementIndex(String dbName, String type, String namespace, String localname,boolean positions) throws Exception{
ObjectMapper mapper = new ObjectMapper();
ObjectNode mainNode = mapper.createObjectNode();
// ObjectNode childNode = mapper.createObjectNode();
ArrayNode childArray = mapper.createArrayNode();
ObjectNode childNodeObject = mapper.createObjectNode();
childNodeObject.put( "scalar-type", type);
childNodeObject.put( "namespace-uri", namespace);
childNodeObject.put( "localname", localname);
childNodeObject.put( "collation", "");
childNodeObject.put("range-value-positions", positions);
childNodeObject.put("invalid-values", "reject");
childArray.add(childNodeObject);
mainNode.putArray("range-element-index").addAll(childArray);
// mainNode.put("range-element-indexes", childNode);
// System.out.println(type + mainNode.path("range-element-indexes").path("range-element-index").toString());
setDatabaseProperties(dbName,"range-element-index",mainNode);
}
项目:athena
文件:MeterBandCodec.java
@Override
public ObjectNode encode(Band band, CodecContext context) {
checkNotNull(band, "Band cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(TYPE, band.type().toString())
.put(RATE, band.rate())
.put(PACKETS, band.packets())
.put(BYTES, band.bytes())
.put(BURST_SIZE, band.burst());
if (band.dropPrecedence() != null) {
result.put(PREC, band.dropPrecedence());
}
return result;
}
项目:crnk-framework
文件:JerseyApplicationTest.java
private Task getTaskFromJson(JsonNode node) throws JsonProcessingException {
if (node.isObject()) {
ObjectNode onode = (ObjectNode) node;
final JsonNode type = onode.remove("type");
final JsonNode attributes = onode.remove("attributes");
final JsonNode relationships = onode.remove("relationships");
final JsonNode links = onode.remove("links");
Iterator<Map.Entry<String, JsonNode>> fields = attributes.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> f = fields.next();
onode.put(f.getKey(), f.getValue().textValue());
}
return mapper.treeToValue(onode, Task.class);
}
else {
throw new JsonMappingException("Not an object: " + node);
}
}
项目:athena
文件:RouterCodec.java
@Override
public ObjectNode encode(Router router, CodecContext context) {
checkNotNull(router, "router cannot be null");
ObjectNode result = context
.mapper()
.createObjectNode()
.put("id", router.id().routerId())
.put("status", router.status().toString())
.put("name", router.name().toString())
.put("admin_state_up", router.adminStateUp())
.put("tenant_id", router.tenantId().toString())
.put("routes",
router.routes() == null ? null : router.routes()
.toString());
result.set("external_gateway_info",
router.externalGatewayInfo() == null ? null
: new RouterGatewayInfoCodec()
.encode(router.externalGatewayInfo(), context));
return result;
}
项目:athena
文件:XosManager.java
/**
* Returns the array of users for the subscriber.
*
* @return list of users
*/
public ArrayNode getUserList() {
log.info("getUserList() called");
String result = xosUtils.getRest("users/");
JsonNode node;
try {
node = MAPPER.readTree(result);
} catch (IOException e) {
log.error("failed to read user list JSON", e);
return null;
}
ObjectNode obj = (ObjectNode) node;
return (ArrayNode) obj.get("users");
}
项目:crnk-framework
文件:ClientResourceUpsert.java
@Override
protected void setRelationsField(Object newResource, RegistryEntry registryEntry, Map.Entry<String, Relationship> property, QueryAdapter queryAdapter, RepositoryMethodParameterProvider parameterProvider) {
Relationship relationship = property.getValue();
if (!relationship.getData().isPresent()) {
ObjectNode links = relationship.getLinks();
if (links != null) {
// create proxy to lazy load relations
String fieldName = property.getKey();
ResourceInformation resourceInformation = registryEntry.getResourceInformation();
ResourceField field = resourceInformation.findRelationshipFieldByName(fieldName);
Class elementType = field.getElementType();
Class collectionClass = field.getType();
JsonNode relatedNode = links.get("related");
if (relatedNode != null) {
String url = null;
if (relatedNode.has(SerializerUtil.HREF)) {
JsonNode hrefNode = relatedNode.get(SerializerUtil.HREF);
if (hrefNode != null) {
url = hrefNode.asText().trim();
}
}
else {
url = relatedNode.asText().trim();
}
Object proxy = proxyFactory.createCollectionProxy(elementType, collectionClass, url);
field.getAccessor().setValue(newResource, proxy);
}
}
} else {
// set elements
super.setRelationsField(newResource, registryEntry, property, queryAdapter, parameterProvider);
}
}
项目:athena
文件:DecodeBgpFlowExtnCodecHelper.java
@Override
public ExtFlowTypes decodeExtension(ObjectNode json) {
if (json == null || !json.isObject()) {
return null;
}
ExtIpProtocol.Builder resultBuilder = new DefaultExtIpProtocol.Builder();
String protocols = nullIsIllegal(json.get(BgpFlowExtensionCodec.PROTOCOLS),
BgpFlowExtensionCodec.PROTOCOLS + MISSING_MEMBER_MESSAGE).asText();
resultBuilder.setIpProtocol(parse.parseIpProtocol(protocols));
resultBuilder.setType(ExtFlowTypes.ExtType.IP_PROTO_LIST);
return resultBuilder.build();
}
项目:athena
文件:OpensatckRouterWebResource.java
@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateRouter(@PathParam("id") String id, InputStream input) {
checkNotNull(input);
try {
ObjectMapper mapper = new ObjectMapper();
ObjectNode routerNode = (ObjectNode) mapper.readTree(input);
OpenstackRouter or = ROUTER_CODEC.decode(routerNode, this);
OpenstackRouter.Builder osBuilder = new OpenstackRouter.Builder()
.tenantId(or.tenantId())
.id(id)
.name(or.name())
.status(OpenstackRouter.RouterStatus.ACTIVE)
.adminStateUp(Boolean.valueOf(or.adminStateUp()))
.gatewayExternalInfo(or.gatewayExternalInfo());
OpenstackRoutingService routingService
= getService(OpenstackRoutingService.class);
routingService.updateRouter(osBuilder.build());
log.debug("REST API UPDATE router is called from router {}", input.toString());
return Response.status(Response.Status.OK).build();
} catch (Exception e) {
log.error("Updates Router failed because of exception {}",
e.toString());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.toString())
.build();
}
}
项目:centraldogma
文件:MoveOperation.java
@Override
JsonNode apply(final JsonNode node) {
if (from.equals(path)) {
return node;
}
if (node.at(from).isMissingNode()) {
throw new JsonPatchException("non-existent source path: " + from);
}
final JsonNode sourceParent = ensureSourceParent(node, from);
// Remove
final String raw = from.last().getMatchingProperty();
final JsonNode source;
if (sourceParent.isObject()) {
source = ((ObjectNode) sourceParent).remove(raw);
} else {
source = ((ArrayNode) sourceParent).remove(Integer.parseInt(raw));
}
// Add
if (path.toString().isEmpty()) {
return source;
}
final JsonNode targetParent = ensureTargetParent(node, path);
return targetParent.isArray() ? AddOperation.addToArray(path, node, source)
: AddOperation.addToObject(path, node, source);
}
项目:premier-wherehows
文件:PropertyController.java
public static Result getProperty(String base, String attr, String name) {
ObjectNode resultJson = Json.newObject();
try {
if (name != null) {
String result = PropertyDao.getProp(base, attr, name);
resultJson.put("return_code", 200);
resultJson.put("color", result);
}
} catch (Exception e) {
ContrUtil.failure(resultJson, e.getMessage());
Logger.error(e.getMessage());
}
return ok(resultJson);
}
项目:athena
文件:MastershipRoleCodec.java
@Override
public ObjectNode encode(MastershipRole mastershipRole, CodecContext context) {
checkNotNull(mastershipRole, "MastershipRole cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(ROLE, mastershipRole.name());
return result;
}
项目:wherehowsX
文件:AdvSearch.java
public static Result getFlowNames()
{
ObjectNode result = Json.newObject();
String apps = request().getQueryString("apps");
result.put("status", "ok");
result.set("flowNames", Json.toJson(AdvSearchDAO.getFlowNames(apps)));
return ok(result);
}
项目:csap-core
文件:Service_Collection_Test.java
@Test
public void verify_agent_standard_collection ()
throws Exception {
logger.info( InitializeLogging.TC_HEAD );
if ( !isSetupOk() )
return;
String[] services = { "CsAgent_8011" };
ObjectNode standardJavaCollection = performJavaCommonCollection( services, testAdminHost1 );
logger.info( "collected: \n {}", CSAP.jsonPrint( jacksonMapper, standardJavaCollection ) );
ArrayList<String> servicesAvailable = jacksonMapper.readValue(
standardJavaCollection.at( "/attributes/servicesAvailable" ).traverse(),
new TypeReference<ArrayList<String>>() {
} );
assertThat( servicesAvailable )
.as( "servicesAvailable" )
.contains( "CsAgent_8011" );
assertThat( standardJavaCollection.at( "/data/openFiles_CsAgent_8011/0" ).asInt() )
.as( "open files" )
.isGreaterThan( 100 );
assertThat( standardJavaCollection.at( "/data/heapUsed_CsAgent_8011/0" ).asInt() )
.as( "heap used" )
.isGreaterThan( 10 );
}
项目:kafka-0.11.0.0-src-with-comment
文件:JsonConverter.java
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
Object enableConfigsVal = configs.get(SCHEMAS_ENABLE_CONFIG);
if (enableConfigsVal != null)
enableSchemas = enableConfigsVal.toString().equals("true");
serializer.configure(configs, isKey);
deserializer.configure(configs, isKey);
Object cacheSizeVal = configs.get(SCHEMAS_CACHE_SIZE_CONFIG);
if (cacheSizeVal != null)
cacheSize = Integer.parseInt((String) cacheSizeVal);
fromConnectSchemaCache = new SynchronizedCache<>(new LRUCache<Schema, ObjectNode>(cacheSize));
toConnectSchemaCache = new SynchronizedCache<>(new LRUCache<JsonNode, Schema>(cacheSize));
}
项目:localcloud_fe
文件:ApplicationConfig.java
private String generateJson() {
JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
ObjectNode json = (ObjectNode) contentConfig.toJson();
json.set(JsonKeys.STORE_PACKAGE_IDENTIFIER, nodeFactory.textNode(storeIdentifier));
return json.toString();
}
项目:premier-wherehows
文件:DatasetController.java
@BodyParser.Of(BodyParser.Json.class)
public static Result removeDataset() {
JsonNode dataset = request().body().asJson();
ObjectNode resultJson = Json.newObject();
try {
DatasetDao.removeDataset(dataset);
resultJson.put("return_code", 200);
resultJson.put("message", "dataset removed");
} catch (Exception e) {
Logger.error("exception when trying to remove dataset:", e);
ContrUtil.failure(resultJson, e.getMessage());
}
return ok(resultJson);
}
项目:demo-springboot
文件:KdsCrawlerService.java
private ObjectNode getNodeByUrl(String url) {
List<Post> posts = getPostList(url);
ObjectNode objectNode = JsonUtil.createObjectNode();
objectNode.put("count", posts.size());
objectNode.putPOJO("posts", posts);
objectNode.put("date", DateUtil.getDateNow());
return objectNode;
}
项目:athena
文件:PortChainCodec.java
@Override
public ObjectNode encode(PortChain portChain, CodecContext context) {
checkNotNull(portChain, "port pair cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(ID, portChain.portChainId().toString())
.put(TENANT_ID, portChain.tenantId().toString())
.put(NAME, portChain.name())
.put(DESCRIPTION, portChain.description())
.put(PORT_PAIR_GROUPS, portChain.portPairGroups().toString())
.put(FLOW_CLASSIFIERS, portChain.flowClassifiers().toString());
return result;
}
项目:premier-wherehows
文件:PropertyController.java
@BodyParser.Of(BodyParser.Json.class)
public static Result putProperty(String base, String attr) {
JsonNode prop = request().body().asJson();
ObjectNode resultJson = Json.newObject();
try {
PropertyDao.updateProp(prop, base, attr, attr);
resultJson.put("return_code", 200);
resultJson.put("message", base + " " + attr + " updated!");
} catch (Exception e) {
ContrUtil.failure(resultJson, e.getMessage());
Logger.error(e.getMessage());
}
return ok(resultJson);
}
项目:bigchaindb-java-driver
文件:SignedBigchaindbTransactionFactory.java
static ObjectNode createJsonObject(final UnsignedBigchaindbTransaction unsignedTransaction,
final List<KeyPair> keyPairs) {
final ObjectNode transactionEnvelopeNode = createTransactionNode(unsignedTransaction, keyPairs);
transactionEnvelopeNode.set("version", jsonNodeFactory.textNode("0.9"));
transactionEnvelopeNode.set("id", jsonNodeFactory.textNode(createTransactionId(transactionEnvelopeNode)));
addFulfillments(transactionEnvelopeNode, keyPairs);
return transactionEnvelopeNode;
}
项目:csap-core
文件:DefinitionRequests.java
private void addToPendingResources ( ObjectNode serviceNode, String serviceName ) {
// File resourceDir = csapApp.getResourcesFolder( serviceName );
File serviceResourceDir = csapApp.getResourcesWorkingFolder();
// only internal files are stored.
ArrayNode files = (ArrayNode) serviceNode.get( ServiceAttributes.files.value );
ArrayNode internalOnly = extractEmbeddedServiceFiles( files );
serviceNode.set( ServiceAttributes.files.value, internalOnly );
files.forEach( propFile -> {
String targetLife = propFile.get( ServiceAttributes.FileAttributes.lifecycle.json ).asText();
String targetName = propFile.get( ServiceAttributes.FileAttributes.name.json ).asText();
String targetPath = serviceName + "/resources/" + targetLife + "/" + targetName;
if ( propFile.has( ServiceAttributes.FileAttributes.external.json )
&& propFile.get( ServiceAttributes.FileAttributes.external.json ).asBoolean() ) {
if ( propFile.has( ServiceAttributes.FileAttributes.newFile.json )
&& propFile.get( ServiceAttributes.FileAttributes.newFile.json ).asBoolean() ) {
writePropertyFile( serviceResourceDir, targetPath, propFile );
csapApp.getPendingResourceAdds().add( targetPath );
} else if ( propFile.has( ServiceAttributes.FileAttributes.contentUpdated.json )
&& propFile.get( ServiceAttributes.FileAttributes.contentUpdated.json ).asBoolean() ) {
writePropertyFile( serviceResourceDir, targetPath, propFile );
}
if ( propFile.has( ServiceAttributes.FileAttributes.deleteFile.json )
&& propFile.get( ServiceAttributes.FileAttributes.deleteFile.json ).asBoolean() ) {
csapApp.getPendingResourceDeletes().add( targetPath );
}
}
} );
logger.info( "Pending Operations: {}", csapApp.getPendingResourceOperations() );
}
项目:athena
文件:CriterionCodecTest.java
/**
* Tests source SCTP criterion.
*/
@Test
public void matchSctpSrcTest() {
Criterion criterion = Criteria.matchSctpSrc(tpPort);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
}
项目:BIMplatform
文件:JsonQueryObjectModelConverter.java
private double checkFloat(ObjectNode node, String key) throws QueryException {
if (!node.has(key)) {
throw new QueryException("\"" + key + "\" not found on \"inBoundingBox\"");
}
JsonNode jsonNode = node.get(key);
if (jsonNode.isNumber()) {
return jsonNode.asDouble();
} else {
throw new QueryException("\"" + key + "\" should be of type number");
}
}