Java Code Examples for org.codehaus.jackson.JsonNode#get()

The following examples show how to use org.codehaus.jackson.JsonNode#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StencilsetServiceImpl.java    From fixflow with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化处理命令类型
 * @param rootNode
 */
private void initTaskCommandType(JsonNode rootNode){
	 ArrayNode baseNodeArray = (ArrayNode)rootNode.get("propertyPackages");
        JsonNode commandInfoBase = JsonConverterUtil.getChildElementByProperty("commandinfobase", "name", baseNodeArray);
        commandInfoBase = commandInfoBase.get("properties").get(0);
        ArrayNode complexItemsNode =(ArrayNode)commandInfoBase.get("complexItems");
        JsonNode commandType = JsonConverterUtil.getChildElementByProperty("commandtype", "id", complexItemsNode);
        ArrayNode arrayNode = objectMapper.createArrayNode();
        TaskCommandConfig  taskCommandConfig = ProcessEngineManagement.getDefaultProcessEngine().getProcessEngineConfiguration().getTaskCommandConfig();
        List<TaskCommandDef> commandDefs = taskCommandConfig.getTaskCommandDef();
        for(TaskCommandDef taskCommandDef :commandDefs){
        	 ObjectNode typeNode = objectMapper.createObjectNode();
        	 if(StringUtil.getBoolean(taskCommandDef.getIsEnabled())&& !"system".equals(taskCommandDef.getType())){
        		 typeNode.put("id",taskCommandDef.getId());
                typeNode.put("title", taskCommandDef.getName());
                typeNode.put("value", taskCommandDef.getId());
                typeNode.put("refToView", "");
                arrayNode.add(typeNode);
        	 }
        }
        ((ObjectNode)commandType).put("items", arrayNode);
}
 
Example 2
Source File: JobExecutor.java    From Cubert with Apache License 2.0 6 votes vote down vote up
protected void setOutput() throws IOException
{
    JsonNode output = get(root, "output");
    JsonNode params = output.get("params");
    if (params == null)
        params = mapper.createObjectNode();

    Path outputPath = new Path(getText(output, "path"));
    FileOutputFormat.setOutputPath(job, outputPath);

    if (params.has("overwrite") && Boolean.parseBoolean(getText(params, "overwrite")))
    {
        fs.delete(outputPath, true);
    }

    BlockSchema schema = new BlockSchema(output.get("schema"));

    Storage storage = StorageFactory.get(getText(output, "type"));
    storage.prepareOutput(job, conf, params, schema, outputPath);
}
 
Example 3
Source File: FlowRestfulApi.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/updateFlowBaseInfo")
public Response updateFlowBaseInfo(@Context HttpServletRequest req, JsonNode json) throws DSSErrorException {
    Long flowID = json.get("id").getLongValue();
    String name = json.get("name")==null?null:json.get("name").getTextValue();
    String description = json.get("description") == null?null:json.get("description").getTextValue();
    Long taxonomyID = json.get("taxonomyID") == null?null:json.get("taxonomyID").getLongValue();
    Long projectVersionID = json.get("projectVersionID").getLongValue();
    String uses = json.get("uses") == null?null:json.get("uses").getTextValue();
    publishManager.checkeIsPublishing(projectVersionID);
    // TODO: 2019/6/13  projectVersionID的更新校验
    //这里可以不做事务
    DWSFlow dwsFlow = new DWSFlow();
    dwsFlow.setId(flowID);
    dwsFlow.setName(name);
    dwsFlow.setDescription(description);
    dwsFlow.setUses(uses);
    flowService.updateFlowBaseInfo(dwsFlow,projectVersionID,taxonomyID);
    return Message.messageToResponse(Message.ok());
}
 
Example 4
Source File: GenerateOperator.java    From Cubert with Apache License 2.0 6 votes vote down vote up
private static BlockSchema buildFunctionTree(FunctionTree tree, JsonNode json) throws PreconditionException
{
    int numOutputColumns = json.size();
    ColumnType[] outputTypes = new ColumnType[numOutputColumns];

    for (int i = 0; i < numOutputColumns; i++)
    {
        JsonNode outputColJson = json.get(i);
        String colName = JsonUtils.getText(outputColJson, "col_name");
        tree.addFunctionTree(outputColJson.get("expression"));

        ColumnType type = tree.getType(i);
        ColumnType copy = new ColumnType(colName, type.getType());
        copy.setColumnSchema(type.getColumnSchema());
        outputTypes[i] = copy;
    }

    return new BlockSchema(outputTypes);
}
 
Example 5
Source File: ForceSortedOrder.java    From Cubert with Apache License 2.0 6 votes vote down vote up
@Override
public PostCondition getPostCondition(Map<String, PostCondition> preConditions,
                                      JsonNode json) throws PreconditionException
{
    PostCondition condition = preConditions.values().iterator().next();

    JsonNode args = json.get("args");

    if (args == null || !args.has("sortKeys"))
        throw new PreconditionException(PreconditionExceptionType.INVALID_CONFIG,
                                        "Missing 'sortKeys' parameter");

    String[] sortKeys = JsonUtils.getText(args, "sortKeys").split(",");

    return new PostCondition(condition.getSchema(),
                             condition.getPartitionKeys(),
                             sortKeys);
}
 
Example 6
Source File: VespaDocumentOperationTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
private JsonNode setupSimpleArrayOperation(String name, String[] array, String... params) throws IOException {
    Schema schema = new Schema();
    Tuple tuple = TupleFactory.getInstance().newTuple();

    DataBag bag = new SortedDataBag(null);
    for (String s : array) {
        Tuple stringTuple = TupleFactory.getInstance().newTuple();
        stringTuple.append(s);
        bag.add(stringTuple);
    }
    addToTuple(name, DataType.BAG, bag, schema, tuple);

    VespaDocumentOperation docOp = new VespaDocumentOperation(params);
    docOp.setInputSchema(schema);
    String json = docOp.exec(tuple);

    ObjectMapper m = new ObjectMapper();
    JsonNode root = m.readTree(json);
    JsonNode fields = root.get("fields");
    return fields.get(name);
}
 
Example 7
Source File: VaultoroExchange.java    From libdynticker with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected List<Pair> getPairsFromAPI() throws IOException {
	List<Pair> pairs = new ArrayList<Pair>();
	JsonNode node = readJsonFromUrl("https://api.vaultoro.com/markets");
	if(node.get("status").asText().equals("success")) {
		JsonNode data = node.get("data");
		pairs.add(new Pair(data.get("MarketCurrency").asText(), data.get("BaseCurrency").asText()));
	} else
		throw new IOException(node.get("status").asText());
	return pairs;
}
 
Example 8
Source File: RubixBlockWriter.java    From Cubert with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(JsonNode json) throws JsonParseException,
        JsonMappingException,
        IOException
{
    outputSchema = new BlockSchema(json.get("schema"));
}
 
Example 9
Source File: JsonUtil.java    From hbase-indexer with Apache License 2.0 5 votes vote down vote up
public static long getLong(JsonNode node, String prop) throws JsonFormatException {
    if (node.get(prop) == null) {
        throw new JsonFormatException("Missing required property: " + prop);
    }
    if (!node.get(prop).isLong() && !node.get(prop).isInt()) {
        throw new JsonFormatException("Not an long property: " + prop);
    }
    return node.get(prop).getLongValue();
}
 
Example 10
Source File: JsonUtil.java    From hbase-indexer with Apache License 2.0 5 votes vote down vote up
public static ArrayNode getArray(JsonNode node, String prop) throws JsonFormatException {
    if (node.get(prop) == null) {
        throw new JsonFormatException("Missing required property: " + prop);
    }
    if (!node.get(prop).isArray()) {
        throw new JsonFormatException("Not an array property: " + prop);
    }
    return (ArrayNode) node.get(prop);
}
 
Example 11
Source File: JSONRPCParser.java    From bitcoin-transaction-explorer with MIT License 5 votes vote down vote up
public static ArrayList<String> getTransactionList(final InputStream jsonData) throws JsonProcessingException, IOException {
  final JsonNode tree = getResultNode(jsonData);

  // Array of txs
  final ArrayList<String> txs = new ArrayList<>();
  final JsonNode txNode = tree.get("tx");
  for (int i = 0; i < txNode.size(); i++) {
    txs.add(txNode.get(i).getTextValue());
  }

  return txs;
}
 
Example 12
Source File: BittrexExchange.java    From libdynticker with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected List<Pair> getPairsFromAPI() throws IOException {
	List<Pair> pairs = new ArrayList<Pair>();
	JsonNode node = readJsonFromUrl("https://bittrex.com/api/v1.1/public/getmarkets");
	if(node.get("success").asBoolean()) {
		for(JsonNode market : node.get("result")) {
			if(market.get("IsActive").asBoolean()) {
				pairs.add(new Pair(market.get("MarketCurrency").asText(), market.get("BaseCurrency").asText()));
			}
		}
	} else
		throw new IOException(node.get("message").asText());
	return pairs;
}
 
Example 13
Source File: JsonUtils.java    From urule with Apache License 2.0 5 votes vote down vote up
public static Value parseValue(JsonNode node){
	JsonNode valueNode=node.get("value");
	if(valueNode==null){
		return null;
	}
	return parseValueNode(valueNode);
}
 
Example 14
Source File: CounterMetricHandler.java    From kardio with Apache License 2.0 5 votes vote down vote up
protected float getMetricValue(CounterDetailVO counterDetails)
		throws IOException {
	String prometheusUrl = counterDetails.getParameter1();
   	String query = counterDetails.getParameter2();

   	String prometheusResponse = RestCommunicationHandler.getResponse(
   			prometheusUrl + URLEncoder.encode(query, "UTF-8") , false, null, null);
   	
   	ObjectMapper mapper = new ObjectMapper();
       JsonNode rootNode = mapper.readTree(prometheusResponse);
       if(rootNode.get("status") == null || !rootNode.get("status").getTextValue().equalsIgnoreCase("success")){
       	getLogger().error("Prometheus : Status Check Failed. Environment Counter Id = " + counterDetails.getEnvironmentCounterId() );
       	getLogger().error("Prometheus Response : \n" + prometheusResponse);
       	throw new GeneralException("Prometheus : Status Check Failed. Environment Counter Id = " + counterDetails.getEnvironmentCounterId());
       }
       if(rootNode.get("data") == null
       		|| rootNode.get("data").get("result") == null
       		|| !rootNode.get("data").get("result").isArray()){
       	getLogger().error("/data/result Node is missing in prometheus response. Environment Counter Id = " + counterDetails.getEnvironmentCounterId() );
       	getLogger().error("Prometheus Response : \n" + prometheusResponse);
       	throw new GeneralException("/data/result Node is missing in prometheus response. Environment Counter Id = " + counterDetails.getEnvironmentCounterId());
       }
       
       JsonNode valuesNode = null;
       for (final JsonNode arrayNode : rootNode.get("data").get("result")) {
       	valuesNode = arrayNode.get("value");
       }
       if(valuesNode == null){
       	getLogger().error("/data/result/values Node is missing in prometheus response. Environment Counter Id = " + counterDetails.getEnvironmentCounterId() );
       	getLogger().error("Prometheus Response : \n" + prometheusResponse);
       	throw new GeneralException("Number of Trasaction in prometheus response is 0. "
       			+ "Environment Counter Id = " + counterDetails.getEnvironmentCounterId()
       			+ "Environment Id = " + counterDetails.getEnvironmentId());
       }
       
       float metricValue = Float.parseFloat(valuesNode.get(1).getTextValue());
       return metricValue;
}
 
Example 15
Source File: SemanticAnalyzer.java    From Cubert with Apache License 2.0 5 votes vote down vote up
@Override
public void enterProgram(JsonNode json)
{
    if (json.has("input") && !json.get("input").isNull())
    {
        JsonNode programInput = json.get("input");
        Iterator<String> it = programInput.getFieldNames();
        while (it.hasNext())
        {
            String input = it.next();
            JsonNode inputJson = programInput.get(input);

            BlockSchema schema = new BlockSchema(inputJson.get("schema"));

            PostCondition condition = null;

            if (inputJson.has("partitionKeys") && inputJson.has("sortKeys"))
                condition =
                        new PostCondition(schema,
                                          JsonUtils.asArray(inputJson.get("partitionKeys")),
                                          JsonUtils.asArray(inputJson.get("sortKeys")));
            else
                condition = new PostCondition(schema, null, null);
            datasetConditions.put(input, condition);
        }
    }
}
 
Example 16
Source File: KubernetesBackUpTask.java    From kardio with Apache License 2.0 5 votes vote down vote up
/**
 * This function returns a Map with key as service name and value as Map with all selector values
 * @param authToken
 * @param eVo
 * @return
 * @throws Exception
 */
private static Map<String, Map<String, String>> getServiceLabelValues(String authToken, EnvironmentVO eVo) throws Exception {
	// TODO Auto-generated method stub
	String serviceApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_SERVICE_PATH);
	String serviceJson = RestCommunicationHandler.getResponse(serviceApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode rootNodeServ = mapper.readTree(serviceJson);
	ArrayNode serviceNode = (ArrayNode) rootNodeServ.get("items");
	if(serviceNode == null || serviceNode.size() == 0){
		logger.info("No Service is available for the environment : "+eVo.getEnvironmentName());
		return null;
	}
	Map<String, Map<String, String>> serviceLabelMap = new HashMap<String, Map<String, String>>(); 
	Iterator<JsonNode> serviceIterator = serviceNode.getElements();
	while (serviceIterator.hasNext()) {
		JsonNode appsInNode = serviceIterator.next();
		JsonNode servMetadataNode = appsInNode.get("metadata");
		JsonNode servNameNode = servMetadataNode.get("name");
		String serviceName = servNameNode.getValueAsText();
		JsonNode namespaceNode = servMetadataNode.get("namespace");
		String namespace = namespaceNode.getValueAsText();
		JsonNode specNode = appsInNode.get("spec");
		JsonNode selectorNode = specNode.get("selector");
		if (namespace.equals("default") || !namespace.contains("-")) {
			logger.info("Excluding service - " + serviceName + " in the namespace - " + namespace);
			continue;
		}
		Map<String, String> selectorMap = mapper.convertValue(selectorNode, Map.class);
		serviceLabelMap.put(namespace+"/"+serviceName, selectorMap);
	}
	return serviceLabelMap;
}
 
Example 17
Source File: LineageHelper.java    From Cubert with Apache License 2.0 5 votes vote down vote up
public boolean isOutputOf(ObjectNode candidateOp, String inputRelation)
{
    Pair<ObjectNode, JsonNode> jobPhase = this.getJobPhase(candidateOp);
    JsonNode phaseNode = jobPhase.getSecond();
    String outRelation =
            getOperatorOutput(jobPhase.getFirst(), phaseNode, candidateOp);
    if (outRelation != null && outRelation.equals(inputRelation))
        return true;

    // if this is an INPUT load, then match against "input"
    if (!isReducePhase(phaseNode) && phaseNode.get("input") == candidateOp
            && candidateOp.get("name").getTextValue().equals(inputRelation))
        return true;
    return false;
}
 
Example 18
Source File: KubernetesBackUpTask.java    From kardio with Apache License 2.0 5 votes vote down vote up
/**
 * This function returns the Health check url for the service
 * @param ingressNode
 * @param healthCheckPort
 * @param pathValue
 * @return
 */
private static String getHealthCheckUrl(JsonNode ingressNode, String healthCheckPort, String pathValue) {
	// TODO Auto-generated method stub
	 JsonNode metadataNode = ingressNode.get("metadata");
     JsonNode annotNode = metadataNode.get("annotations");
     JsonNode namespaceNode = metadataNode.get("namespace");
     JsonNode nameNode = metadataNode.get("name");
     String ingressName = nameNode.asText();
     String namespace = namespaceNode.asText();
     /*The below block of code is for checking path based routing
      *CASE:: We are using nginx controller,below is the logic to find the app is using path based routing or not
      * If the "nginx.ingress.kubernetes.io/rewrite-target" is present in the annotation then app has path based routing */
     boolean isPathNeeded = false;
     String schemeValue = null;
        if(annotNode == null){
        	logger.info("The annotations node is null for the Ingress - "+ingressName+" in the namespace - "+ namespace);
        	isPathNeeded = false;
        }else{
        	isPathNeeded = annotNode.get("nginx.ingress.kubernetes.io/rewrite-target") == null? false : true;
        	schemeValue = annotNode.get("nginx.ingress.kubernetes.io/ssl-passthrough") == null ? null : "https";
        }
        
        JsonNode specIngNode = ingressNode.get("spec");
    	 JsonNode tlsNode = specIngNode.get("tls");
    	 if(schemeValue == null){
     		schemeValue = tlsNode == null ? "http" : "https";
     	 }
    	 String hostUrlPath = null;
        hostUrlPath =  getHostUrlAndPath(specIngNode, healthCheckPort, isPathNeeded);
        if(hostUrlPath == null){
       	 return null;
        }
	return schemeValue+ "://" + hostUrlPath + pathValue;
}
 
Example 19
Source File: FlattenBagOperator.java    From Cubert with Apache License 2.0 5 votes vote down vote up
private void init(JsonNode operatorJson, BlockSchema inputSchema)
{
    JsonNode exprListNode = operatorJson.get("genExpressions");
    Iterator<JsonNode> it = exprListNode.getElements();
    while (it.hasNext())
    {
        JsonNode e = it.next();
        String colName = e.get("col").getTextValue();
        int columnId = inputSchema.getIndex(colName);
        flattenColumnNameSet.add(colName);
        columnIndexArray.add(columnId);

        JsonNode flattenNode = e.get("flatten");
        if (flattenNode != null)
        {
            String ftypestr = flattenNode.getTextValue();

            flattenPositions.put(inputSchema.getIndex(colName),
                                 FlattenType.fromString(ftypestr));
            // System.out.println("Flatten column  =" + colName + " position = " +
            // inputSchema.getIndex(colName) + " type= " + ftypestr);

            odometerIterators.add(null);

            // out put column definitions:
            List<ColumnType> outputColumTypeList = new ArrayList<ColumnType>();
            outputColumnTypeMap.put(colName, outputColumTypeList);
            JsonNode outputNode = e.get("output");
            for (JsonNode j : outputNode)
            {
                String outColName = j.get("col").getTextValue();
                DataType outType = DataType.valueOf(j.get("type").getTextValue());
                outputColumTypeList.add(new ColumnType(outColName, outType));
            }

        }
    }

    this.outSchema = generateOutSchema(inputSchema);
}
 
Example 20
Source File: DerpTest.java    From torrenttunes-client with GNU General Public License v3.0 4 votes vote down vote up
public void testDerp7() {
	
	Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
	
	String json = Tools.readFile(DataSources.STRINGS_FR_LOCATION());
	
	JsonNode node = Tools.jsonToNode(json);
	
	Map<String, String> innerMap = new HashMap<String, String>();
	
	// Iterate over all the string fields
	JsonNode s = node.get("strings");
	
	Iterator<Entry<String, JsonNode>> sIt = s.getFields();
	while (sIt.hasNext()) {
		Entry<String, JsonNode> e = sIt.next();
		
		innerMap.put(e.getKey(), e.getValue().asText());
		
		log.info(e.getValue().asText());
	}
	
	map.put("strings", innerMap);
	
	
}