@Test public void applyGeneratesDate() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "string"); TextNode formatNode = TextNode.valueOf("date-time"); objectNode.set("format", formatNode); JType mockDateType = mock(JType.class); FormatRule mockFormatRule = mock(FormatRule.class); when(mockFormatRule.apply(eq("fooBar"), eq(formatNode), Mockito.isA(JType.class), isNull(Schema.class))).thenReturn(mockDateType); when(ruleFactory.getFormatRule()).thenReturn(mockFormatRule); JType result = rule.apply("fooBar", objectNode, jpackage, null); assertThat(result, equalTo(mockDateType)); }
public Selector deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { ObjectMapper mapper = (ObjectMapper) p.getCodec(); ObjectNode obj = mapper.readTree(p); String typeName; if (obj.get("@type").isArray()) { // Find the actual selector type typeName = StreamSupport.stream(obj.get("@type").spliterator(), false) .filter(v -> !v.textValue().equals("cnt:ContentAsText")) .findFirst().orElse(new TextNode("UNKNOWN")).textValue(); // Make @type a text value so that Jackson doesn't bail out further down the line obj.set("@type", new TextNode(typeName)); } else { typeName = obj.get("@type").textValue(); } if (MAPPING.containsKey(typeName)) { return mapper.treeToValue(obj, MAPPING.get(typeName)); } else { throw new IllegalArgumentException("Cannot deserialize Selector."); } }
private ObjectNode getComponentMeta(ClassLoader classLoader) { Properties properties = loadComponentProperties(classLoader); if (properties == null) { return null; } String components = (String) properties.get("components"); if (components == null) { return null; } String[] part = components.split("\\s"); ObjectNode componentMeta = new ObjectNode(JsonNodeFactory.instance); for (String scheme : part) { // find the class name String javaType = extractComponentJavaType(classLoader, scheme); if (javaType == null) { continue; } String schemeMeta = loadComponentJSonSchema(classLoader, scheme, javaType); if (schemeMeta == null) { continue; } componentMeta.set(scheme, new TextNode(schemeMeta)); } return componentMeta.size() > 0 ? componentMeta : null; }
public static JsonNode get( final PrimitiveObject obj ) throws IOException{ switch( obj.getPrimitiveType() ){ case BOOLEAN: return BooleanNode.valueOf( obj.getBoolean() ); case BYTE: return IntNode.valueOf( obj.getInt() ); case SHORT: return IntNode.valueOf( obj.getInt() ); case INTEGER: return IntNode.valueOf( obj.getInt() ); case LONG: return new LongNode( obj.getLong() ); case FLOAT: return new DoubleNode( obj.getDouble() ); case DOUBLE: return new DoubleNode( obj.getDouble() ); case STRING: return new TextNode( obj.getString() ); case BYTES: return new BinaryNode( obj.getBytes() ); default: return new TextNode( null ); } }
@Test(expected = WebApplicationException.class) public void testMappingException() throws Exception { final ObjectMapper om = mock(ObjectMapper.class); when(om.writeValueAsString(any())).thenThrow(new JsonProcessingException("ignore me") { private static final long serialVersionUID = 1L; @Override public StackTraceElement[] getStackTrace() { return new StackTraceElement[] {}; } }); uut = new FactsTransactionsResource(mock(FactStore.class), om); final FactTransactionJson tx = new FactTransactionJson(); tx.facts(Arrays.asList(new FactJson().payload(TextNode.valueOf("buh")))); uut.newTransaction(tx); }
@Activate public void activate() { Serializer serializer = Serializer.using(KryoNamespaces.API, ObjectNode.class, ArrayNode.class, JsonNodeFactory.class, LinkedHashMap.class, TextNode.class, BooleanNode.class, LongNode.class, DoubleNode.class, ShortNode.class, IntNode.class, NullNode.class); prefsConsistentMap = storageService.<String, ObjectNode>consistentMapBuilder() .withName(ONOS_USER_PREFERENCES) .withSerializer(serializer) .withRelaxedReadConsistency() .build(); prefsConsistentMap.addListener(prefsListener); prefs = prefsConsistentMap.asJavaMap(); register(core); log.info("Started"); }
@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"); }
/** * Gets the details of an input or output * @param inputOutput The node of the particular input or output * @return An CWLElement object with the label, doc and type extracted */ private CWLElement getDetails(JsonNode inputOutput) { if (inputOutput != null) { CWLElement details = new CWLElement(); // Shorthand notation "id: type" - no label/doc/other params if (inputOutput.getClass() == TextNode.class) { details.setType(inputOutput.asText()); } else { details.setLabel(extractLabel(inputOutput)); details.setDoc(extractDoc(inputOutput)); extractSource(inputOutput).forEach(details::addSourceID); details.setDefaultVal(extractDefault(inputOutput)); // Type is only for inputs if (inputOutput.has(TYPE)) { details.setType(extractTypes(inputOutput.get(TYPE))); } } return details; } return null; }
/** * Map existing JsonRpcRequest to Jackson JsonNode. * * @param request the JsonRpcRequest * @return the ObjectNode */ public static ObjectNode map(JsonRpcRequest request) { if (request == null) { return null; } ObjectNode node = new ObjectNode(JsonNodeFactory.instance); // Set protocol version node.set("jsonrpc", JSON_RPC_VERSION); // Set method node.set("method", new TextNode(request.getMethod())); // Set id if (request.getId() != null) { node.set("id", new TextNode(request.getId())); } // Set Params Map<String, String> params = request.getParams(); if (params != null && !params.isEmpty()) { ObjectMapper mapper = new ObjectMapper(); node.set("params", mapper.valueToTree(params)); } return node; }
@Test public void shouldUpdateNameSuccessfully() throws Exception { String serviceId = randomUuid(); String nameToUpdate = "new-name"; ServiceUpdateRequest request = ServiceUpdateRequest.from(new ObjectNode(JsonNodeFactory.instance, ImmutableMap.of( "path", new TextNode("name"), "value", new TextNode(nameToUpdate), "op", new TextNode("replace")))); ServiceEntity serviceEntity = mock(ServiceEntity.class); when(serviceDao.findByExternalId(serviceId)).thenReturn(Optional.of(serviceEntity)); when(serviceEntity.toService()).thenReturn(Service.from()); Optional<Service> maybeService = updater.doUpdate(serviceId, request); assertThat(maybeService.isPresent(), is(true)); verify(serviceEntity, times(1)).setName(nameToUpdate); verify(serviceDao, times(1)).merge(serviceEntity); }
@Test public void testEntityCreationSuccess() { String collectionName = "ect" + System.currentTimeMillis(); String entityName = "testEntity1"; HashMap<String,JsonNode> map = new HashMap<>(); map.put("name",new TextNode(entityName)); map.put("color",new TextNode("red")); map.put("shape",new TextNode("square")); UsergridEntity entity = new UsergridEntity(collectionName,null,map); UsergridResponse response = entity.save(); assertNull(response.getResponseError()); UsergridEntity eLookUp = Usergrid.GET(collectionName, entityName).first(); assertNotNull("The returned entity is null!", eLookUp); assertEquals("entities has the correct type", eLookUp.getType(),collectionName); assertEquals("entities has the correct name", eLookUp.getName(),entityName); assertEquals("entities has the correct color", eLookUp.getStringProperty("color"),"red"); assertEquals("entities has the correct shape", eLookUp.getStringProperty("shape"),"square"); }
@Override public GoalState deserialize( JsonParser p, DeserializationContext ctxt) throws IOException, JsonParseException { String value = ((TextNode) p.getCodec().readTree(p)).textValue(); if (value.equals("FINISHED") || value.equals("ONCE")) { return referenceTerminalGoalState; } else if (value.equals("FINISH")) { return GoalState.FINISH; } else if (value.equals("RUNNING")) { return GoalState.RUNNING; } else { logger.warn("Found unknown goal state in config store: {}", value); return GoalState.UNKNOWN; } }
@NotNull public static UsergridDevice getSharedDevice(@NotNull final Context context) { if (sharedDevice == null) { sharedDevice = UsergridSharedDevice.getStoredSharedDevice(context); if (sharedDevice == null) { String sharedDeviceId = UsergridSharedDevice.getSharedDeviceUUID(context); HashMap<String, JsonNode> map = new HashMap<String, JsonNode>(); map.put("uuid", new TextNode(sharedDeviceId)); sharedDevice = new UsergridDevice(map); sharedDevice.setModel(Build.MODEL); sharedDevice.setPlatform("android"); sharedDevice.setOsVersion(Build.VERSION.RELEASE); } } return sharedDevice; }
@Test public void deserialize() throws Exception { StratumMessage m1 = readValue("{\"id\":123, \"method\":\"a.b\", \"params\":[1, \"x\", null]}"); assertEquals(123L, (long)m1.id); assertEquals("a.b", m1.method); assertEquals(Lists.newArrayList(new IntNode(1), new TextNode("x"), NullNode.getInstance()), m1.params); StratumMessage m2 = readValue("{\"id\":123, \"result\":{\"x\": 123}}"); assertTrue(m2.isResult()); assertEquals(123L, (long)m2.id); assertEquals(mapper.createObjectNode().put("x", 123), m2.result); StratumMessage m3 = readValue("{\"id\":123, \"result\":[\"x\"]}"); assertEquals(123L, (long)m3.id); //noinspection AssertEqualsBetweenInconvertibleTypes assertEquals(mapper.createArrayNode().add("x"), m3.result); }
@Test public void createActitvityExtract() throws Exception { MarketoResponse<ObjectNode> marketoResponse = new MarketoResponse<>(); marketoResponse.setSuccess(true); Date startDate = new Date(1506865856000L); Date endDate = new Date(1507297856000L); ObjectNode bulkExtractResult = OBJECT_MAPPER.createObjectNode(); bulkExtractResult.set("exportId", new TextNode("bulkExtractId")); marketoResponse.setResult(Arrays.asList(bulkExtractResult)); ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class); Mockito.doReturn(marketoResponse).when(marketoRestClient).doPost(Mockito.eq(END_POINT + MarketoRESTEndpoint.CREATE_ACTIVITY_EXTRACT.getEndpoint()), Mockito.isNull(Map.class), Mockito.isNull(ImmutableListMultimap.class), argumentCaptor.capture(), Mockito.any(MarketoResponseJetty92EntityReader.class)); String bulkExtractId = marketoRestClient.createActivityExtract(startDate, endDate); Assert.assertEquals("bulkExtractId", bulkExtractId); String postContent = argumentCaptor.getValue(); ObjectNode marketoBulkExtractRequest = (ObjectNode) OBJECT_MAPPER.readTree(postContent); ObjectNode filter = (ObjectNode) marketoBulkExtractRequest.get("filter"); Assert.assertTrue(filter.has("createdAt")); }
@Test public void waitLeadExportJobTimeOut() throws Exception { String bulkExportId = "bulkExportId"; Map<String, String> pathParams = new HashMap<>(); pathParams.put("export_id", bulkExportId); MarketoResponse<ObjectNode> marketoResponse = Mockito.mock(MarketoResponse.class); Mockito.when(marketoResponse.isSuccess()).thenReturn(true); ObjectNode result = Mockito.mock(ObjectNode.class); Mockito.when(marketoResponse.getResult()).thenReturn(Arrays.asList(result)); Mockito.when(result.get("status")).thenReturn(new TextNode("Queued")).thenReturn(new TextNode("Processing")); Mockito.doReturn(marketoResponse).when(marketoRestClient).doGet(Mockito.eq(END_POINT + MarketoRESTEndpoint.GET_LEAD_EXPORT_STATUS.getEndpoint(pathParams)), Mockito.isNull(Map.class), Mockito.isNull(ImmutableListMultimap.class), Mockito.any(MarketoResponseJetty92EntityReader.class)); try { marketoRestClient.waitLeadExportJobComplete(bulkExportId, 2, 4); } catch (DataException e) { Assert.assertTrue(e.getMessage().contains("Job timeout exception")); Mockito.verify(marketoRestClient, Mockito.times(2)).doGet(Mockito.eq(END_POINT + MarketoRESTEndpoint.GET_LEAD_EXPORT_STATUS.getEndpoint(pathParams)), Mockito.isNull(Map.class), Mockito.isNull(ImmutableListMultimap.class), Mockito.any(MarketoResponseJetty92EntityReader.class)); return; } Assert.fail(); }
@Test public void waitLeadExportJobFailed() throws Exception { String bulkExportId = "bulkExportId"; Map<String, String> pathParams = new HashMap<>(); pathParams.put("export_id", bulkExportId); MarketoResponse<ObjectNode> marketoResponse = Mockito.mock(MarketoResponse.class); Mockito.when(marketoResponse.isSuccess()).thenReturn(true); ObjectNode result = Mockito.mock(ObjectNode.class); Mockito.when(marketoResponse.getResult()).thenReturn(Arrays.asList(result)); Mockito.when(result.get("status")).thenReturn(new TextNode("Queued")).thenReturn(new TextNode("Failed")); Mockito.when(result.get("errorMsg")).thenReturn(new TextNode("ErrorMessage")); Mockito.doReturn(marketoResponse).when(marketoRestClient).doGet(Mockito.eq(END_POINT + MarketoRESTEndpoint.GET_LEAD_EXPORT_STATUS.getEndpoint(pathParams)), Mockito.isNull(Map.class), Mockito.isNull(ImmutableListMultimap.class), Mockito.any(MarketoResponseJetty92EntityReader.class)); try { marketoRestClient.waitLeadExportJobComplete(bulkExportId, 1, 4); } catch (DataException e) { Assert.assertTrue(e.getMessage().contains("Bulk extract job failed")); Assert.assertTrue(e.getMessage().contains("ErrorMessage")); Mockito.verify(marketoRestClient, Mockito.times(2)).doGet(Mockito.eq(END_POINT + MarketoRESTEndpoint.GET_LEAD_EXPORT_STATUS.getEndpoint(pathParams)), Mockito.isNull(Map.class), Mockito.isNull(ImmutableListMultimap.class), Mockito.any(MarketoResponseJetty92EntityReader.class)); return; } Assert.fail(); }
public static ObjectNode fromPackage(String packageName) { ObjectNode generatedContext = JsonNodeFactory.withExactBigDecimals(true).objectNode(); FastClasspathScanner scanner = new FastClasspathScanner(packageName); scanner.matchAllStandardClasses((clazz) -> { if(!Modifier.isAbstract(clazz.getModifiers()) && AnnotationsUtils.isAnnotationPresent(clazz, JsonldTypeFromJavaClass.class)) { Optional<String> type = JsonldResourceUtils.dynamicTypeLookup(clazz); type.ifPresent(t ->generatedContext.set(clazz.getSimpleName(), TextNode.valueOf(t))); } if(AnnotationsUtils.isAnnotationPresent(clazz, ioinformarics.oss.jackson.module.jsonld.annotation.JsonldResource.class)) { Optional<ObjectNode> resourceContext = fromAnnotations(clazz); resourceContext.ifPresent((context) -> JsonUtils.merge(generatedContext, context)); } }); scanner.scan(); return (ObjectNode) JsonNodeFactory.withExactBigDecimals(true).objectNode().set("@context", generatedContext); }
public static Optional<ObjectNode> fromAnnotations(Class<?> objType) { ObjectNode generatedContext = JsonNodeFactory.withExactBigDecimals(true).objectNode(); generateNamespaces(objType).forEach((name, uri) -> generatedContext.set(name, new TextNode(uri))); //TODO: This is bad...it does not consider other Jackson annotations. Need to use a AnnotationIntrospector? final Map<String, JsonNode> fieldContexts = generateContextsForFields(objType); fieldContexts.forEach(generatedContext::set); //add links JsonldLink[] links = objType.getAnnotationsByType(JsonldLink.class); if (links != null) { for (int i = 0; i < links.length; i++) { com.fasterxml.jackson.databind.node.ObjectNode linkNode = JsonNodeFactory.withExactBigDecimals(true) .objectNode(); linkNode.set("@id", new TextNode(links[i].rel())); linkNode.set("@type", new TextNode("@id")); generatedContext.set(links[i].name(), linkNode); } } //Return absent optional if context is empty return generatedContext.size() != 0 ? Optional.of(generatedContext) : Optional.empty(); }
private void parseResources(JsonParser jParser, JsonGenerator jGenerator, String context) throws IOException { jGenerator.writeFieldName("resources"); jParser.nextToken(); // "[" jGenerator.writeStartArray(); // parse each resource ObjectMapper mapper = new ObjectMapper(); boolean first = true; while (jParser.nextToken() != JsonToken.END_ARRAY) { if (!first) { jGenerator.writeRaw(","); } ObjectNode annotationNode = mapper.readTree(jParser); String created = Instant.now().toString(); annotationNode.set("http://purl.org/dc/terms/created", new TextNode(created)); annotationNode.set("@context", new TextNode(context)); ObjectNode storedAnnotation = webAnnotationService.validateAndStore(annotationNode); jGenerator.writeRaw(new ObjectMapper().writeValueAsString(storedAnnotation)); first = false; } jGenerator.writeEndArray(); }
private void handleNextResource() throws IOException { if (jParser.nextToken() != JsonToken.END_ARRAY) { if (!firstField.get()) { deque.add(","); } firstField.set(false); ObjectNode annotationNode = new ObjectMapper().readTree(jParser); String created = Instant.now().toString(); annotationNode.set("http://purl.org/dc/terms/created", new TextNode(created)); annotationNode.set("@context", new TextNode(context)); ObjectNode storedAnnotation = webAnnotationService.validateAndStore(annotationNode); deque.add(new ObjectMapper().writeValueAsString(storedAnnotation)); } else { deque.add("]"); inResources.set(false); } }
/** * Executes a compiled instruction using the given context and JSON node. * Optionally hides all context above the JSON node, treating it as a root. * This is a helper method for formatters which need to execute templates to * produce their output. */ public static JsonNode executeTemplate(Context ctx, Instruction inst, JsonNode node, boolean privateContext) throws CodeExecuteException { // Temporarily swap the buffers to capture all output of the partial. StringBuilder buf = new StringBuilder(); StringBuilder origBuf = ctx.swapBuffer(buf); try { // If we want to hide the parent context during execution, create a new // temporary sub-context. ctx.push(node); ctx.frame().stopResolution(privateContext); ctx.execute(inst); } finally { ctx.swapBuffer(origBuf); ctx.pop(); } return new TextNode(buf.toString()); }
@Test public void deserializePrimitiveTest() { assertEquals(Boolean.TRUE, Deserializer.fromJson(TypeNode.fromString("bool"), BooleanNode.TRUE)); assertEquals(Boolean.FALSE, Deserializer.fromJson(TypeNode.fromString("bool"), BooleanNode.FALSE)); assertEquals('a', Deserializer.fromJson(TypeNode.fromString("char"), TextNode.valueOf("a"))); assertEquals(Integer.valueOf(123), Deserializer.fromJson(TypeNode.fromString("int"), IntNode.valueOf(123))); assertEquals(Long.valueOf(123), Deserializer.fromJson(TypeNode.fromString("long"), IntNode.valueOf(123))); assertEquals(Double.valueOf(123.0), Deserializer.fromJson(TypeNode.fromString("double"), DoubleNode.valueOf(123.0))); assertEquals("algohub", Deserializer.fromJson(TypeNode.fromString("string"), TextNode.valueOf("algohub"))); }
@Test public void primitiveToJsonTest() { assertEquals(BooleanNode.TRUE, Serializer.toJson(true, TypeNode.fromString("bool"))); assertEquals(BooleanNode.FALSE, Serializer.toJson(false, TypeNode.fromString("bool"))); assertEquals(TextNode.valueOf("a"), Serializer.toJson('a', TypeNode.fromString("char"))); assertEquals(IntNode.valueOf(123), Serializer.toJson(123, TypeNode.fromString("int"))); assertEquals(LongNode.valueOf(123), Serializer.toJson(123L, TypeNode.fromString("long"))); assertEquals(DoubleNode.valueOf(123.0), Serializer.toJson(123.0, TypeNode.fromString("double"))); assertEquals(TextNode.valueOf("123"), Serializer.toJson("123", TypeNode.fromString("string"))); }
@Override public HyperLogLogPlus deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException { final TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); final TreeNode coreHyperLogLogPlusObject = treeNode.get("hyperLogLogPlus"); if (null != coreHyperLogLogPlusObject) { final TextNode jsonNodes = (TextNode) coreHyperLogLogPlusObject.get(HyperLogLogPlusJsonConstants.HYPER_LOG_LOG_PLUS_SKETCH_BYTES_FIELD); final byte[] nodeAsString = jsonNodes.binaryValue(); final HyperLogLogPlus hyperLogLogPlus = HyperLogLogPlus.Builder.build(nodeAsString); return hyperLogLogPlus; } else { throw new IllegalArgumentException("Receieved null or empty HyperLogLogPlus sketch"); } }
/** * Parse command field from the compose yaml file to list command words. * * @param jsonParser json parser * @param ctxt deserialization context * @throws IOException in case I/O error. For example element to parsing contains invalid yaml * field type defined for this field by yaml document model. * @throws JsonProcessingException */ @Override public List<String> deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException { TreeNode tree = jsonParser.readValueAsTree(); if (tree.isArray()) { return toCommand((ArrayNode) tree, ctxt); } if (tree instanceof TextNode) { TextNode textNode = (TextNode) tree; return asList(textNode.asText().trim().split(SPLIT_COMMAND_REGEX)); } throw ctxt.mappingException( (format("Field '%s' must be simple text or string array.", jsonParser.getCurrentName()))); }
@Test public void unknownAttributesAreIgnoredWhenDesserializing() throws Exception { final EventType eventType = buildDefaultEventType(); final ObjectNode node = (ObjectNode) TestUtils.OBJECT_MAPPER.readTree( TestUtils.OBJECT_MAPPER.writeValueAsString(eventType)); node.set("unknown_attribute", new TextNode("will just be ignored")); final String eventTypeName = eventType.getName(); final String insertSQL = "INSERT INTO zn_data.event_type (et_name, et_event_type_object) " + "VALUES (?, to_json(?::json))"; template.update(insertSQL, eventTypeName, TestUtils.OBJECT_MAPPER.writeValueAsString(node)); final EventType persistedEventType = repository.findByName(eventTypeName); assertThat(persistedEventType, notNullValue()); }
private static JsonNode resolveSecrets(JsonNode node, SecretProvider secrets) { if (node.isObject()) { ObjectNode object = (ObjectNode) node; ObjectNode newObject = object.objectNode(); object.fields().forEachRemaining(entry -> newObject.set( UserSecretTemplate.of(entry.getKey()).format(secrets), resolveSecrets(entry.getValue(), secrets))); return newObject; } else if (node.isArray()) { ArrayNode array = (ArrayNode) node; ArrayNode newArray = array.arrayNode(); array.elements().forEachRemaining(element -> newArray.add(resolveSecrets(element, secrets))); return newArray; } else if (node.isTextual()) { return new TextNode(UserSecretTemplate.of(node.textValue()).format(secrets)); } else { return node; } }
@SuppressWarnings("unchecked") public static <T extends JsonNode> T resolveSecrets(T node, SecretProvider secrets) { if (node.isObject()) { return (T) resolveSecrets((ObjectNode) node, secrets); } else if (node.isArray()) { return (T) resolveSecrets((ArrayNode) node, secrets); } else if (node.isTextual()) { return (T) resolveSecrets((TextNode) node, secrets); } else { return node; } }
Payload upsertInstallationWithToken(Optional<String> id, Credentials credentials, // ObjectNode installation, String token, Context context) { String appId = Json8.checkStringNotNullOrEmpty(installation, APP_ID); PushServices service = PushServices.valueOf(// Json8.checkStringNotNullOrEmpty(installation, PUSH_SERVICE)); if (SpaceContext.isTest()) { installation.set(ENDPOINT, TextNode.valueOf("FAKE_ENDPOINT_FOR_TESTING")); } else { String endpoint = createApplicationEndpoint(credentials.backendId(), appId, service, token); installation.put(ENDPOINT, endpoint); } if (credentials.isReal()) { installation.put(USER_ID, credentials.name()); installation.put(CREDENTIALS_NAME, credentials.name()); installation.put(CREDENTIALS_ID, credentials.id()); } if (id.isPresent()) { DataStore.get().patchObject(credentials.backendId(), TYPE, id.get(), installation, credentials.name()); return JsonPayload.saved(false, credentials.backendId(), "/1", TYPE, id.get()); } else return DataResource.get().post(TYPE, installation.toString(), context); }
@Deprecated public static ValueNode toValueNode(Object value) { if (value == null) return NullNode.instance; if (value instanceof ValueNode) return (ValueNode) value; if (value instanceof Boolean) return BooleanNode.valueOf((boolean) value); else if (value instanceof Integer) return IntNode.valueOf((int) value); else if (value instanceof Long) return LongNode.valueOf((long) value); else if (value instanceof Double) return DoubleNode.valueOf((double) value); else if (value instanceof Float) return FloatNode.valueOf((float) value); return TextNode.valueOf(value.toString()); }
@Test public void convertTextMessageToSnsMessage() { JsonNode textMessage = new TextNode("coucou"); ObjectNode objectMessage = PushResource.toObjectMessage(textMessage); ObjectNode snsMessage = PushResource.toSnsMessage(PushService.BAIDU, objectMessage); assertEquals("coucou", snsMessage.get("default").asText()); snsMessage = PushResource.toSnsMessage(PushService.APNS, objectMessage); assertEquals(Json8.object("aps", Json8.object("alert", "coucou")), // Json8.readObject(snsMessage.get("APNS").asText())); snsMessage = PushResource.toSnsMessage(PushService.APNS_SANDBOX, objectMessage); assertEquals(Json8.object("aps", Json8.object("alert", "coucou")), // Json8.readObject(snsMessage.get("APNS_SANDBOX").asText())); snsMessage = PushResource.toSnsMessage(PushService.GCM, objectMessage); assertEquals(Json8.object("data", Json8.object("message", "coucou")), // Json8.readObject(snsMessage.get("GCM").asText())); }
public static JsonNode validate(String type, JsonNode schema) throws SchemaException { JsonNode rootObjectSchema = checkField(schema, type, true, JsonType.OBJECT).get(); checkIfInvalidField(schema, false, type); String rootType = checkField(rootObjectSchema, "_type", false, JsonType.STRING)// .orElse(TextNode.valueOf("object")).asText(); if (SchemaType.OBJECT.equals(rootType)) { checkCommonDirectives(rootObjectSchema); checkField(rootObjectSchema, "_id", false, JsonType.STRING); Optional7<JsonNode> opt = checkField(rootObjectSchema, "_acl", false, JsonType.OBJECT); if (opt.isPresent()) checkAcl(type, opt.get()); checkObjectProperties(type, rootObjectSchema); } else throw SchemaException.invalidType(type, rootType); return schema; }
public static ValueNode toValueNode(Object value) { if (value == null) return NullNode.instance; if (value instanceof ValueNode) return (ValueNode) value; if (value instanceof Boolean) return BooleanNode.valueOf((boolean) value); else if (value instanceof Integer) return IntNode.valueOf((int) value); else if (value instanceof Long) return LongNode.valueOf((long) value); else if (value instanceof Double) return DoubleNode.valueOf((double) value); else if (value instanceof Float) return FloatNode.valueOf((float) value); return TextNode.valueOf(value.toString()); }
@Override public AnnotationResource deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { AnnotationResource result; ObjectMapper mapper = (ObjectMapper) jp.getCodec(); TreeNode node = mapper.readTree(jp); String format = ((TextNode) node.get("format")).textValue(); String id = null; TextNode idNode = (TextNode) node.get("@id"); if (idNode != null) { id = idNode.textValue(); } String type = ((TextNode) node.get("@type")).textValue(); if (node.get("chars") != null) { result = new AnnotationResourceCharsImpl(type, format); String chars = ((TextNode) node.get("chars")).textValue(); ((AnnotationResourceCharsImpl) result).setChars(chars); } else { result = new AnnotationResourceImpl(type, format); } if (id != null) { result.setId(URI.create(id)); } return result; }
@Override public SeeAlso deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) jp.getCodec(); TreeNode node = mapper.readTree(jp); SeeAlso seeAlso = new SeeAlsoImpl(); if (ObjectNode.class.isAssignableFrom(node.getClass())) { String id = ((TextNode) node.get("@id")).textValue(); TextNode formatNode = ((TextNode) node.get("format")); TextNode profileNode = ((TextNode) node.get("profile")); seeAlso.setId(uriFromString(id)); if (formatNode != null) { seeAlso.setFormat(formatNode.textValue()); } if (profileNode != null) { seeAlso.setProfile(uriFromString(profileNode.textValue())); } } else if (TextNode.class.isAssignableFrom(node.getClass())) { seeAlso.setId(uriFromString(((TextNode) node).textValue())); } else { throw new IllegalArgumentException("SeeAlso must be a string or object!"); } return seeAlso; }
@Override public IiifReference deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) jp.getCodec(); TreeNode node = mapper.readTree(jp); String id; if (ObjectNode.class.isAssignableFrom(node.getClass())) { id = ((TextNode) node.get("@id")).textValue(); String type = ((TextNode) node.get("@type")).textValue(); if (!"sc:AnnotationList".equals(type)) { throw new IllegalArgumentException(String.format("Do not know how to handle reference type '%s'", type)); } } else if (TextNode.class.isAssignableFrom(node.getClass())) { id = ((TextNode) node).textValue(); } else { throw new IllegalArgumentException("Reference must be a string or object!"); } return new AnnotationListReferenceImpl(URI.create(id)); }
private static JobLaunchingData getJobLaunchingData(final JsonNode payload, final JsonNode jobJsonNode) { final String jobName = jobJsonNode.get("name").asText(); final JobParametersBuilder jobParametersBuilder = new JobParametersBuilder(); final JsonNode commercetools = payload.get("commercetools"); commercetools.fields().forEachRemaining(stringJsonNodeEntry -> { jobParametersBuilder.addString("commercetools." + stringJsonNodeEntry.getKey(), stringJsonNodeEntry.getValue().asText()); }); jobJsonNode.fields().forEachRemaining(jobField -> { //TODO prepare for other classes if (jobField.getValue() instanceof TextNode) { jobParametersBuilder.addString(jobField.getKey(), jobField.getValue().asText()); } else if (jobField.getValue() instanceof IntNode || jobField.getValue() instanceof LongNode) { jobParametersBuilder.addLong(jobField.getKey(), jobField.getValue().asLong()); } }); return new JobLaunchingData(jobName, jobParametersBuilder.toJobParameters()); }
/** * Get an Avro schema using {@link AvroUtils#wrapAsNullable(Schema)} by node type. * * @param node Json node. * @return an Avro schema using {@link AvroUtils#wrapAsNullable(Schema)} by node type. */ public Schema getAvroSchema(JsonNode node) { if (node instanceof TextNode) { return AvroUtils.wrapAsNullable(AvroUtils._string()); } else if (node instanceof IntNode) { return AvroUtils.wrapAsNullable(AvroUtils._int()); } else if (node instanceof LongNode) { return AvroUtils.wrapAsNullable(AvroUtils._long()); } else if (node instanceof DoubleNode) { return AvroUtils.wrapAsNullable(AvroUtils._double()); } else if (node instanceof BooleanNode) { return AvroUtils.wrapAsNullable(AvroUtils._boolean()); } else if (node instanceof NullNode) { return AvroUtils.wrapAsNullable(AvroUtils._string()); } else { return Schema.createRecord(getSubRecordRandomName(), null, null, false, getFields(node)); } }