Java Examples for org.codehaus.jackson.JsonNode
The following java examples will help you to understand the usage of org.codehaus.jackson.JsonNode. These source code samples are taken from different open source projects.
Example 1
| Project: indie-master File: ProjectPresenter.java View source code |
public String toJson(List projects) {
StringWriter out = new StringWriter();
try {
JsonGenerator g = factory.createJsonGenerator(out);
JsonNode root = mapper.createObjectNode();
ArrayNode projectArray = ((ObjectNode) root).putArray("projects");
for (Object project : projects) {
projectArray.add(project.toString());
}
mapper.writeValue(g, root);
g.close();
} catch (IOException e) {
throw new RuntimeException("Json parsing failed! : " + e.getMessage());
}
return out.toString();
}Example 2
| Project: javabin-play-public-master File: TwitterApplicationAuthenticator.java View source code |
@Override
public String apply(WS.Response response) throws Throwable {
final JsonNode jsonNode = response.asJson();
if ("bearer".equals(jsonNode.findPath("token_type").getTextValue())) {
return jsonNode.findPath("access_token").getTextValue();
} else {
throw new RuntimeException(String.format("Illegal response from the Twitter API. Data returned: %1$s", response.getBody()));
}
}Example 3
| Project: jenkow-plugin-master File: TaskUrlAddResource.java View source code |
@Put
public AttachmentResponse addUrl(Representation entity) {
if (authenticate() == false)
return null;
String taskId = (String) getRequest().getAttributes().get("taskId");
if (taskId == null || taskId.length() == 0) {
throw new ActivitiException("No taskId provided");
}
try {
String taskParams = entity.getText();
JsonNode taskJSON = new ObjectMapper().readTree(taskParams);
String name = null;
if (taskJSON.path("name") != null && taskJSON.path("name").getTextValue() != null) {
name = taskJSON.path("name").getTextValue();
}
String description = null;
if (taskJSON.path("description") != null && taskJSON.path("description").getTextValue() != null) {
description = taskJSON.path("description").getTextValue();
}
String url = null;
if (taskJSON.path("url") != null && taskJSON.path("url").getTextValue() != null) {
url = taskJSON.path("url").getTextValue();
}
Attachment attachment = ActivitiUtil.getTaskService().createAttachment("url", taskId, null, name, description, url);
return new AttachmentResponse(attachment);
} catch (Exception e) {
throw new ActivitiException("Unable to add new attachment to task " + taskId);
}
}Example 4
| Project: Metrika4j-master File: JacksonJsonObject.java View source code |
public JsonObject[] getObjectArray(String fieldName) {
JsonNode valueNode = srcNode.get(fieldName);
if (valueNode == null) {
return null;
} else {
JsonObject[] result = new JsonObject[valueNode.size()];
Iterator<org.codehaus.jackson.JsonNode> it = valueNode.getElements();
for (int i = 0; i < result.length; i++) {
result[i] = new JacksonJsonObject(it.next());
}
return result;
}
}Example 5
| Project: geckoboard-java-api-master File: HighChartTest.java View source code |
@Test
public void testJson() throws JsonProcessingException, IOException {
HighChart widget = new HighChart("1234");
ChartOptions chartOptions = widget.getChartOptions();
chartOptions.getChart().setWidth(800).setHeight(600).setMarginLeft(70).setMarginTop(80);
// title
chartOptions.getTitle().setText("Browser market shares at a specific website, 2010");
// plotOptions
chartOptions.getPlotOptions().getPie().setAllowPointSelect(true).getDataLabels().setEnabled(true).setColor("#000000").setFormatter("function() {return '<b>'+ this.point.name +'</b>: '+ this.y +' %';}");
Series newSeries = new Series().setName("Browser share").setType("pie");
chartOptions.getSeries().pushElement(newSeries);
newSeries.getData().pushElement(new Point().setName("Firefox").setY(45)).pushElement(new Point().setName("IE").setY(26.8)).pushElement(new Point().setName("Chrome").setY(12.8).setSliced(true).setSelected(true)).pushElement(new Point().setName("Safari").setY(8.5)).pushElement(new Point().setName("Opera").setY(6.2)).pushElement(new Point().setName("Others").setY(0.7));
JsonNode data = JsonTestHelper.getJsonFromWidget(widget);
Assert.assertNotNull(data.get("data"));
JsonNode node = data.get("data");
Assert.assertNull(node.get("widgetKey"));
Assert.assertNotNull(node.get("highchart"));
JsonNode highchart = node.get("highchart");
Assert.assertEquals("Expected pie json", HighChartTest.pieJson, highchart.toString());
}Example 6
| Project: Java-library-master File: TagActionDataDeserializer.java View source code |
@Override
public TagActionData deserialize(JsonParser parser, DeserializationContext deserializationContext) throws IOException {
JsonNode jsonNode = parser.readValueAsTree();
if (!jsonNode.isArray() && !jsonNode.isTextual()) {
throw new APIParsingException("Tag must be a string or an array.");
}
if (jsonNode.isTextual()) {
return TagActionData.single(jsonNode.getTextValue());
}
Iterator<JsonNode> items = jsonNode.getElements();
List<String> tags = Lists.newArrayList();
while (items.hasNext()) {
JsonNode item = items.next();
if (item.isNull() || !item.isTextual()) {
throw new APIParsingException("Null or non-string tags are not allowed.");
}
tags.add(item.getTextValue());
}
if (tags.size() == 0) {
throw new APIParsingException("Tag list must contain at least one tag.");
}
return TagActionData.set(Sets.newHashSet(tags));
}Example 7
| Project: karyon-master File: JsonReadingResource.java View source code |
@SuppressWarnings("unused")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response processJson(String payload) {
try {
System.out.println("processing payload size: '" + payload.length() + "'");
JsonNode tree = mapper.readTree(payload);
return Response.ok().build();
} catch (Exception e) {
System.err.println("ERROR:" + e.getMessage());
return Response.serverError().build();
}
}Example 8
| Project: Koya-master File: PreferencesDeserializer.java View source code |
private void recursiveDeserialize(JsonNode n, String key, String keySep, Preferences pref) { if (n.isContainerNode()) { Iterator<Entry<String, JsonNode>> it = n.getFields(); while (it.hasNext()) { Entry<String, JsonNode> e = it.next(); recursiveDeserialize(e.getValue(), key + keySep + e.getKey(), ".", pref); } } else { // if (!key.equals(ItlAlfrescoServiceWrapperDeserializer.ATTRIBUTE_CONTENT_TYPE)) { if (n.isBoolean()) { pref.put(key, n.getBooleanValue()); } else if (n.isTextual()) { pref.put(key, n.getTextValue()); } else { logger.error("unhandled type for deserialization : " + key); } // } } }
Example 9
| Project: libdynticker-master File: OneBTCXEExchange.java View source code |
@Override
protected String getTicker(Pair pair) throws IOException {
// https://1btcxe.com/api/stats?currency=MXN
JsonNode node = readJsonFromUrl("https://1btcxe.com/api/stats?currency=" + pair.getExchange());
if (node.has("errors"))
throw new IOException(node.get("errors").get(0).get("message").asText());
else
return parseTicker(node, pair);
}Example 10
| Project: activityinfo-master File: SitesResourcesTest.java View source code |
@Test
public void indicatorsArePresent() throws IOException {
QueryParameters parameters = new QueryParameters();
parameters.databaseIds.add(2);
String json = query(parameters);
System.out.println(json);
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory();
JsonParser jp = factory.createJsonParser(json);
ArrayNode array = (ArrayNode) mapper.readTree(jp);
assertThat(array.size(), equalTo(3));
JsonNode site6 = getSiteById(array, 6);
assertThat(site6.path("id").asInt(), equalTo(6));
assertThat(site6.path("activity").asInt(), equalTo(4));
double indicatorValue = site6.path("indicatorValues").path("6").asDouble();
assertThat(indicatorValue, equalTo(70d));
}Example 11
| Project: Blogs-master File: TwitterClient.java View source code |
private void appendTweets() throws IOException {
InputStream input = null;
JsonParser parser = null;
try {
connection.connect();
input = connection.getInputStream();
parser = new ObjectMapper().getJsonFactory().createJsonParser(input);
Iterator<JsonNode> nodes = parser.readValueAsTree().getElements();
while (nodes.hasNext()) {
JsonNode node = nodes.next();
appendable.append("> ").append(node.path("text").getTextValue()).append('\n');
}
} catch (FileNotFoundException e) {
throw new UserNotFoundException(e);
} finally {
connection.disconnect();
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(parser);
}
}Example 12
| Project: calabash-android-java-master File: TreeNodeBuilder.java View source code |
public TreeNode buildFrom(JsonNode jsonNode, String query) {
final HashMap<Object, Object> map = new HashMap<Object, Object>();
map.put("class", getProperty(jsonNode, "type"));
map.put("id", getProperty(jsonNode, "id"));
map.put("text", getProperty(jsonNode, "value"));
map.put("enabled", getBooleanProperty(jsonNode, "enabled"));
createRect(jsonNode, map);
return new TreeNode(new UIElement(map, query, calabashWrapper));
}Example 13
| Project: cloudbees-api-client-master File: CloudResourceProvider.java View source code |
/**
* Lists up all the cloud resources.
*/
public Iterator<CloudResource> iterator() {
try {
JsonNode res = getOwner().retrieve().get("resources");
if (res == null || !res.isArray())
throw new IllegalStateException("Expected a JSON array but " + getOwner() + " gave us " + res);
ReferencedResource[] dto = CloudResource.MAPPER.readValue(res, ReferencedResource[].class);
List<CloudResource> r = new ArrayList<CloudResource>(dto.length);
for (ReferencedResource rr : dto) {
r.add(rr.toCloudResource(getOwner()));
}
return r.iterator();
} catch (IOException e) {
throw new Error(e);
}
}Example 14
| Project: confit-master File: Serializers.java View source code |
@Override
public DurationTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
int hours = node.get("hours").getIntValue();
int minutes = node.get("minutes").getIntValue();
int seconds = node.get("seconds").getIntValue();
boolean negative = node.get("negative").getBooleanValue();
return new DurationTime(negative, hours, minutes, seconds);
}Example 15
| Project: cs-244-project-master File: PBFTKeyGenerator.java View source code |
public static void main(String args[]) {
File configFile = new File(args[0]);
try {
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(configFile));
JsonFactory factory = new JsonFactory();
JsonParser jsonParser = factory.createJsonParser(reader);
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(jsonParser);
Iterator<JsonNode> serverIterator = root.get("servers").getElements();
while (serverIterator.hasNext()) {
JsonNode server = serverIterator.next();
KeyPair keyPair = CryptoUtil.generateNewKeyPair();
File publicKeyFile = new File(server.get("public_key").getTextValue());
File privateKeyFile = new File(server.get("private_key").getTextValue());
FileOutputStream publicKeyOutputStream = new FileOutputStream(publicKeyFile);
FileOutputStream privateKeyOutputStream = new FileOutputStream(privateKeyFile);
publicKeyOutputStream.write(keyPair.getPublic().getEncoded());
privateKeyOutputStream.write(keyPair.getPrivate().getEncoded());
publicKeyOutputStream.close();
privateKeyOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}Example 16
| Project: Cubert-master File: TestUDAF.java View source code |
@Override
public void setup(Block block, BlockSchema outputTupleSchema, JsonNode json) throws IOException {
BlockSchema inputSchema = block.getProperties().getSchema();
String inputColumnName = JsonUtils.getText(json, "input");
inputColumnIndex = inputSchema.getIndex(inputColumnName);
inputDataType = inputSchema.getType(inputColumnIndex);
// FieldSchema fs =
// outputSchema(SchemaUtils.convertFromBlockSchema(inputSchema), json);
BlockSchema aggOutputSchema = outputSchema(inputSchema, json);
String outputColumnName = aggOutputSchema.getName(0);
outputColumnIndex = outputTupleSchema.getIndex(outputColumnName);
outputDataType = outputTupleSchema.getType(outputColumnIndex);
resetState();
}Example 17
| Project: gobblin-master File: AvroToJsonRecordWithMetadataConverter.java View source code |
@Override public Iterable<RecordWithMetadata<JsonNode>> convertRecord(String outputSchema, GenericRecord inputRecord, WorkUnitState workUnit) throws DataConversionException { try { Iterable<String> innerRecordIterable = innerConverter.convertRecord(outputSchema, inputRecord, workUnit); String record = innerRecordIterable.iterator().next(); JsonNode jsonRoot = objectMapper.readValue(record, JsonNode.class); return Collections.singleton(new RecordWithMetadata<JsonNode>(jsonRoot, defaultMetadata)); } catch (IOException e) { throw new DataConversionException("Error converting to JSON", e); } }
Example 18
| Project: hideyoshi-master File: EclipsePluginDeserializer.java View source code |
@Override
public EclipsePlugin deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
String literal = node.asText();
List<String> split = SLASH_SPLITTER.splitToList(literal);
if (split.size() == 2) {
return EclipsePlugin.of(converter.apply(split.get(0)), split.get(1));
} else {
return EclipsePlugin.of(converter.apply(literal));
}
}Example 19
| Project: jconfig-master File: LsgAdapter.java View source code |
/**
* Load lsg config Json and return a Json node that adheres to the standard
* autoConf Json syntax
*
* @return autoConf JsonNode. null if "lsgclient" section missing in
* autoConf.
* @throws ConfigSourceException
*/
@Override
public JsonNode getModuleNode(final String appName, final String moduleName) throws ConfigException {
// make sure we have an autoConf file with an "lsgclient" section
if (!autoconf.hasApplication("lsgclient")) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
ArrayNode lsgSets = mapper.createArrayNode();
JsonNode lsgNode = autoconf.getApplication("lsgclient");
Iterator<String> farms = lsgNode.getFieldNames();
while (farms.hasNext()) {
String farmName = farms.next();
JsonNode oldFarmNode = lsgNode.get(farmName);
ArrayNode newKeyNode = mapper.createArrayNode();
ObjectNode newKeyListNode = mapper.createObjectNode();
ObjectNode newFarmNode = mapper.createObjectNode();
//{ "key": [ "323" ],
newKeyNode.add(farmName);
newFarmNode.put(ConfigAdapterJson.CONST.KEY.toString(), newKeyNode);
//"keyList": { "FilerGateServerName": "fg323.mail.vip.mud.com", "FilerGateAppId": "mail.acl.yca.fg-beta" }
Iterator<String> fields = oldFarmNode.getFieldNames();
while (fields.hasNext()) {
String fieldName = fields.next();
JsonNode fieldValue = oldFarmNode.get(fieldName);
//{ "FilerGateServerName": "fg323.mail.vip.mud.com", "FilerGateAppId": "mail.acl.yca.fg-beta" }
newKeyListNode.put(fieldName, fieldValue);
}
newFarmNode.put(ConfigAdapterJson.CONST.KEY_LIST.toString(), newKeyListNode);
lsgSets.add(newFarmNode);
}
// {"Sets": [
ObjectNode lsgRoot = mapper.createObjectNode();
lsgRoot.put(ConfigAdapterJson.CONST.SETS.toString(), lsgSets);
lsgRoot.put(ConfigAdapterJson.CONST.SETS_TYPE.toString(), "FARM");
return lsgRoot;
}Example 20
| Project: jira-rest-client-master File: CustomFieldDeSerializer.java View source code |
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
logger.info("Deserialize...");
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
for (int i = 0; i < node.size(); i++) {
JsonNode child = node.get(i);
if (child == null) {
logger.info(i + "th Child node is null");
continue;
}
//String
if (child.isTextual()) {
Iterator<String> it = child.getFieldNames();
while (it.hasNext()) {
String field = it.next();
logger.info("in while loop " + field);
if (field.startsWith("customfield")) {
}
}
}
}
return null;
}Example 21
| Project: jumbodb-master File: GenericJsonStringSortMapper.java View source code |
private String getSortKey(JsonNode jsonNode) {
List<String> keys = new LinkedList<String>();
for (String sort : sortFields) {
String valueFor = getValueFor(sort, jsonNode);
if (valueFor != null) {
keys.add(valueFor);
}
}
if (keys.size() > 0) {
return StringUtils.join(keys, "-");
}
return "default";
}Example 22
| Project: LeanEngine-Server-master File: ScriptRest.java View source code |
private JsonNode toJSON(NativeObject object) {
if (object == null)
return null;
ObjectNode result = JsonUtils.getObjectMapper().createObjectNode();
for (Map.Entry<Object, Object> entry : object.entrySet()) {
if (entry.getValue().getClass().equals(NativeObject.class)) {
result.put((String) entry.getKey(), toJSON((NativeObject) entry.getValue()));
} else if (entry.getValue().getClass().equals(NativeArray.class)) {
result.put((String) entry.getKey(), toJSON((NativeArray) entry.getValue()));
} else {
result.putPOJO((String) entry.getKey(), entry.getValue());
}
}
return result;
}Example 23
| Project: mesos-hbase-master File: HdfsConfFileUrlJsonFinder.java View source code |
public String findUrl(URL jsonURL) throws IOException {
JsonNode rootNode = mapper.readTree(jsonURL);
Iterator<JsonNode> frameworkIterator = rootNode.path("frameworks").iterator();
for (Iterator<JsonNode> iterator = frameworkIterator; iterator.hasNext(); ) {
JsonNode framework = iterator.next();
JsonNode nameNode = framework.path("name");
if (nameNode.getTextValue().equals("hdfs")) {
JsonNode uris = framework.findValue("uris");
Iterator<JsonNode> urisIterator = uris.iterator();
for (Iterator<JsonNode> iterator2 = urisIterator; iterator.hasNext(); ) {
String value = iterator2.next().findValue("value").getTextValue();
if (value.contains(HBaseConstants.HDFS_CONFIG_FILE_NAME))
return value;
}
;
}
}
return null;
}Example 24
| Project: nuxeo-mule-connector-master File: TestTypeFetcher.java View source code |
@Test
public void checkTypeFetcher() throws Exception {
TypeDefinitionFecther fetcher = new TypeDefinitionFecther(null);
Assert.assertTrue(fetcher.getDocTypesNames().contains("File"));
Assert.assertTrue(fetcher.getDocTypesNames().contains("DocumentRoute"));
Assert.assertTrue(fetcher.getDocTypesNames().contains("Workspace"));
List<String> schemas = fetcher.getSchemasForDocType("File");
Assert.assertTrue(schemas.contains("dublincore"));
Assert.assertTrue(schemas.contains("common"));
Assert.assertTrue(schemas.contains("file"));
JsonNode dcSchema = fetcher.getSchema("dublincore");
Assert.assertNotNull(dcSchema);
}Example 25
| Project: org.handwerkszeug.riak-master File: MapReduceQueryContextTest.java View source code |
protected void assertJson(String expectedJsonFile) throws JsonProcessingException, IOException {
ChannelBuffer cb = ChannelBuffers.dynamicBuffer();
this.target.prepare(new ChannelBufferOutputStream(cb));
ObjectMapper om = new ObjectMapper();
JsonNode act = om.readTree(new ChannelBufferInputStream(cb));
JsonNode exp = read(expectedJsonFile);
assertEquals(exp, act);
}Example 26
| Project: pancake-smarts-master File: JSONIterator.java View source code |
public Instance next() {
JsonNode currentNode = jsonIterator.next();
String name = currentNode.get("name").getTextValue();
String text = currentNode.get("text").getTextValue();
String group = currentNode.get("group").getTextValue();
Instance carrier = new Instance(text, group, name, null);
return carrier;
}Example 27
| Project: parkandrideAPI-master File: TranslationService.java View source code |
public String translate(Enum<?> value) {
if (value == null) {
return null;
}
String translationGroup = Introspector.decapitalize(value.getClass().getSimpleName());
JsonNode node = translations.path(translationGroup).path(value.name());
if (node.isMissingNode()) {
node = translations.findValue(value.name());
}
if (node != null) {
node = node.get("label");
}
return node != null ? node.asText() : value.name();
}Example 28
| Project: pinot-master File: TenantTest.java View source code |
@Test
public void testDeserializeFromJson() throws JSONException, IOException {
JSONObject json = new JSONObject();
json.put("tenantRole", "SERVER");
json.put("tenantName", "newTenant");
json.put("numberOfInstances", 10);
json.put("offlineInstances", 5);
json.put("realtimeInstances", 5);
json.put("keyIDontKnow", "blahblahblah");
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json.toString());
Tenant tenant = mapper.readValue(jsonNode, Tenant.class);
Assert.assertEquals(5, tenant.getOfflineInstances());
Assert.assertEquals(10, tenant.getNumberOfInstances());
Assert.assertEquals("newTenant", tenant.getTenantName());
Assert.assertEquals(TenantRole.SERVER, tenant.getTenantRole());
}Example 29
| Project: prototype-20150626-master File: OpenFdaUrlTransportServiceTest.java View source code |
@Test
public void testGetData10Records() {
OpenFdaUrlTransportService transport = new OpenFdaUrlTransportService();
JsonNode jsonNode = transport.getData("https://api.fda.gov/drug/enforcement.json?search=report_date:[20040101+TO+20151231]", 10, 0);
assertNotNull(jsonNode);
ArrayNode results = (ArrayNode) jsonNode.get("results");
assertNotNull(results);
assertTrue(results.size() == 10);
}Example 30
| Project: spatial-framework-for-hadoop-master File: GeoJsonSerDe.java View source code |
@Override
protected OGCGeometry parseGeom(JsonParser parser) {
try {
JsonNode node = mapper.readTree(parser);
return OGCGeometry.fromGeoJson(node.toString());
} catch (JsonProcessingException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return // ?
null;
}Example 31
| Project: spring-camp-spring-security-session-master File: FacebookUserDeserializer.java View source code |
@Override
public FacebookUser deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
FacebookUser user = new FacebookUser();
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
user.setId(getNodeString(node.get("id")));
user.setName(getNodeString(node.get("username")));
user.setBirthday(getNodeString(node.get("birthday")));
user.setEmail(getNodeString(node.get("email")));
user.setGender(getNodeString(node.get("gender")));
user.setLink(getNodeString(node.get("link")));
user.setLocale(getNodeString(node.get("locale")));
return user;
}Example 32
| Project: spring-security-javaconfig-master File: FacebookController.java View source code |
@RequestMapping("/facebook/info")
public String photos(Model model) throws Exception {
ObjectNode result = facebookRestTemplate.getForObject("https://graph.facebook.com/me/friends", ObjectNode.class);
ArrayNode data = (ArrayNode) result.get("data");
ArrayList<String> friends = new ArrayList<String>();
for (JsonNode dataNode : data) {
friends.add(dataNode.get("name").getTextValue());
}
model.addAttribute("friends", friends);
return "facebook";
}Example 33
| Project: spring-security-oauth-javaconfig-master File: FacebookController.java View source code |
@RequestMapping("/facebook/info")
public String photos(Model model) throws Exception {
ObjectNode result = facebookRestTemplate.getForObject("https://graph.facebook.com/me/friends", ObjectNode.class);
ArrayNode data = (ArrayNode) result.get("data");
ArrayList<String> friends = new ArrayList<String>();
for (JsonNode dataNode : data) {
friends.add(dataNode.get("name").getTextValue());
}
model.addAttribute("friends", friends);
return "facebook";
}Example 34
| Project: stickypunch-master File: WebsiteDeserializer.java View source code |
@Override
public Website deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectCodec oc = jp.getCodec();
JsonNode nodes = oc.readTree(jp);
String websitePushID = nodes.get("websitePushID").getTextValue();
String websiteName = nodes.get("websiteName").getTextValue();
List<String> allowedDomains = new ArrayList<String>();
for (JsonNode node : nodes.get("allowedDomains")) {
allowedDomains.add(node.getTextValue());
}
String urlFormatString = nodes.get("urlFormatString").getTextValue();
String authenticationToken = nodes.get("authenticationToken").getTextValue();
String webServiceUrl = nodes.get("webServiceURL").getTextValue();
return new WebsiteBuilder().setWebsiteName(websiteName).setWebsitePushId(websitePushID).setAllowedDomains(allowedDomains).setUrlFormatString(urlFormatString).setAuthenticationToken(authenticationToken).setWebServiceUrl(webServiceUrl).build();
}Example 35
| Project: weiboclient4j-master File: Tag.java View source code |
public static Tag parseTag(JsonNode tagNode) { Tag tag = new Tag(); Iterator<String> fieldNames = tagNode.getFieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); JsonNode fieldValue = tagNode.get(fieldName); if ("weight".equals(fieldName)) { tag.setWeight(fieldValue.asInt()); } else { tag.setId(Long.parseLong(fieldName)); tag.setTag(fieldValue.asText()); } } return tag; }
Example 36
| Project: YiDB-master File: JsonBuilder.java View source code |
@SuppressWarnings("unchecked")
protected JsonNode buildJsonNode(Object object) {
if (object instanceof List) {
List<AbstractCMSEntity> lists = (List<AbstractCMSEntity>) object;
ArrayNode an = JsonNodeFactory.instance.arrayNode();
for (AbstractCMSEntity entity : lists) {
CMSEntityMapper mapper = new CMSEntityMapper(null, config, JsonCMSEntity.class, ProcessModeEnum.JSON, entity.getClass(), true);
entity.traverse(mapper);
JsonCMSEntity jsonEntity = (JsonCMSEntity) mapper.getTargetEntity();
an.add(jsonEntity.getNode());
}
return an;
} else {
AbstractCMSEntity entity = (AbstractCMSEntity) object;
CMSEntityMapper mapper = new CMSEntityMapper(null, config, JsonCMSEntity.class, ProcessModeEnum.JSON, entity.getClass(), true);
entity.traverse(mapper);
JsonCMSEntity jsonEntity = (JsonCMSEntity) mapper.getTargetEntity();
return jsonEntity.getNode();
}
}Example 37
| Project: action-core-0.1.x-master File: RowFactory.java View source code |
/**
* Return the right row associated with some data.
* <p/>
* The decoding from Hadoop was done in the RowSerializers. This utility class simply maps the right Row representation
* given the decoded datatype.
*
* @param rowSchema schema associated with the row
* @param data decoded Data
* @param <T> decoded column types
* @param <Serializable> serialization
* @return a row instance with associated schema and data
* @see com.ning.metrics.action.hdfs.data.parser.RowSerializer
*/
public static <T extends Comparable, Serializable> Row getRow(RowSchema rowSchema, List<T> data) {
if (data.get(0) instanceof DataItem) {
return new RowThrift(rowSchema, (List<DataItem>) data);
} else if (data.get(0) instanceof JsonNode) {
return new RowSmile(rowSchema, (List<JsonNodeComparable>) data);
} else {
return new RowText(rowSchema, (List<String>) data);
}
}Example 38
| Project: Activiti-KickStart-master File: UsersResource.java View source code |
@Get public JsonNode retrieveUser() { // We're simply proxying the Alfresco rest API, so this code is quite unfancy ... AlfrescoKickstartServiceImpl kickstartService = (AlfrescoKickstartServiceImpl) getKickstartService(); HttpState state = new HttpState(); state.setCredentials(new AuthScope(null, AuthScope.ANY_PORT), new UsernamePasswordCredentials(kickstartService.getCmisUser(), kickstartService.getCmisPassword())); String url = "http://localhost:8080/alfresco/service/api/people"; String filter = (String) getRequest().getAttributes().get("filter"); if (filter != null) { url = url + "?filter=" + filter; } GetMethod getMethod = new GetMethod(url); try { HttpClient httpClient = new HttpClient(); httpClient.executeMethod(null, getMethod, state); String responseJson = getMethod.getResponseBodyAsString(); ObjectMapper mapper = new ObjectMapper(); JsonNode json = mapper.readTree(responseJson); return json; } catch (Throwable t) { System.err.println("Error: " + t.getMessage()); t.printStackTrace(); return null; } finally { getMethod.releaseConnection(); } }
Example 39
| Project: ambari-master File: AbstractStateFileZkCommand.java View source code |
public AmbariSolrState getStateFromJson(AmbariSolrCloudClient client, String fileName) throws Exception {
byte[] data = client.getSolrZkClient().getData(fileName, null, null, true);
String input = new String(data);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(input.getBytes(), JsonNode.class);
return AmbariSolrState.valueOf(rootNode.get(STATE_FIELD).asText());
}Example 40
| Project: Anicetus-master File: InMemoryAdapter.java View source code |
List<JsonNode> getAllObjects() throws Exception { System.out.println(m_delegate.toCharArray()); JsonFactory fact = new JsonFactory(); JsonParser parser = fact.createJsonParser(new CharArrayReader(m_delegate.toCharArray())); ObjectMapper mapper = new ObjectMapper(); List<JsonNode> result = new ArrayList<JsonNode>(); while (true) { try { JsonNode node = mapper.readTree(parser); if (node == null) { break; } result.add(node); } catch (Exception e) { break; } } return result; }
Example 41
| Project: atlas-lb-master File: PropertyListDeserializer.java View source code |
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
Object out = null;
List childList;
String nodeStr = "";
String rootName = ClassReflectionTools.getXmlRootElementName(this.forClass);
String errMsg = "";
String excMsg = "";
JsonNode node = jp.readValueAsTree();
JsonNode childNode = null;
Object nodeObj = null;
if (node.has(rootName)) {
// If a root name is found on input strip it off
//and continue decoding
childNode = node.get(rootName);
JsonParser childParser = childNode.traverse();
} else {
// If its not wrapped don't worry about it cause
childNode = node;
// its probably a nested child. For example Node fro Nodes
}
nodeStr = childNode.toString();
try {
out = ClassReflectionTools.newInstance(forClass);
childList = (List) ClassReflectionTools.invokeGetter(out, getterName);
for (JsonNode itemNode : childNode) {
String itemJson = itemNode.toString();
Object item = cleanObjectMapper.readValue(itemJson, itemClass);
childList.add(item);
}
} catch (Exception ex) {
excMsg = getExtendedStackTrace(ex);
errMsg = String.format("Error converting \"%s\" into class %s\n", nodeStr, forClass.toString());
LOG.error(errMsg);
throw JsonMappingException.from(jp, errMsg);
}
return out;
}Example 42
| Project: baiji4j-master File: PropertyMap.java View source code |
public void parse(JsonNode node) { if (!(node instanceof ObjectNode)) { return; } ObjectNode objNode = (ObjectNode) node; Iterator<Map.Entry<String, JsonNode>> fields = objNode.getFields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); if (reserved.contains(entry.getKey())) { continue; } String key = entry.getKey(); JsonNode value = entry.getValue(); if (!containsKey(key)) { put(key, value.isTextual() ? value.getTextValue() : value.asText()); } } }
Example 43
| Project: cloudify-widget-master File: WidgetCustomLoginController.java View source code |
public static Result customLogin(String widgetKey) {
if (StringUtils.isEmptyOrSpaces(widgetKey)) {
return internalServerError("missing widgetId");
}
Widget widget = Widget.getWidget(widgetKey);
logger.info("logged in custom");
JsonNode jsonNode = request().body().asJson();
logger.info("jsonNode is : " + jsonNode);
try {
handleLogin(widget, new CustomLoginDetails(jsonNode));
} catch (CustomLoginException e) {
return internalServerError(e.getMessage());
} catch (Exception e) {
logger.info("custom login failed", e);
return internalServerError("invalid details");
}
return ok();
}Example 44
| Project: CoreLib-master File: CustomNodeDeserializer.java View source code |
@Override
public CustomNode deserialize(JsonParser jp, DeserializationContext arg1) throws IOException {
CustomNode node = new CustomNode();
JsonNode json = jp.getCodec().readTree(jp);
Iterator<String> iterator = json.getFieldNames();
Map<String, Object> properties = new HashMap<>();
while (iterator.hasNext()) {
String iteratorKey = iterator.next();
properties.put(iteratorKey, json.get(iteratorKey));
}
node.setProperties(properties);
return node;
}Example 45
| Project: cta-otp-master File: JCDecauxBikeRentalDataSource.java View source code |
/**
* JSON JCDecaux API v1 format:
*
* <pre>
* [ {
* "number" : 94,
* "name" : "00094-PETIT PORT",
* "address" : "PETIT PORT - BD DU PETIT PORT",
* "position" : {
* "lat" : 47.243263914975486,
* "lng" : -1.556344610167984 },
* "banking" : true,
* "bonus" : false,
* "status" : "OPEN",
* "bike_stands" : 20,
* "available_bike_stands" : 1,
* "available_bikes" : 19,
* "last_update" : 1368611914000
* },
* ...
* ]
* </pre>
*/
public BikeRentalStation makeStation(JsonNode node) {
if (!node.path("status").getTextValue().equals("OPEN")) {
return null;
}
BikeRentalStation station = new BikeRentalStation();
station.id = String.format("%d", node.path("number").asInt());
station.x = node.path("position").path("lng").asDouble();
station.y = node.path("position").path("lat").asDouble();
station.name = node.path("name").getTextValue();
station.bikesAvailable = node.path("available_bikes").asInt();
station.spacesAvailable = node.path("available_bike_stands").asInt();
return station;
}Example 46
| Project: dcache-master File: JsonHttpClient.java View source code |
public JsonNode doGet(String url, Header header) throws IOException {
HttpGet httpGet = new HttpGet(url);
if (header != null) {
httpGet.addHeader(header);
}
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
return responseAsJson(entity);
} else {
return null;
}
}Example 47
| Project: dog-master File: JsonUpdate.java View source code |
public static ZWaveModelTree updateModel(ObjectMapper mapper, JsonNode zWaveTree, String json) throws JsonProcessingException, IOException { JsonNode node = mapper.readTree(json); Iterator<Entry<String, JsonNode>> it = node.getFields(); while (it.hasNext()) { Entry<String, JsonNode> n = it.next(); String sNodeKey = n.getKey(); int nIndex = sNodeKey.indexOf("."); int nStart = 0; JsonNode x = zWaveTree; while (nIndex > 0) { x = x.path(sNodeKey.substring(nStart, nIndex)); nStart = nIndex + 1; nIndex = sNodeKey.indexOf(".", nStart); } String sKey = sNodeKey.substring(nStart); ((ObjectNode) x).put(sKey, n.getValue()); } return mapper.readValue(zWaveTree, ZWaveModelTree.class); }
Example 48
| Project: emf4sw-master File: RDFJSONResourceImpl.java View source code |
@Override
protected void doSave(OutputStream outputStream, Map<?, ?> options) throws IOException {
if (!getContents().isEmpty()) {
if (getContents().get(0) instanceof RDFGraph) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
JsonNode root = RDFGraph2Json.createJsonTree((DocumentGraph) getContents().get(0));
mapper.writeValue(outputStream, root);
}
}
}Example 49
| Project: FiWare-Template-Handler-master File: TaskUrlAddResource.java View source code |
@Put
public AttachmentResponse addUrl(Representation entity) {
if (authenticate() == false)
return null;
String taskId = (String) getRequest().getAttributes().get("taskId");
if (taskId == null || taskId.length() == 0) {
throw new ActivitiException("No taskId provided");
}
try {
String taskParams = entity.getText();
JsonNode taskJSON = new ObjectMapper().readTree(taskParams);
String name = null;
if (taskJSON.path("name") != null && taskJSON.path("name").getTextValue() != null) {
name = taskJSON.path("name").getTextValue();
}
String description = null;
if (taskJSON.path("description") != null && taskJSON.path("description").getTextValue() != null) {
description = taskJSON.path("description").getTextValue();
}
String url = null;
if (taskJSON.path("url") != null && taskJSON.path("url").getTextValue() != null) {
url = taskJSON.path("url").getTextValue();
}
Attachment attachment = ActivitiUtil.getTaskService().createAttachment("url", taskId, null, name, description, url);
return new AttachmentResponse(attachment);
} catch (Exception e) {
throw new ActivitiException("Unable to add new attachment to task " + taskId);
}
}Example 50
| Project: flexmls_api4j-master File: Response.java View source code |
/**
* Results list. Returns instances of the service's model type
* @param <T> Model type to create
* @param resultClass class object for the model to create
* @return One or more instances of the model based on the JSON response results
* @throws FlexmlsApiClientException if unable to parse the response JSON, or unable to map it
* to the input Model class.
*/
public <T> List<T> getResults(Class<T> resultClass) throws FlexmlsApiClientException {
try {
JsonNode results = rootNode.get("Results");
List<T> r = new ArrayList<T>();
if (!results.isArray()) {
throw new JsonMappingException("The JSON returned is missing a results array, which is expected on all api responses.");
}
for (int i = 0; i < results.size(); i++) {
JsonNode n = results.get(i);
T result = mapper.readValue(n, resultClass);
r.add(result);
}
return r;
} catch (IOException e) {
throw new FlexmlsApiClientException("Failure parsing JSON resonse. The server response may be invalid", e);
}
}Example 51
| Project: flume-lib-master File: TwitterEventChannelListener.java View source code |
@Override
public void onMessage(String rawString) {
try {
// Only push new status events
if (rawString.contains("created_at")) {
// Decode the line to JSON to get the timestamp
JsonNode node = mapper.readTree(rawString);
// Get the timestamp and add the header
headers.put("timestamp", String.valueOf(sf.parse(node.get("created_at").getTextValue()).getTime()));
// Push the event through the channel
channel.processEvent(EventBuilder.withBody(rawString.getBytes(), headers));
}
} catch (ParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}Example 52
| Project: grendel-master File: LinkListRepresentationTest.java View source code |
@Test
public void itSerializesIntoJSON() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final String json = mapper.writeValueAsString(rep);
final ObjectNode entity = mapper.readValue(json, ObjectNode.class);
final List<JsonNode> links = ImmutableList.copyOf(entity.get("links").getElements());
assertThat(links).hasSize(1);
final JsonNode link = links.get(0);
assertThat(link.get("uri").getTextValue()).isEqualTo("http://example.com/users/mrpeepers/documents/document1.txt/links/flaflaf");
final JsonNode user = link.get("user");
assertThat(user.get("id").getTextValue()).isEqualTo("flaflaf");
assertThat(user.get("uri").getTextValue()).isEqualTo("http://example.com/users/flaflaf");
}Example 53
| Project: inproctester-master File: InProcessResteasyTest.java View source code |
@Test
public void shouldAddResource() throws Exception {
ClientRequest request = new ClientRequest("http://localhost/", new InProcessClientExecutor(httpAppTester));
JsonNode testResource = objectMapper.readValue("{\"name\":\"test\"}", JsonNode.class);
ClientResponse<JsonNode> createResponse = request.body(MediaType.APPLICATION_JSON, testResource).post(JsonNode.class);
Assert.assertEquals(201, createResponse.getStatus());
JsonNode entity = createResponse.getEntity();
Assert.assertEquals(testResource, entity);
// JsonNode testResourceFromServer = webResource.uri(createResponse.getLocation()).accept(MediaType.APPLICATION_JSON).get(JsonNode.class);
// Assert.assertEquals(testResource, testResourceFromServer);
}Example 54
| Project: kaa-master File: Utils.java View source code |
/** * Change encoding of uuids from <b>latin1 (ISO-8859-1)</b> to <b>base64</b>. * * @param json the json that should be processed * @return the json with changed uuids * @throws IOException the io exception */ public static JsonNode encodeUuids(JsonNode json) throws IOException { if (json.has(UUID_FIELD)) { JsonNode jsonNode = json.get(UUID_FIELD); if (jsonNode.has(UUID_VALUE)) { String value = jsonNode.get(UUID_VALUE).asText(); String encodedValue = Base64.getEncoder().encodeToString(value.getBytes("ISO-8859-1")); ((ObjectNode) jsonNode).put(UUID_VALUE, encodedValue); } } for (JsonNode node : json) { if (node.isContainerNode()) { encodeUuids(node); } } return json; }
Example 55
| Project: keemto-master File: RandomAccountControllerTest.java View source code |
@Test
public void testGetRandomAccountForAUser() throws Exception {
when(userRepository.getAllUsers()).thenReturn(Lists.newArrayList(user));
when(accountFactory.getAccounts(user)).thenReturn(Lists.newArrayList(account));
controller.setMaxRandomAccount(1);
handlerAdapter.handle(request, response, controller);
assertThat(response.getStatus(), equalTo(200));
JsonNode jsonNode = toJsonNode(response.getContentAsString());
assertThat(jsonNode.size(), equalTo(1));
JsonNode connx = jsonNode.get(0);
JsonNode keyNode = connx.get("key");
assertThat(keyNode.get("providerId").getValueAsText(), equalTo("provider"));
}Example 56
| Project: lilyproject-master File: RecordTypeFilterJson.java View source code |
@Override
public RecordTypeFilter fromJson(JsonNode node, Namespaces namespaces, LRepository repository, RecordFilterJsonConverter<RecordFilter> converter) throws JsonFormatException, RepositoryException, InterruptedException {
RecordTypeFilter filter = new RecordTypeFilter();
String recordType = JsonUtil.getString(node, "recordType", null);
if (recordType != null) {
filter.setRecordType(QNameConverter.fromJson(recordType, namespaces));
}
Long version = JsonUtil.getLong(node, "version", null);
if (version != null) {
filter.setVersion(version);
}
String operator = JsonUtil.getString(node, "operator", null);
if (operator != null) {
filter.setOperator(RecordTypeFilter.Operator.valueOf(operator.toUpperCase()));
}
return filter;
}Example 57
| Project: magnificent-mileage-master File: JCDecauxBikeRentalDataSource.java View source code |
/**
* JSON JCDecaux API v1 format:
*
* <pre>
* [ {
* "number" : 94,
* "name" : "00094-PETIT PORT",
* "address" : "PETIT PORT - BD DU PETIT PORT",
* "position" : {
* "lat" : 47.243263914975486,
* "lng" : -1.556344610167984 },
* "banking" : true,
* "bonus" : false,
* "status" : "OPEN",
* "bike_stands" : 20,
* "available_bike_stands" : 1,
* "available_bikes" : 19,
* "last_update" : 1368611914000
* },
* ...
* ]
* </pre>
*/
public BikeRentalStation makeStation(JsonNode node) {
if (!node.path("status").getTextValue().equals("OPEN")) {
return null;
}
BikeRentalStation station = new BikeRentalStation();
station.id = String.format("%d", node.path("number").asInt());
station.x = node.path("position").path("lng").asDouble();
station.y = node.path("position").path("lat").asDouble();
station.name = node.path("name").getTextValue();
station.bikesAvailable = node.path("available_bikes").asInt();
station.spacesAvailable = node.path("available_bike_stands").asInt();
return station;
}Example 58
| Project: mbox_tools-master File: ConverterMetadataTest.java View source code |
@Test
public void shouldAddAndOverrideFromMetadata() throws IOException, MimeException, MessageParseException {
Map<String, String> metadata = new HashMap<>();
metadata.put("foo", "bar");
metadata.put("author", "John Doe <john.doe@his.com>");
Message msg = getMessage("mbox/encoding/invalid/simple.mbox", mb);
JsonNode node = null;
try {
node = mapper.readValue(new ByteArrayInputStream(Converter.toJSON(MessageParser.parse(msg), metadata).getBytes()), JsonNode.class);
} catch (IOException e) {
fail("Exception while parsing!: " + e);
}
assertTrue(node.has("foo"));
assertTrue(node.has("author"));
assertEquals("John Doe <john.doe@his.com>", node.get("author").getTextValue());
}Example 59
| Project: miso-lims-master File: PooledElementDeserializer.java View source code |
@Override
public Collection<Poolable> deserialize(JsonParser jp, DeserializationContext arg1) throws IOException, JsonProcessingException {
Collection<Poolable> poolables = new ArrayList<Poolable>();
JsonNode node = jp.readValueAsTree();
ObjectMapper o = new ObjectMapper();
for (JsonNode element : node) {
//this should be the poolable, i.e. plate, library or dilution
log.debug("Element: " + element.toString());
Poolable p = o.readValue(element, type);
poolables.add(p);
}
return poolables;
}Example 60
| Project: nabal-master File: ContesApplication.java View source code |
public String getRand() throws IOException {
InputStream inputStream = getClass().getResourceAsStream("/contes.json");
JsonNode jsonNodes = mapper.readTree(inputStream);
Iterator<Map.Entry<String, JsonNode>> fields = jsonNodes.get("fields").get(0).get("values").getFields();
List<Map.Entry<String, JsonNode>> listFields = new ArrayList<Map.Entry<String, JsonNode>>();
while (fields.hasNext()) {
listFields.add(fields.next());
}
int sz = listFields.size();
return listFields.get(rand.nextInt(sz)).getValue().getTextValue();
}Example 61
| Project: nosql-unit-master File: DataParser.java View source code |
public List<Object> readValues(InputStream dataStream) {
List<Object> definedObjects = new ArrayList<Object>();
try {
Iterator<JsonNode> elements = dataElements(dataStream);
while (elements.hasNext()) {
JsonNode definedObject = elements.next();
String implementationValue = getImplementationValue(definedObject);
JsonNode objectDefinition = getObjectDefinition(definedObject);
Object unmarshallObject = unmarshallObject(objectDefinition, implementationValue);
definedObjects.add(unmarshallObject);
}
} catch (JsonParseException e) {
throw new IllegalArgumentException(e);
} catch (JsonMappingException e) {
throw new IllegalArgumentException(e);
} catch (IOException e) {
throw new IllegalArgumentException(e);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
}
return definedObjects;
}Example 62
| Project: nuxeo-labs-master File: HTTPUtils.java View source code |
/**
* Adds the headers to the HttpURLConnection object
*
* @param inHttp
* @param inProps. A list of key-value pairs
* @param inJsonStr. A JSON objects as String, each property is a header to set
* @throws JsonProcessingException
* @throws IOException
* @since 7.2
*/
public static void addHeaders(HttpURLConnection inHttp, Properties inProps, String inJsonStr) throws JsonProcessingException, IOException {
if (inProps != null) {
for (String oneHeader : inProps.keySet()) {
inHttp.setRequestProperty(oneHeader, inProps.get(oneHeader));
}
}
if (StringUtils.isNotBlank(inJsonStr)) {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(inJsonStr);
Iterator<String> it = rootNode.getFieldNames();
while (it.hasNext()) {
String oneHeader = it.next();
inHttp.setRequestProperty(oneHeader, rootNode.get(oneHeader).getTextValue());
}
}
}Example 63
| Project: OpenClinica-master File: ODMClinicalDataController.java View source code |
@RequestMapping(value = "/json/view/{studyOID}/{studySubjectIdentifier}/{studyEventOID}/{formVersionOID}", method = RequestMethod.GET)
@ResponseBody
public JsonNode getClinicalData(@PathVariable("studyOID") String studyOID, @PathVariable("formVersionOID") String formVersionOID, @PathVariable("studyEventOID") String studyEventOID, @PathVariable("studySubjectIdentifier") String studySubjectIdentifier, @RequestParam(value = "includeDNs", defaultValue = "n", required = false) String includeDns, @RequestParam(value = "includeAudits", defaultValue = "n", required = false) String includeAudits, HttpServletRequest request) throws Exception {
ResourceBundleProvider.updateLocale(new Locale("en_US"));
String result = odmClinicaDataResource.getODMClinicaldata(studyOID, formVersionOID, studyEventOID, studySubjectIdentifier, includeDns, includeAudits, request);
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readTree(result);
}Example 64
| Project: partake-master File: GetUserAPITest.java View source code |
@Test
public void testGetUser() throws Exception {
ActionProxy proxy = getActionProxy(GET, "/api/user/get?userId=" + DEFAULT_USER_ID);
proxy.execute();
assertResultOK(proxy);
ObjectNode obj = getJSON(proxy);
assertThat(obj.get("id").asText(), is(DEFAULT_USER_ID));
// These values should not be public.
assertThat(obj.get("twitterId"), is(nullValue()));
assertThat(obj.get("lastLoginAt"), is(nullValue()));
assertThat(obj.get("calendarId"), is(nullValue()));
JsonNode twitter = obj.get("twitter");
assertThat(twitter, is(notNullValue()));
assertThat(twitter.get("screenName").asText(), is(DEFAULT_TWITTER_SCREENNAME));
assertThat(twitter.get("profileImageURL").asText(), is("http://www.example.com/"));
// These values should not be public.
assertThat(twitter.get("accessToken"), is(nullValue()));
assertThat(twitter.get("accessTokenSecret"), is(nullValue()));
// We don't expose OpenID Linkage.
assertThat(obj.get("openIDLinakge"), is(nullValue()));
}Example 65
| Project: pdfcombinercco-master File: WorkerProcessTest.java View source code |
@Test
public void test() throws MalformedURLException, IOException {
String url = "https://cs13.salesforce.com/services/data/v27.0/sobjects/ContentVersion";
String sessionId = "00DW0000000In2Q!ARoAQBmR_M2A6ZfCb3zWisyAUQQnlCQua0gle0HnM7fFBBaY4YgUcDrIpHLrC3Us0OCQKjiNv.kfEAPnyd0gabzj4SwOpm7o";
String contentDocumentId = "069W00000000IC3IAM";
String sourceFileName = "D:/tmp/generatedpdf/1365783621636/image1.png";
String jsonString = "{\"title\":\"aaab\",\"subTitle\":\"444\",\"showTimeAndDateStamp\":false,\"showTableOfContents\":false,\"showPageNumbering\":false,\"sessionId\":\"" + sessionId + "\",\"pdfCombinerCallback\":{\"callbackUrl\":\"https://na14.salesforce.com/services/data/v27.0/sobjects/Account/001d000000HiIUz\",\"callbackContents\":\"{\\\"Site\\\" : \\\"%result%\\\"}\"},\"outputFileName\":\"image1.png\",\"marketName\":null,\"marketContactInformation\":null,\"insertContentVersionUrl\":\"" + url + "\",\"includeServiceGuaranteeDoc\":false,\"includeResearchToolsDoc\":false,\"includeProductionSpecificationDoc\":false,\"includeOutdoorVocabularyTermsDoc\":true,\"email\":null,\"contents\":[],\"contentDocumentId\":\"" + contentDocumentId + "\",\"clientContactInformation\":null,\"clientCompanyName\":null,\"attachmentsUrl\":\"https://na14.salesforce.com/services/data/v27.0/sobjects/Attachment/\",\"appendixes\":[{\"title\":\"PDFCombiner sample document\",\"salesforceUrl\":\"https://c.na14.visual.force.com/services/data/v27.0/sobjects/ContentVersion/068d0000000ibMjAAI/VersionData\",\"pathOnClient\":\"PDFCombiner sample document.pdf\",\"description\":\"This is for simulating an Outdoor Vocabulary Terms Doc\"}],\"agencyName\":null,\"agencyContactInformation\":null}";
JsonNode jsonNode = Json.parse(jsonString);
PDFCombinerArguments pdfCombinerArguments = Json.fromJson(jsonNode, PDFCombinerArguments.class);
//WorkerProcess.uploadFileToSalesforce(sourceFileName, jsonString, pdfCombinerArguments);
}Example 66
| Project: play-restifyerrors-master File: Helper.java View source code |
public static void addUser(JsonNode reqJson) {
String userName = null;
String email = null;
try {
if (reqJson == null) {
throw new HTTPException(HTTPErrorType.BAD_REQUEST, "Bad Request:Content-Type is not application/json", null, "bad-request-json-header-missing");
}
User user = new User();
if (reqJson.get("email") != null) {
user.setEmailAddress(reqJson.get("email").asText());
}
if (reqJson.get("name") != null) {
user.setName(reqJson.get("name").asText());
}
user.save();
} catch (ValidationException ve) {
Map<String, String> infos = new HashMap<String, String>();
String value = null;
for (InvalidValue invalidValue : ve.getErrors()) {
if (invalidValue.getValue() != null) {
value = invalidValue.getValue().toString();
}
infos.put(invalidValue.getPropertyName(), value);
}
throw new HTTPException(HTTPErrorType.BAD_REQUEST, "Bad Request", ve, "user-bad-request", infos);
}
}Example 67
| Project: private_project_iparty-master File: ShareList.java View source code |
public static ShareList parse(InputStream stream) throws AppException {
ShareList shareList = new ShareList();
ObjectMapper om = new ObjectMapper();
try {
JsonNode rootNode = om.readTree(stream);
int result = rootNode.path("result").getIntValue();
if (result == 0) {
// 失败
String why = rootNode.path("description").getTextValue();
L.i("��失败:" + why);
throw AppException.fail(why);
} else if (result == 1) {
// �功
JsonNode dataNode = rootNode.path("details");
JsonFactory f = new JsonFactory();
JsonParser jp = f.createJsonParser(dataNode.toString());
jp.nextToken();
while (jp.nextToken() == JsonToken.START_OBJECT) {
IshareInfo info = om.readValue(jp, IshareInfo.class);
shareList.getShareList().add(info);
}
return shareList;
} else {
throw AppException.fail("接�异常");
}
} catch (JsonProcessingException e) {
L.i("json转�失败");
throw AppException.json(e);
} catch (IOException e) {
throw AppException.io(e);
}
}Example 68
| Project: product-esb-master File: HttpRelativeLocationHeaderTestCase.java View source code |
@Test(groups = { "wso2.esb", "localOnly" }, description = "Http Location header")
public void testRelativeLocationHeader() throws Exception {
String addUrl = getProxyServiceURLHttp("service0");
String query = "{\"employees\": [{\"id\": 0,\"name\": \"Carlene Pope\"},{\"id\": 1,\"name\": \"Jewell Richard\"}]}";
String expectedResult = "{\"employees\":[{\"id\":0,\"name\":\"Carlene Pope\"},{\"id\":1,\"name\":\"Jewell Richard\"}]}";
String actualResult = jsonclient.sendUserDefineRequest(addUrl, query).toString();
final ObjectMapper mapper = new ObjectMapper();
final JsonNode expectedJsonObject = mapper.readTree(expectedResult);
final JsonNode actualJsonObject = mapper.readTree(actualResult);
assertEquals(actualJsonObject, expectedJsonObject, "Could not process relative Location header.");
}Example 69
| Project: reddit-is-fun-master File: RestJsonClient.java View source code |
public static JsonNode connect(String url) { HttpClient httpclient = RedditIsFunHttpClientFactory.getGzipHttpClient(); // Prepare a request object HttpGet httpget = new HttpGet(url); // Execute the request HttpResponse response; ObjectMapper json = Common.getObjectMapper(); JsonNode data = null; try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { // A Simple JSON Response Read InputStream instream = entity.getContent(); data = json.readValue(instream, JsonNode.class); instream.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return data; }
Example 70
| Project: rest-client-master File: JSONUtil.java View source code |
public static String indentJSON(final String jsonIn) throws JSONParseException {
JsonFactory fac = new JsonFactory();
try {
JsonParser parser = fac.createJsonParser(new StringReader(jsonIn));
JsonNode node = null;
try {
node = jsonObjMapper.readTree(parser);
} catch (JsonParseException ex) {
throw new JSONParseException(ex.getMessage());
}
StringWriter out = new StringWriter();
// Create pretty printer:
JsonGenerator gen = fac.createJsonGenerator(out);
DefaultPrettyPrinter pp = new DefaultPrettyPrinter();
pp.indentArraysWith(new DefaultPrettyPrinter.Lf2SpacesIndenter());
gen.setPrettyPrinter(pp);
// Now write:
jsonObjMapper.writeTree(gen, node);
gen.flush();
gen.close();
return out.toString();
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
return jsonIn;
}Example 71
| Project: rsimulator-master File: JsonHandler.java View source code |
/**
* {@inheritDoc}
*/
@Override
protected String escape(String request, boolean isCandidate) {
String result = request;
if (isCandidate && request != null && !"".equals(request)) {
try {
StringBuilder sb = new StringBuilder();
JsonNode rootNode = mapper.readValue(request, JsonNode.class);
escape(sb, rootNode, null);
result = sb.toString();
} catch (Exception e) {
log.error(null, e);
}
}
return result;
}Example 72
| Project: s3hdfs-master File: BucketInfoRedirect.java View source code |
public boolean checkEmpty() throws IOException {
GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(), request.getServerName(), request.getServerPort(), "GETCONTENTSUMMARY", path.getUserName(), path.getHdfsRootBucketPath(), GET);
httpClient.executeMethod(httpGet);
String contentSummaryJson = readInputStream(httpGet.getResponseBodyAsStream());
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonRoot = mapper.readTree(contentSummaryJson);
int dirs = jsonRoot.get("ContentSummary").get("directoryCount").getIntValue();
return (dirs == 1);
}Example 73
| Project: sequenceiq-samples-master File: QueueInformation.java View source code |
public void printQueueInfo(HttpClient client, ObjectMapper mapper, String schedulerResourceURL) {
//http://sandbox.hortonworks.com:8088/ws/v1/cluster/scheduler in case of HDP
GetMethod get = new GetMethod(schedulerResourceURL);
get.setRequestHeader("Accept", "application/json");
try {
int statusCode = client.executeMethod(get);
if (statusCode != HttpStatus.SC_OK) {
LOGGER.error("Method failed: " + get.getStatusLine());
}
InputStream in = get.getResponseBodyAsStream();
JsonNode jsonNode = mapper.readValue(in, JsonNode.class);
ArrayNode queues = (ArrayNode) jsonNode.path("scheduler").path("schedulerInfo").path("queues").get("queue");
for (int i = 0; i < queues.size(); i++) {
JsonNode queueNode = queues.get(i);
LOGGER.info("queueName / usedCapacity / absoluteUsedCap / absoluteCapacity / absMaxCapacity: " + queueNode.findValue("queueName") + " / " + queueNode.findValue("usedCapacity") + " / " + queueNode.findValue("absoluteUsedCapacity") + " / " + queueNode.findValue("absoluteCapacity") + " / " + queueNode.findValue("absoluteMaxCapacity"));
}
} catch (IOException e) {
LOGGER.error("Exception occured", e);
} finally {
get.releaseConnection();
}
}Example 74
| Project: siren-master File: RangePropertyParser.java View source code |
@Override
int[] parse() throws ParseException {
final int[] range = new int[2];
final JsonNode value = node.path(RANGE_PROPERTY);
if (!(value.isArray() && (value.size() == 2))) {
throw new ParseException("Invalid value for property '" + RANGE_PROPERTY + "'");
}
final Iterator<JsonNode> it = value.iterator();
JsonNode e;
for (int i = 0; i < 2; i++) {
e = it.next();
if (!e.isInt()) {
throw new ParseException("Invalid property '" + RANGE_PROPERTY + "': range value is not an integer");
}
range[i] = e.asInt();
}
return range;
}Example 75
| Project: skysail-server-ext-master File: FriendsResource.java View source code |
@Override
protected List<FacebookUser> getData() {
JsonNode jsonRootNode;
List<FacebookUser> friends = new ArrayList<FacebookUser>();
try {
String friendsLink = myFriendsOnFacebookUrl + "?access_token=";
friendsLink += facebookApp.getAccessToken(currentUser);
jsonRootNode = mapper.readTree(new URL(friendsLink));
JsonNode data = jsonRootNode.get("data");
if (data != null) {
Iterator<JsonNode> elements = data.getElements();
while (elements.hasNext()) {
JsonNode next = elements.next();
friends.add(new FacebookUser(next, null));
}
}
return friends;
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}Example 76
| Project: sling-master File: JsonUtils.java View source code |
/**
* Get {@link JsonNode} from a a String containing JSON.
*
* @param jsonString A string containing JSON
* @return A {@link JsonNode} that is the root node of the JSON structure.
* @throws ClientException if error occurs while reading json string
*/
public static JsonNode getJsonNodeFromString(String jsonString) throws ClientException {
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(jsonString);
} catch (JsonProcessingException e) {
throw new ClientException("Could not read json file.", e);
} catch (IOException e) {
throw new ClientException("Could not read json node.", e);
}
}Example 77
| Project: spring-social-500px-master File: FivepxProfileMixin.java View source code |
@Override
public FivepxProfile deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
FivepxProfile profile = null;
String sex = null;
JsonNode tree = jp.readValueAsTree();
JsonNode profileNode = tree.get("user");
long id = profileNode.get("id").asLong();
String fullName = profileNode.get("fullname").asText();
String userName = profileNode.get("username").asText();
String city = profileNode.get("city").asText();
String country = profileNode.get("country").asText();
String userPicUrl = getUserProfilePicValue(profileNode, "userpic_url");
String domain = profileNode.get("domain").asText();
String about = profileNode.get("about").asText();
int followersCount = profileNode.get("followers_count").getIntValue();
int friendsCount = profileNode.get("friends_count").getIntValue();
int sexVal = profileNode.get("sex").getIntValue();
if (sexVal == 0) {
sex = "Undefined";
} else if (sexVal == 1) {
sex = "Male";
} else if (sexVal == 2) {
sex = "Female";
}
profile = new FivepxProfile(id, userName, fullName, userPicUrl);
profile.setSex(sex);
profile.setAbout(about);
profile.setDomain(domain);
profile.setFollowersCount(followersCount);
profile.setFriendsCount(friendsCount);
profile.setCity(city);
profile.setCountry(country);
return profile;
}Example 78
| Project: torrenttunes-server-master File: Transformations.java View source code |
public static ObjectNode artistViewJson(String artistMbid) {
Artist artist = ARTIST.findFirst("mbid = ?", artistMbid);
List<ArtistTagView> tags = ARTIST_TAG_VIEW.find("mbid = ?", artistMbid);
List<Model> relatedArtists = RELATED_ARTIST_VIEW.findBySQL(RELATED_ARTIST_VIEW_SQL, artistMbid, artistMbid);
// RELATED_ARTIST_VIEW.find
// log.info(RELATED_ARTIST_VIEW.find(
// "mbid like ? and `mbid:1` not like ?",
// artistMbid,artistMbid).toSql());
ObjectNode a = Tools.MAPPER.createObjectNode();
JsonNode c = Tools.jsonToNode(artist.toJson(false));
ObjectNode on = Tools.MAPPER.valueToTree(c);
a.putAll(on);
ArrayNode an = a.putArray("related_artists");
for (Model relatedArtist : relatedArtists) {
an.add(Tools.jsonToNode(relatedArtist.toJson(false)));
}
ArrayNode ab = a.putArray("tags");
for (ArtistTagView tag : tags) {
ab.add(Tools.jsonToNode(tag.toJson(false)));
}
return a;
}Example 79
| Project: tuscany-sca-2.x-master File: JSON2OutputStream.java View source code |
public void transform(Object source, OutputStream sink, TransformationContext context) {
if (source == null) {
return;
}
if (source instanceof JsonNode) {
JacksonHelper.write((JsonNode) source, sink);
} else if (source instanceof JsonParser) {
JacksonHelper.write((JsonParser) source, sink);
} else {
try {
sink.write(source.toString().getBytes("UTF-8"));
} catch (Exception e) {
throw new TransformationException(e);
}
}
}Example 80
| Project: vector_health-master File: GoogleAuthProvider.java View source code |
@Override
protected GoogleAuthUser transform(final GoogleAuthInfo info, final String state) throws AuthException {
final String url = getConfiguration().getString(USER_INFO_URL_SETTING_KEY);
final Response r = WS.url(url).setQueryParameter(OAuth2AuthProvider.Constants.ACCESS_TOKEN, info.getAccessToken()).get().get(PlayAuthenticate.TIMEOUT);
final JsonNode result = r.asJson();
if (result.get(OAuth2AuthProvider.Constants.ERROR) != null) {
throw new AuthException(result.get(OAuth2AuthProvider.Constants.ERROR).asText());
} else {
Logger.debug(result.toString());
return new GoogleAuthUser(result, info, state);
}
}Example 81
| Project: vocidex-master File: DescriberIterator.java View source code |
@Override
public VocidexDocument next() {
Resource resource = it.next();
ObjectNode description = JSONHelper.createObject();
describer.describe(resource, description);
JsonNode typeNode = description.get("type");
if (typeNode == null || !typeNode.isTextual()) {
throw new VocidexException("Description for " + resource + " must include \"type\" key: " + description);
}
return new VocidexDocument(typeNode.getTextValue(), resource, description);
}Example 82
| Project: webpie-master File: JacksonLookup.java View source code |
@SuppressWarnings("unchecked")
@Override
public <T> T unmarshal(Class<T> entityClass, byte[] data) {
try {
if (data.length == 0)
throw new ClientDataError("Client did not provide a json request in the body of the request");
if (JsonNode.class.isAssignableFrom(entityClass))
return (T) mapper.readTree(data);
return mapper.readValue(data, entityClass);
} catch (JsonProcessingException e) {
throw new ClientDataError("invalid json in client request. " + e.getMessage(), e);
} catch (IOException e) {
throw new RuntimeException("should not occur", e);
}
}Example 83
| Project: WebServices-master File: JSONUtil.java View source code |
public static String indentJSON(final String jsonIn) throws JSONParseException {
JsonFactory fac = new JsonFactory();
try {
JsonParser parser = fac.createJsonParser(new StringReader(jsonIn));
JsonNode node = null;
try {
node = jsonObjMapper.readTree(parser);
} catch (JsonParseException ex) {
throw new JSONParseException(ex.getMessage());
}
StringWriter out = new StringWriter();
// Create pretty printer:
JsonGenerator gen = fac.createJsonGenerator(out);
DefaultPrettyPrinter pp = new DefaultPrettyPrinter();
pp.indentArraysWith(new DefaultPrettyPrinter.Lf2SpacesIndenter());
gen.setPrettyPrinter(pp);
// Now write:
jsonObjMapper.writeTree(gen, node);
gen.flush();
gen.close();
return out.toString();
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
return jsonIn;
}Example 84
| Project: ycsb-master File: TestMeasurementsExporter.java View source code |
@Test
public void testJSONArrayMeasurementsExporter() throws IOException {
Properties props = new Properties();
props.put(Measurements.MEASUREMENT_TYPE_PROPERTY, "histogram");
Measurements mm = new Measurements(props);
ByteArrayOutputStream out = new ByteArrayOutputStream();
JSONArrayMeasurementsExporter export = new JSONArrayMeasurementsExporter(out);
long min = 5000;
long max = 100000;
ZipfianGenerator zipfian = new ZipfianGenerator(min, max);
for (int i = 0; i < 1000; i++) {
int rnd = zipfian.nextValue().intValue();
mm.measure("UPDATE", rnd);
}
mm.exportMeasurements(export);
export.close();
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(out.toString("UTF-8"));
assertTrue(json.isArray());
assertEquals(json.get(0).get("measurement").asText(), "Operations");
assertEquals(json.get(4).get("measurement").asText(), "MaxLatency(us)");
assertEquals(json.get(11).get("measurement").asText(), "4");
}Example 85
| Project: GNDMS-master File: ConfigEditor.java View source code |
/**
* Apply the update diff to node subject to the following rules. For every singular node that is updated, the
* ConfigEditor.Visitor of this ConfigEditor is called.
*
* The toplevel is expected to be an object or an array or null (initially only).
*
* Updates to the toplevel are always appended, i.e. the toplevel is never fully overwritten.
*
* Sublevels are always overwritten unless all keys on the path to the current level are all prefixed with '+'.
* (However the final key to the value must not be prefixed with '+'!)
*
* To delete, prefix the key of the entry that is to be deleted with '-'
*
* @param node the root node to be updated
* @param update the update to be applied to the root node
* @return the updated node
*
* @throws UpdateRejectedException if anything goes wrong or the visitor vetos
*/
@SuppressWarnings({ "UnnecessaryContinue" })
@NotNull
public JsonNode update(@NotNull JsonNode node, @NotNull JsonNode update) throws UpdateRejectedException {
if (!(node.isObject() || node.isArray() || node.isNull()))
throw new IllegalArgumentException("Toplevel node is neither an object nor an array nor null");
final Stack<Record> records = new Stack<Record>();
final Record topRecord = new Record(node, update, null, null, Update.Mode.APPEND);
records.push(topRecord);
try {
while (!records.empty()) {
final Record rec = records.pop();
// handles nodes of different types and null snapshot causes by missing pieces
if (rec.snapshot == null || rec.snapshot.getClass() != rec.update.getClass()) {
rec.visit(records, visitor);
continue;
}
// (1) Handle value nodes
if (rec.snapshot.isValueNode()) {
if (!rec.snapshot.equals(rec.update))
// replace
rec.visit(records, visitor);
continue;
}
// (2) Handle array nodes
if (rec.snapshot.isArray()) {
if ((rec.snapshot.size() != rec.update.size()) || (!Update.Mode.APPEND.equals(rec.mode)))
// replace if update is of different size or we're not in APPEND
rec.visit(records, visitor);
else {
// update all childs
for (int i = 0; i < rec.update.size(); i++) records.push(new Record(rec.snapshot.get(i), rec.update.get(i), rec, i, Update.Mode.OVERWRITE));
}
continue;
}
// (3) Handle object nodes
if (rec.snapshot.isObject()) {
if (!Update.Mode.APPEND.equals(rec.mode)) {
// replace if we're not in APPEND
rec.visit(records, visitor);
} else {
// handle childs according to mode selected by key prefix
for (final Iterator<String> iter = rec.update.getFieldNames(); iter.hasNext(); ) {
final String fieldName = iter.next();
switch(fieldName.charAt(0)) {
case '+':
{
final String snapshotFieldName = fieldName.substring(1);
final JsonNode snapshot = rec.snapshot.get(snapshotFieldName);
if (snapshot != null && snapshot.isObject())
records.push(new Record(snapshot, rec.update.get(fieldName), rec, snapshotFieldName, Update.Mode.APPEND));
else
throw new IllegalArgumentException("No updatable hash found");
}
break;
case '-':
{
final String snapshotFieldName = fieldName.substring(1);
new Record(rec.snapshot.get(snapshotFieldName), null, rec, snapshotFieldName, Update.Mode.DELETE).visit(records, visitor);
}
break;
default:
records.push(new Record(rec.snapshot.get(fieldName), rec.update.get(fieldName), rec, fieldName, Update.Mode.OVERWRITE));
}
}
}
continue;
}
throw new IllegalArgumentException("Unknown node type encountered");
}
} catch (IllegalArgumentException iae) {
throw new UpdateRejectedException(iae);
} catch (IOException ioe) {
throw new UpdateRejectedException(ioe);
}
return topRecord.snapshot;
}Example 86
| Project: aerogear-unifiedpush-server-master File: HealthStatusTest.java View source code |
@Test
public void shouldReturnJson() throws IOException {
//given
HealthStatus status = getHealthStatus();
//when
final ObjectMapper mapper = new ObjectMapper();
final JsonNode value = mapper.valueToTree(status);
//then
final JsonNode format = mapper.reader().readTree(getClass().getResourceAsStream("/health-format.json"));
//because the json file will use int for the 'runtime' field and the model long
assertThat(value.toString()).isEqualTo(format.toString());
}Example 87
| Project: AIM-master File: InstrumentationEntityDeserializer.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public InstrumentationEntity<?> deserialize(JsonParser parser, DeserializationContext context) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ObjectCodec oc = parser.getCodec();
JsonNode node = oc.readTree(parser);
Class<? extends Scope> scopeClass = mapper.treeToValue(node.get("scopeClass"), Class.class);
Scope scope = mapper.treeToValue(node.get("scope"), scopeClass);
InstrumentationEntity entity = new InstrumentationEntity(scope);
Restriction restriction = mapper.treeToValue(node.get("localRestriction"), Restriction.class);
entity.setLocalRestriction(restriction);
MeasurementProbe[] probesAsArray = mapper.treeToValue(node.get("probesAsArray"), MeasurementProbe[].class);
Set<MeasurementProbe> probes = new HashSet<>();
for (MeasurementProbe mp : probesAsArray) {
probes.add(mp);
}
entity.getProbes().addAll(probes);
return entity;
}Example 88
| Project: akvo-flow-master File: CaddisflyResourceDao.java View source code |
/**
* lists caddisfly resources. Source is the json file caddisfly-tests.json stored in
* WEB-INF/resources
*/
public List<CaddisflyResource> listResources() {
List<CaddisflyResource> result = null;
try {
InputStream stream = getClass().getClassLoader().getResourceAsStream("resources/caddisfly/caddisfly-tests.json");
// create a list of caddisflyResource objects
JsonNode rootNode = mapper.readTree(stream);
result = mapper.readValue(rootNode.get("tests"), new TypeReference<List<CaddisflyResource>>() {
});
} catch (Exception e) {
log.log(Level.SEVERE, "Error parsing Caddisfly resource: " + e.getMessage(), e);
}
if (result != null) {
return result;
} else {
return Collections.emptyList();
}
}Example 89
| Project: archived-net-virt-platform-master File: JSONDecoder.java View source code |
@Override
protected Object decode(ChannelHandlerContext chc, Channel channel, ChannelBuffer cb) throws Exception {
ctr++;
cb.markReaderIndex();
ChannelBuffer compositeBuffer = cb;
if (remainderBytes != null) {
ChannelBuffer remainderBuffer = ChannelBuffers.wrappedBuffer(remainderBytes);
compositeBuffer = ChannelBuffers.wrappedBuffer(remainderBuffer, cb);
remainderBytes = null;
}
ChannelBufferInputStream cbis = new ChannelBufferInputStream(compositeBuffer);
JsonParser jp = mjf.createJsonParser(cbis);
JsonNode node = null;
try {
node = jp.readValueAsTree();
} catch (EOFException e) {
return null;
} catch (JsonProcessingException e) {
if (e.getMessage().contains("end-of-input")) {
cb.resetReaderIndex();
return null;
} else {
throw e;
}
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
jp.releaseBuffered(os);
if (os.size() > 0) {
remainderBytes = os.toByteArray();
}
return node;
}Example 90
| Project: BackEnd-master File: GeoDeserializer.java View source code |
@Override
public Geo deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
final JsonNode tree = jp.readValueAsTree();
final JsonNode coordinates = tree.get("coordinates");
final JsonNode type = tree.get("type");
final Geo geo = new Geo();
geo.setType(type.getTextValue());
if (Geometries.Polygon.equals(Geometries.valueOf(type.getTextValue()))) {
geo.setCoordinates(createPolygon(coordinates));
} else {
geo.setCoordinates(createPoint(coordinates));
}
return geo;
}Example 91
| Project: camel-master File: FreeGeoIpGeoLocationProvider.java View source code |
@Override
public GeoLocation getCurrentGeoLocation() throws Exception {
HttpClient httpClient = component.getHttpClient();
GetMethod getMethod = new GetMethod("http://freegeoip.io/json/");
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
throw new IllegalStateException("Got the unexpected http-status '" + getMethod.getStatusLine() + "' for the geolocation");
}
String geoLocation = component.getCamelContext().getTypeConverter().mandatoryConvertTo(String.class, getMethod.getResponseBodyAsStream());
if (isEmpty(geoLocation)) {
throw new IllegalStateException("Got the unexpected value '" + geoLocation + "' for the geolocation");
}
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(geoLocation, JsonNode.class);
JsonNode latitudeNode = notNull(node.get("latitude"), "latitude");
JsonNode longitudeNode = notNull(node.get("longitude"), "longitude");
return new GeoLocation(longitudeNode.asText(), latitudeNode.asText());
} finally {
getMethod.releaseConnection();
}
}Example 92
| Project: cloudpier-adapters-master File: VcapServicesReader.java View source code |
/** * Returns the JsonNode corresponding a given service name. */ public static JsonNode findBindedService(JsonNode rootNode, String serviceName) { /* * iterate over services */ for (JsonNode service : rootNode) { /* * iterate over binded services */ for (JsonNode binded : service) { String name = binded.path("name").getValueAsText(); if (serviceName.equals(name)) { return binded; } } } return null; }
Example 93
| Project: fixflow-master File: JsonConverterUtil.java View source code |
public static List<String> getPropertyValueAsList(String name, JsonNode objectNode) { List<String> resultList = new ArrayList<String>(); JsonNode propertyNode = getProperty(name, objectNode); if (propertyNode != null && "null".equalsIgnoreCase(propertyNode.asText()) == false) { String propertyValue = propertyNode.asText(); String[] valueList = propertyValue.split(","); for (String value : valueList) { resultList.add(value.trim()); } } return resultList; }
Example 94
| Project: gnip-java-master File: GeoDeserializer.java View source code |
@Override
public Geo deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
final JsonNode tree = jp.readValueAsTree();
final JsonNode coordinates = tree.get("coordinates");
final JsonNode type = tree.get("type");
final Geo geo = new Geo();
geo.setType(type.getTextValue());
if (Geometries.Polygon.equals(Geometries.valueOf(type.getTextValue()))) {
geo.setCoordinates(createPolygon(coordinates));
} else {
geo.setCoordinates(createPoint(coordinates));
}
return geo;
}Example 95
| Project: gnip4j-master File: GeoDeserializer.java View source code |
@Override
public Geo deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
final JsonNode tree = jp.readValueAsTree();
final JsonNode coordinates = tree.get("coordinates");
final JsonNode type = tree.get("type");
final Geo geo = new Geo();
geo.setType(type.getTextValue());
if (Geometries.Polygon.equals(Geometries.valueOf(type.getTextValue()))) {
geo.setCoordinates(createPolygon(coordinates));
} else {
geo.setCoordinates(createPoint(coordinates));
}
return geo;
}Example 96
| Project: jcommune-master File: JsonResponseUtils.java View source code |
public static List<String> fetchErrorMessagesFromJsonString(String jsonString) {
List<String> result = new ArrayList<>();
JsonNode rootNode;
try {
rootNode = OBJECT_MAPPER.readValue(jsonString, JsonNode.class);
} catch (IOException e) {
return result;
}
JsonNode resultNode = rootNode.get("result");
if (resultNode != null && resultNode.isArray()) {
for (JsonNode itemNode : resultNode) {
JsonNode defaultMessage = itemNode.get("defaultMessage");
if (defaultMessage != null) {
result.add(defaultMessage.getTextValue());
}
}
}
return result;
}Example 97
| Project: jstorm-master File: JSONUtil.java View source code |
public boolean equals(String firstJSON, String secondJSON) {
try {
JsonNode tree1 = MAPPER.readTree(firstJSON);
JsonNode tree2 = MAPPER.readTree(secondJSON);
boolean areEqual = tree1.equals(tree2);
return areEqual;
} catch (JsonProcessingException e) {
LOGGER.error("json compare wrong:" + firstJSON + ";" + secondJSON, e);
} catch (IOException e) {
LOGGER.error("json compare wrong:" + firstJSON + ";" + secondJSON, e);
}
return false;
}Example 98
| Project: jTalk-master File: JsonResponseUtils.java View source code |
public static List<String> fetchErrorMessagesFromJsonString(String jsonString) {
List<String> result = new ArrayList<>();
JsonNode rootNode;
try {
rootNode = OBJECT_MAPPER.readValue(jsonString, JsonNode.class);
} catch (IOException e) {
return result;
}
JsonNode resultNode = rootNode.get("result");
if (resultNode != null && resultNode.isArray()) {
for (JsonNode itemNode : resultNode) {
JsonNode defaultMessage = itemNode.get("defaultMessage");
if (defaultMessage != null) {
result.add(defaultMessage.getTextValue());
}
}
}
return result;
}Example 99
| Project: loggingbox-master File: LogsInsertServlet.java View source code |
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
String logsString;
String contentEncoding = req.getHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.equals("gzip")) {
GZIPInputStream is = new GZIPInputStream(req.getInputStream());
logsString = IOUtil.toString(is, "UTF-8");
is.close();
} else {
logsString = IOUtil.toString(req.getInputStream());
}
JsonNode jsonNode = objectMapper.readTree(logsString);
List<Log> logsToInsert = new ArrayList<Log>();
if (jsonNode.isArray()) {
for (int i = 0; i < jsonNode.size(); i++) {
JsonNode logNode = jsonNode.get(i);
Log log = new Log();
if (logNode.get("date") != null) {
log.setDate(new Date(logNode.get("date").asLong()));
} else {
log.setDate(new Date());
}
log.setData(logNode.get("data").asText());
log.setApplicationId(logNode.get("applicationId").asText());
if (logNode.get("host") != null) {
log.setHost(logNode.get("host").asText());
} else {
log.setHost(req.getRemoteHost());
}
if (logNode.get("type") != null) {
log.setType(logNode.get("type").asText());
}
if (logNode.get("level") != null) {
try {
log.setLevel(Level.valueOf(logNode.get("level").asText().toUpperCase()));
} catch (Exception ex) {
}
}
logsToInsert.add(log);
}
}
logComponent.insertLog(logsToInsert);
resp.getWriter().write("OK");
} catch (Exception ex) {
ex.printStackTrace();
resp.getWriter().write("KO");
}
}Example 100
| Project: ning-api-java-master File: SubResources.java View source code |
/**
* Method for loading specified resources
*/
protected <RT> RT loadResource(Class<RT> type, String id, RT instance) {
if (resources == null || id == null) {
return null;
}
JsonNode entry = resources.get(id);
if (entry == null) {
return null;
}
// Ok: should be an object... if not, indicate error
if (!entry.isObject()) {
throw new IllegalArgumentException("Corrupt or malformed data: " + type.getSimpleName() + " data for '" + id + "' not a JSON object but " + entry.asToken());
}
// Then try binding
try {
if (instance == null) {
instance = objectMapper.treeToValue(entry, type);
} else {
objectMapper.updatingReader(instance).readValue(entry.traverse());
}
} catch (IOException e) {
throw new IllegalArgumentException("Corrupt or malformed data: author data for '" + id + "' could not be bound, problem: " + e.getMessage());
}
if (boundResources == null) {
boundResources = new HashMap<String, Object>();
}
boundResources.put(id, instance);
return instance;
}Example 101
| Project: nuxeo-master File: EntityJsonReader.java View source code |
@Override public final EntityType read(JsonNode jn) throws IOException { if (!jn.isObject()) { throw new MarshallingException("Json does not contain an object as expected"); } JsonNode entityNode = jn.get(ENTITY_FIELD_NAME); if (entityNode == null || entityNode.isNull() || !entityNode.isTextual()) { throw new MarshallingException("Json object does not contain an entity-type field as expected"); } String entityValue = entityNode.getTextValue(); if (!entityType.equals(entityValue)) { throw new MarshallingException("Json object entity-type is wrong. Expected is " + entityType + " but was " + entityValue); } return readEntity(jn); }