List of usage examples for com.fasterxml.jackson.databind.node ArrayNode size
public int size()
From source file:com.redhat.lightblue.config.AbstractMetadataConfiguration.java
@Override public void initializeFromJson(JsonNode node) { if (node != null) { JsonNode x = node.get("hookConfigurationParsers"); if (x != null && x.isArray()) { // each element in array is a class Iterator<JsonNode> elements = ((ArrayNode) x).elements(); while (elements.hasNext()) { JsonNode e = elements.next(); String clazz = e.asText(); // instantiate the class Object o = null;// www . j a v a 2s .c o m try { o = Class.forName(clazz).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, ex.getMessage()); } // add to list or fail if (o instanceof HookConfigurationParser) { hookConfigurationParsers.add((HookConfigurationParser) o); } else { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "Class not instance of HookConfigurationParser: " + clazz); } } } ArrayNode backendParsersJs = (ArrayNode) node.get("backendParsers"); if (backendParsersJs != null) { Iterator<JsonNode> bpjsItr = backendParsersJs.iterator(); while (bpjsItr.hasNext()) { JsonNode jsonNode = bpjsItr.next(); String name = jsonNode.get("name").asText(); String clazz = jsonNode.get("clazz").asText(); if (name == null || clazz == null) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "Backend/DataStoreParser class was not informed: name='" + name + "' clazz=" + clazz); } try { DataStoreParser instance = (DataStoreParser) Class.forName(clazz).newInstance(); AbstractMap.SimpleEntry<String, DataStoreParser> stringDataStoreParserSimpleEntry = new AbstractMap.SimpleEntry<>( name, instance); backendParsers.add(stringDataStoreParserSimpleEntry); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "Class not instance of Backend/DataStoreParser: " + clazz); } } } ArrayNode propertyParserJs = (ArrayNode) node.get("propertyParsers"); if (propertyParserJs != null) { for (JsonNode jsonNode : propertyParserJs) { String name = jsonNode.get("name").asText(); String clazz = jsonNode.get("clazz").asText(); if (name == null || clazz == null) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "PropertyParser Name/Class not informed: name=" + name + " clazz=" + clazz); } try { PropertyParser instance = (PropertyParser) Class.forName(clazz).newInstance(); AbstractMap.SimpleEntry<String, PropertyParser> stringPropertyParserSimpleEntry = new AbstractMap.SimpleEntry<>( name, instance); propertyParsers.add(stringPropertyParserSimpleEntry); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "Class not instance of PropertyParser: " + clazz); } } } JsonNode roleMapJs = node.get("roleMap"); if (roleMapJs != null) { // If the roleMap element is defined, it is expected to have all the roles mapped MetadataRole[] values = MetadataRole.values(); for (MetadataRole value : values) { String name = value.toString(); ArrayNode rolesJs = (ArrayNode) roleMapJs.get(name); if (rolesJs == null || rolesJs.size() == 0) { throw Error.get(MetadataConstants.ERR_CONFIG_NOT_VALID, "roleMap missing the role \"" + name + "\""); } roleMap.put(value, new ArrayList<String>()); for (JsonNode jsonNode : rolesJs) { roleMap.get(value).add(jsonNode.textValue()); } } } x = node.get("validateRequests"); if (x != null) { validateRequests = x.booleanValue(); } } }
From source file:org.openmhealth.reference.request.DataWriteRequest.java
/** * Validates the data and, if valid, stores it. *//*w w w . jav a2 s . c om*/ @Override public void service() throws OmhException { // First, short-circuit if this request has already been serviced. if (isServiced()) { return; } else { setServiced(); } // Check to be sure the schema is known. MultiValueResult<? extends Schema> schemas = Registry.getInstance().getSchemas(schemaId, version, 0, 1); if (schemas.count() == 0) { throw new OmhException( "The schema ID, '" + schemaId + "', and version, '" + version + "', pair is unknown."); } Schema schema = schemas.iterator().next(); // Get the user that owns this token. User requestingUser = authToken.getUser(); // Parse the data. JsonNode dataNode; try { dataNode = JSON_FACTORY.createJsonParser(data).readValueAs(JsonNode.class); } catch (JsonParseException e) { throw new OmhException("The data was not well-formed JSON.", e); } catch (JsonProcessingException e) { throw new OmhException("The data was not well-formed JSON.", e); } catch (IOException e) { throw new OmhException("The data could not be read.", e); } // Make sure it is a JSON array. if (!(dataNode instanceof ArrayNode)) { throw new OmhException("The data was not a JSON array."); } ArrayNode dataArray = (ArrayNode) dataNode; // Get the number of data points. int numDataPoints = dataArray.size(); // Create the result list of data points. List<Data> dataPoints = new ArrayList<Data>(numDataPoints); // Create a new ObjectMapper that will be used to convert the meta-data // node into a MetaData object. ObjectMapper mapper = new ObjectMapper(); // For each element in the array, be sure it is a JSON object that // represents a valid data point for this schema. for (int i = 0; i < numDataPoints; i++) { // Get the current data point. JsonNode dataPoint = dataArray.get(i); // Validate that it is a JSON object. if (!(dataPoint instanceof ObjectNode)) { throw new OmhException("A data point was not a JSON object: " + i); } ObjectNode dataObject = (ObjectNode) dataPoint; // Attempt to get the meta-data; MetaData metaData = null; JsonNode metaDataNode = dataObject.get(Data.JSON_KEY_METADATA); if (metaDataNode != null) { metaData = mapper.convertValue(metaDataNode, MetaData.class); } // Attempt to get the schema data. JsonNode schemaData = dataObject.get(Data.JSON_KEY_DATA); // If the data is missing, fail the request. if (schemaData == null) { throw new OmhException("A data point's '" + Data.JSON_KEY_DATA + "' field is missing."); } // Create and add the point to the set of data. dataPoints.add(schema.validateData(requestingUser.getUsername(), metaData, schemaData)); } // Store the data. DataSet.getInstance().storeData(dataPoints); }
From source file:net.idea.opentox.cli.dataset.DatasetClient.java
@Override public List<Dataset> processPayload(InputStream in, String mediaType) throws RestException, IOException { List<Dataset> list = null; if (mime_json.equals(mediaType)) { ObjectMapper m = new ObjectMapper(); JsonNode node = m.readTree(in);/* w w w. j a v a 2s .co m*/ if (callback != null) callback.callback(node); ArrayNode data = (ArrayNode) node.get("dataset"); if (data != null) for (int i = 0; i < data.size(); i++) { JsonNode metadata = data.get(i); Dataset dataset = new Dataset(new Identifier(metadata.get("URI").textValue())); if (list == null) list = new ArrayList<Dataset>(); list.add(dataset); try { dataset.getMetadata().setTitle(metadata.get("title").textValue()); } catch (Exception x) { } try { dataset.getMetadata().setSeeAlso(metadata.get("seeAlso").textValue()); } catch (Exception x) { } try { dataset.getMetadata().setStars(metadata.get("stars").intValue()); } catch (Exception x) { } dataset.getMetadata().setRights(new Rights()); try { dataset.getMetadata().getRights().setRightsHolder(metadata.get("rightsHolder").textValue()); } catch (Exception x) { } try { dataset.getMetadata().getRights().setURI(metadata.get("rights").get("URI").textValue()); } catch (Exception x) { } try { dataset.getMetadata().getRights() .setType(_type.rights.valueOf(metadata.get("rights").get("type").textValue())); } catch (Exception x) { } } return list; } else if (mime_rdfxml.equals(mediaType)) { return super.processPayload(in, mediaType); } else if (mime_n3.equals(mediaType)) { return super.processPayload(in, mediaType); } else if (mime_csv.equals(mediaType)) { return super.processPayload(in, mediaType); } else return super.processPayload(in, mediaType); }
From source file:com.activiti.service.activiti.ProcessInstanceService.java
public List<String> getCompletedActivityInstancesAndProcessDefinitionId(ServerConfig serverConfig, String processInstanceId) { URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_ACTIVITY_INSTANCE_LIST_URL); builder.addParameter("processInstanceId", processInstanceId); //builder.addParameter("finished", "true"); builder.addParameter("sort", "startTime"); builder.addParameter("order", "asc"); builder.addParameter("size", DEFAULT_ACTIVITY_SIZE); HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder)); JsonNode node = clientUtil.executeRequest(get, serverConfig); List<String> result = new ArrayList<String>(); if (node.has("data") && node.get("data").isArray()) { ArrayNode data = (ArrayNode) node.get("data"); ObjectNode activity = null;//from w w w. j av a 2s .c o m for (int i = 0; i < data.size(); i++) { activity = (ObjectNode) data.get(i); if (activity.has("activityType")) { result.add(activity.get("activityId").asText()); } } } return result; }
From source file:org.modeshape.web.jcr.rest.handler.RestItemHandlerImpl.java
/** * Performs a bulk deletion of items, using a single {@link javax.jcr.Session}. If any of the items cannot be deleted for whatever * reason, the entire operation fails./*from w ww . j a v a 2 s . c om*/ * * @param request the servlet request; may not be null or unauthenticated * @param repositoryName the URL-encoded repository name * @param workspaceName the URL-encoded workspace name * @param requestContent the JSON-encoded array of the nodes to remove * @return a {@code non-null} {@link Result} * @throws javax.jcr.RepositoryException if any of the JCR operations fail * @see RestItemHandlerImpl#deleteItem(Request, String, String, String) */ @Override public void deleteItems(Request request, String repositoryName, String workspaceName, String requestContent) throws RepositoryException { ArrayNode requestArray = stringToJSONArray(requestContent); if (requestArray.size() == 0) { return; } Session session = getSession(request, repositoryName, workspaceName); TreeSet<String> pathsInOrder = new TreeSet<>(); for (int i = 0; i < requestArray.size(); i++) { pathsInOrder.add(absPath(requestArray.get(i).toString())); } List<String> pathsInOrderList = new ArrayList<>(pathsInOrder); Collections.reverse(pathsInOrderList); for (String path : pathsInOrderList) { doDelete(path, session); } session.save(); }
From source file:org.apache.taverna.scufl2.translator.t2flow.defaultactivities.BeanshellActivityParser.java
@Override public Configuration parseConfiguration(T2FlowParser t2FlowParser, ConfigBean configBean, ParserState parserState) throws ReaderException { BeanshellConfig beanshellConfig = unmarshallConfig(t2FlowParser, configBean, "xstream", BeanshellConfig.class); Configuration configuration = new Configuration(); configuration.setParent(parserState.getCurrentProfile()); ObjectNode json = (ObjectNode) configuration.getJson(); configuration.setType(ACTIVITY_URI.resolve("#Config")); if (beanshellConfig.getLocalworkerName() != null) { URI localWorkerURI = LOCAL_WORKER_URI .resolve(uriTools.validFilename(beanshellConfig.getLocalworkerName())); /*// w w w.j a va 2 s . c o m * FIXME: As we can't read the annotation chain yet, we can't tell * whether this local worker has been edited or not, and so can't * use #definedBy */ json.put("derivedFrom", localWorkerURI.toString()); } String script = beanshellConfig.getScript(); json.put("script", script); ClassLoaderSharing classLoaderSharing = beanshellConfig.getClassLoaderSharing(); if (classLoaderSharing == ClassLoaderSharing.SYSTEM) json.put("classLoaderSharing", "system"); else { // default is "workflow" but don't need to be expressed // json.put("classLoaderSharing", "workflow"); } if (beanshellConfig.getLocalDependencies() != null) { ArrayNode dependencies = json.arrayNode(); for (String localDep : beanshellConfig.getLocalDependencies().getString()) dependencies.add(localDep); if (dependencies.size() > 0) json.put("localDependency", dependencies); } /* * Note: Maven Dependencies are not supported by Taverna 3 - only here * for informational purposes and potential t2flow->t2flow scenarios */ if (beanshellConfig.getArtifactDependencies() != null) { ArrayNode dependencies = json.arrayNode(); for (BasicArtifact mavenDep : beanshellConfig.getArtifactDependencies() .getNetSfTavernaRavenRepositoryBasicArtifact()) { ObjectNode mavenDependency = json.objectNode(); dependencies.add(mavenDependency); mavenDependency.put("groupId", mavenDep.getGroupId()); mavenDependency.put("artifactId", mavenDep.getArtifactId()); mavenDependency.put("version", mavenDep.getVersion()); } if (dependencies.size() > 0) json.put("mavenDependency", dependencies); } Activity activity = parserState.getCurrentActivity(); activity.getInputPorts().clear(); activity.getOutputPorts().clear(); for (ActivityPortDefinitionBean portBean : beanshellConfig.getInputs() .getNetSfTavernaT2WorkflowmodelProcessorActivityConfigActivityInputPortDefinitionBean()) parseAndAddInputPortDefinition(portBean, configuration, activity); for (ActivityPortDefinitionBean portBean : beanshellConfig.getOutputs() .getNetSfTavernaT2WorkflowmodelProcessorActivityConfigActivityOutputPortDefinitionBean()) parseAndAddOutputPortDefinition(portBean, configuration, activity); return configuration; }
From source file:com.basho.riak.client.core.operations.itest.ITestMapReduceOperation.java
private void testBasicMR(Namespace namespace) throws InterruptedException, ExecutionException, IOException { RiakObject obj = new RiakObject(); obj.setValue(BinaryValue.create("Alice was beginning to get very tired of sitting by her sister on the " + "bank, and of having nothing to do: once or twice she had peeped into the " + "book her sister was reading, but it had no pictures or conversations in " + "it, 'and what is the use of a book,' thought Alice 'without pictures or " + "conversation?'")); Location location = new Location(namespace, BinaryValue.unsafeCreate("p1".getBytes())); StoreOperation storeOp = new StoreOperation.Builder(location).withContent(obj).build(); cluster.execute(storeOp);/*from w ww . j av a 2s .com*/ storeOp.get(); obj.setValue(BinaryValue.create("So she was considering in her own mind (as well as she could, for the " + "hot day made her feel very sleepy and stupid), whether the pleasure " + "of making a daisy-chain would be worth the trouble of getting up and " + "picking the daisies, when suddenly a White Rabbit with pink eyes ran " + "close by her.")); location = new Location(namespace, BinaryValue.unsafeCreate("p2".getBytes())); storeOp = new StoreOperation.Builder(location).withContent(obj).build(); cluster.execute(storeOp); storeOp.get(); obj.setValue(BinaryValue.create("The rabbit-hole went straight on like a tunnel for some way, and then " + "dipped suddenly down, so suddenly that Alice had not a moment to think " + "about stopping herself before she found herself falling down a very deep " + "well.")); location = new Location(namespace, BinaryValue.unsafeCreate("p3".getBytes())); storeOp = new StoreOperation.Builder(location).withContent(obj).build(); cluster.execute(storeOp); storeOp.get(); String bName = namespace.getBucketNameAsString(); String bType = namespace.getBucketTypeAsString(); String query = "{\"inputs\":[[\"" + bName + "\",\"p1\",\"\",\"" + bType + "\"]," + "[\"" + bName + "\",\"p2\",\"\",\"" + bType + "\"]," + "[\"" + bName + "\",\"p3\",\"\",\"" + bType + "\"]]," + "\"query\":[{\"map\":{\"language\":\"javascript\",\"source\":\"" + "function(v) {var m = v.values[0].data.toLowerCase().match(/\\w*/g); var r = [];" + "for(var i in m) {if(m[i] != '') {var o = {};o[m[i]] = 1;r.push(o);}}return r;}" + "\"}},{\"reduce\":{\"language\":\"javascript\",\"source\":\"" + "function(v) {var r = {};for(var i in v) {for(var w in v[i]) {if(w in r) r[w] += v[i][w];" + "else r[w] = v[i][w];}}return [r];}\"}}]}"; MapReduceOperation mrOp = new MapReduceOperation.Builder(BinaryValue.unsafeCreate(query.getBytes())) .build(); cluster.execute(mrOp); mrOp.await(); assertTrue(mrOp.isSuccess()); ArrayNode resultList = mrOp.get().getResults().get(1); // The query should return one result which is a JSON array containing a // single JSON object that is a asSet of word counts. assertEquals(resultList.size(), 1); String json = resultList.get(0).toString(); ObjectMapper oMapper = new ObjectMapper(); @SuppressWarnings("unchecked") Map<String, Integer> resultMap = oMapper.readValue(json, Map.class); assertNotNull(resultMap.containsKey("the")); assertEquals(Integer.valueOf(8), resultMap.get("the")); resetAndEmptyBucket(namespace); }
From source file:org.flowable.admin.service.engine.ProcessInstanceService.java
public List<String> getCompletedActivityInstancesAndProcessDefinitionId(ServerConfig serverConfig, String processInstanceId) { URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_ACTIVITY_INSTANCE_LIST_URL); builder.addParameter("processInstanceId", processInstanceId); // builder.addParameter("finished", "true"); builder.addParameter("sort", "startTime"); builder.addParameter("order", "asc"); builder.addParameter("size", DEFAULT_ACTIVITY_SIZE); HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder)); JsonNode node = clientUtil.executeRequest(get, serverConfig); List<String> result = new ArrayList<String>(); if (node.has("data") && node.get("data").isArray()) { ArrayNode data = (ArrayNode) node.get("data"); ObjectNode activity = null;//from w w w.j ava 2s . c om for (int i = 0; i < data.size(); i++) { activity = (ObjectNode) data.get(i); if (activity.has("activityType")) { result.add(activity.get("activityId").asText()); } } } return result; }
From source file:org.pentaho.metaverse.impl.model.kettle.json.TransMetaJsonDeserializer.java
protected void deserializeVariables(TransMeta transMeta, JsonNode node, ObjectMapper mapper) throws IOException { ArrayNode varsArrayNode = (ArrayNode) node.get(TransMetaJsonSerializer.JSON_PROPERTY_VARIABLES); for (int i = 0; i < varsArrayNode.size(); i++) { JsonNode paramNode = varsArrayNode.get(i); ParamInfo param = mapper.readValue(paramNode.toString(), ParamInfo.class); transMeta.setVariable(param.getName(), param.getValue()); }/*from w ww.ja v a2s. c o m*/ }
From source file:org.pentaho.metaverse.impl.model.kettle.json.TransMetaJsonDeserializer.java
protected void deserializeHops(TransMeta transMeta, JsonNode root, ObjectMapper mapper) { ArrayNode hopsArray = (ArrayNode) root.get(TransMetaJsonSerializer.JSON_PROPERTY_HOPS); for (int i = 0; i < hopsArray.size(); i++) { JsonNode hopNode = hopsArray.get(i); try {// w w w .j a v a 2 s.c o m HopInfo hop = mapper.readValue(hopNode.toString(), HopInfo.class); if (hop != null) { TransHopMeta hopMeta = new TransHopMeta(); hopMeta.setFromStep(transMeta.findStep(hop.getFromStepName())); hopMeta.setToStep(transMeta.findStep(hop.getToStepName())); hopMeta.setEnabled(hop.isEnabled()); transMeta.addTransHop(hopMeta); } } catch (IOException e) { LOGGER.warn(Messages.getString("WARNING.Deserialization.Trans.Hops"), e); } } }