Java Code Examples for com.fasterxml.jackson.databind.node.ObjectNode#has()

The following examples show how to use com.fasterxml.jackson.databind.node.ObjectNode#has() . 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: ClassDelegate.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {
    if (CommandContextUtil.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
        ObjectNode taskElementProperties = BpmnOverrideContext.getBpmnOverrideElementProperties(serviceTaskId, execution.getProcessDefinitionId());
        if (taskElementProperties != null && taskElementProperties.has(DynamicBpmnConstants.SERVICE_TASK_CLASS_NAME)) {
            String overrideClassName = taskElementProperties.get(DynamicBpmnConstants.SERVICE_TASK_CLASS_NAME).asText();
            if (StringUtils.isNotEmpty(overrideClassName) && !overrideClassName.equals(className)) {
                className = overrideClassName;
                activityBehaviorInstance = null;
            }
        }
    }

    if (activityBehaviorInstance == null) {
        activityBehaviorInstance = getActivityBehaviorInstance();
    }

    try {
        activityBehaviorInstance.execute(execution);
    } catch (BpmnError error) {
        ErrorPropagation.propagateError(error, execution);
    } catch (RuntimeException e) {
        if (!ErrorPropagation.mapException(e, (ExecutionEntity) execution, mapExceptions))
            throw e;
    }
}
 
Example 2
Source File: ColumnToRowExpander.java    From samantha with MIT License 6 votes vote down vote up
public List<ObjectNode> expand(List<ObjectNode> initialResult,
                               RequestContext requestContext) {
    List<ObjectNode> expanded = new ArrayList<>();
    for (ObjectNode entity : initialResult) {
        List<ObjectNode> oneExpanded = new ArrayList<>();
        for (String colName : colNames) {
            if (entity.has(colName)) {
                ObjectNode newEntity = entity.deepCopy();
                newEntity.put(nameAttr, colName);
                newEntity.set(valueAttr, entity.get(colName));
                oneExpanded.add(newEntity);
            } else {
                logger.warn("The column {} is not present: {}", colName, entity.toString());
            }
        }
        if (oneExpanded.size() > 0) {
            expanded.addAll(oneExpanded);
        } else {
            expanded.add(entity);
        }
    }
    return expanded;
}
 
Example 3
Source File: Scrolling.java    From immutables with Apache License 2.0 6 votes vote down vote up
Flowable<T> scroll(ObjectNode query) {
  final Map<String, String> params = Collections.singletonMap("scroll", keepAlive.getSeconds() + "s");
  final boolean hasLimit = query.has("size");
  final long limit = hasLimit ? query.get("size").asLong() : Long.MAX_VALUE;

  if (scrollSize > limit) {
    // don't use scrolling when batch size is greater than limit
    return ops.search(query, converter);
  }

  // override size during scrolling
  query.put("size", scrollSize);

  return ops.searchRaw(query, params)
          .toFlowable()
          .scan(AccumulatedResult.empty(limit), AccumulatedResult::next)
          .skip(1)// skip first empty accumulator
          .compose(transformer())
          .map(AccumulatedResult::result)
          .flatMapIterable(r -> r.searchHits().hits())
          .compose(f -> hasLimit ? f.limit(limit) : f) // limit number of elements
          .map(hit -> converter.convert(hit.source()));
}
 
Example 4
Source File: SelfPlusOneRatioExpander.java    From samantha with MIT License 6 votes vote down vote up
public List<ObjectNode> expand(List<ObjectNode> initialResult,
                               RequestContext requestContext) {
    for (ObjectNode entity : initialResult) {
        for (int i=0; i<fieldNames.size(); i++) {
            String fieldName = fieldNames.get(i);
            if (entity.has(fieldName)) {
                double value = entity.get(fieldName).asDouble();
                SelfPlusOneRatioFunction func = new SelfPlusOneRatioFunction();
                value = func.value(value);
                if (newFieldNames != null && newFieldNames.size() == fieldNames.size()) {
                    entity.put(newFieldNames.get(i), value);
                } else if (appendix != null) {
                    entity.put(fieldName + appendix, value);
                } else {
                    entity.put(fieldName, value);
                }
            } else {
                logger.warn("The field {} is not present: {}", fieldName, entity.toString());
            }
        }
    }
    return initialResult;
}
 
Example 5
Source File: ConfigFile.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static void upgradeUiIfNeeded(ObjectNode configRootObjectNode) {
    JsonNode uiNode = configRootObjectNode.get("ui");
    if (uiNode == null || !uiNode.isObject()) {
        return;
    }
    ObjectNode uiObjectNode = (ObjectNode) uiNode;
    if (uiObjectNode.has("defaultDisplayedTransactionType")) {
        // upgrade from 0.9.28 to 0.10.0
        uiObjectNode.set("defaultTransactionType",
                uiObjectNode.remove("defaultDisplayedTransactionType"));
    }
    if (uiObjectNode.has("defaultDisplayedPercentiles")) {
        // upgrade from 0.9.28 to 0.10.0
        uiObjectNode.set("defaultPercentiles",
                uiObjectNode.remove("defaultDisplayedPercentiles"));
    }
    // upgrade from 0.10.12 to 0.11.0
    configRootObjectNode.set("uiDefaults", configRootObjectNode.remove("ui"));
}
 
Example 6
Source File: InventoryController.java    From servicecomb-saga-actuator with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "inventory", method = POST, consumes = APPLICATION_FORM_URLENCODED_VALUE, produces = TEXT_PLAIN_VALUE)
public ResponseEntity<String> dispatch(@RequestParam String response) {
  try {
    ObjectNode jsonNodes = objectMapper.readValue(response, ObjectNode.class);
    if (jsonNodes.has(CUSTOMER_ID)) {
      String customerId = jsonNodes.get(CUSTOMER_ID).textValue();

      stock--;
      if (isStockShort()) {
        // when no sagaChildren is provided, all child sub-transaction of inventory will be run
        return response(customerId, "");
      }

      // select no child sub-transaction to run next, by specifying none in sagaChildren
      return response(customerId,",  \"sagaChildren\": [\"none\"] \n");
    }
    return new ResponseEntity<>("Customer Id is missing", BAD_REQUEST);
  } catch (IOException e) {
    return new ResponseEntity<>(e.getMessage(), INTERNAL_SERVER_ERROR);
  }
}
 
Example 7
Source File: DynamicBpmnServiceImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void setElementProperty(String id, String propertyName, String propertyValue, ObjectNode infoNode) {
    ObjectNode bpmnNode = createOrGetBpmnNode(infoNode);
    if (!bpmnNode.has(id)) {
        bpmnNode.putObject(id);
    }

    ((ObjectNode) bpmnNode.get(id)).put(propertyName, propertyValue);
}
 
Example 8
Source File: DynamicBpmnServiceImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void setElementProperty(String id, String propertyName, JsonNode propertyValue, ObjectNode infoNode) {
    ObjectNode bpmnNode = createOrGetBpmnNode(infoNode);
    if (!bpmnNode.has(id)) {
        bpmnNode.putObject(id);
    }

    ((ObjectNode) bpmnNode.get(id)).set(propertyName, propertyValue);
}
 
Example 9
Source File: JsonQueryObjectModelConverter.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
private double checkFloat(ObjectNode node, String key) throws QueryException {
	if (!node.has(key)) {
		throw new QueryException("\"" + key + "\" not found on \"inBoundingBox\"");
	}
	JsonNode jsonNode = node.get(key);
	if (jsonNode.isNumber()) {
		return jsonNode.asDouble();
	} else {
		throw new QueryException("\"" + key + "\" should be of type number");
	}
}
 
Example 10
Source File: TBLTemplateController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
void processTestQuestion(String name, String questionText, String questionTitle, Integer questionDisplayOrder,
	Integer optionDisplayOrder, String optionText) {

    ObjectNode question = testQuestions.get(questionDisplayOrder);
    if (question == null) {
	question = JsonNodeFactory.instance.objectNode();
	question.set(RestTags.ANSWERS, JsonNodeFactory.instance.arrayNode());
	question.put(RestTags.DISPLAY_ORDER, questionDisplayOrder);
	testQuestions.put(questionDisplayOrder, question);
    }

    if (questionText != null) {
	question.put(RestTags.QUESTION_TEXT, questionText);
	// default title just in case - used for scratchie. Should be replaced with a user value
	if ( ! question.has(RestTags.QUESTION_TITLE) ) {
	    question.put(RestTags.QUESTION_TITLE, "Q" + questionDisplayOrder.toString()); 
	}
    }
    
    if (questionTitle != null) {
	question.put(RestTags.QUESTION_TITLE, questionTitle);
    }
    
    if (optionDisplayOrder != null && optionText != null) {
	ObjectNode newOption = JsonNodeFactory.instance.objectNode();
	newOption.put(RestTags.DISPLAY_ORDER, optionDisplayOrder);
	newOption.put(RestTags.CORRECT, false);
	newOption.put(RestTags.ANSWER_TEXT, optionText);
	((ArrayNode) question.get(RestTags.ANSWERS)).add(newOption);
    }

}
 
Example 11
Source File: DynamicBpmnServiceImpl.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected void setElementProperty(String id, String propertyName, String propertyValue, ObjectNode infoNode) {
  ObjectNode bpmnNode = createOrGetBpmnNode(infoNode);
  if (bpmnNode.has(id) == false) {
    bpmnNode.putObject(id);
  }
  
  ((ObjectNode) bpmnNode.get(id)).put(propertyName, propertyValue);
}
 
Example 12
Source File: DynamicBpmnServiceImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void setLocalizationProperty(String language, String id, String propertyName, String propertyValue, ObjectNode infoNode) {
    ObjectNode localizationNode = createOrGetLocalizationNode(infoNode);
    if (!localizationNode.has(language)) {
        localizationNode.set(language, processEngineConfiguration.getObjectMapper().createObjectNode());
    }

    ObjectNode languageNode = (ObjectNode) localizationNode.get(language);
    if (!languageNode.has(id)) {
        languageNode.set(id, processEngineConfiguration.getObjectMapper().createObjectNode());
    }

    ((ObjectNode) languageNode.get(id)).put(propertyName, propertyValue);
}
 
Example 13
Source File: JsonEventConventions.java    From tasmo with Apache License 2.0 5 votes vote down vote up
public boolean hasInstanceField(ObjectNode eventNode, String className, String fieldname) {
    ObjectNode objectNode = getInstanceNode(eventNode, className);
    if (objectNode != null) {
        return objectNode.has(fieldname);
    } else {
        return false;
    }
}
 
Example 14
Source File: DynamicBpmnServiceImpl.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected void setLocalizationProperty(String language, String id, String propertyName, String propertyValue, ObjectNode infoNode) {
  ObjectNode localizationNode = createOrGetLocalizationNode(infoNode);
  if (localizationNode.has(language) == false) {
    localizationNode.putObject(language);
  }
  
  ObjectNode languageNode = (ObjectNode) localizationNode.get(language);
  if (languageNode.has(id) == false) {
    languageNode.putObject(id);
  }
  
  ((ObjectNode) languageNode.get(id)).put(propertyName, propertyValue);
}
 
Example 15
Source File: ClassDelegate.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {
    ActivityExecution activityExecution = (ActivityExecution) execution;

    if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
        ObjectNode taskElementProperties = Context.getBpmnOverrideElementProperties(serviceTaskId, execution.getProcessDefinitionId());
        if (taskElementProperties != null && taskElementProperties.has(DynamicBpmnConstants.SERVICE_TASK_CLASS_NAME)) {
            String overrideClassName = taskElementProperties.get(DynamicBpmnConstants.SERVICE_TASK_CLASS_NAME).asText();
            if (StringUtils.isNotEmpty(overrideClassName) && !overrideClassName.equals(className)) {
                className = overrideClassName;
                activityBehaviorInstance = null;
            }
        }
    }

    if (activityBehaviorInstance == null) {
        activityBehaviorInstance = getActivityBehaviorInstance(activityExecution);
    }

    try {
        activityBehaviorInstance.execute(execution);
    } catch (BpmnError error) {
        ErrorPropagation.propagateError(error, activityExecution);
    } catch (RuntimeException e) {
        if (!ErrorPropagation.mapException(e, activityExecution, mapExceptions))
            throw e;
    }
}
 
Example 16
Source File: JsonNodeDeserializer.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
public Object deserializeJsonNode(JsonNode node) {
  if(node instanceof ObjectNode) {
    ObjectNode objectNode = (ObjectNode)node;
    if(objectNode.has(BsonNumberLongToLongDeserializer.NODE_KEY)) {
      // this is a number long.
      return objectNode.get(BsonNumberLongToLongDeserializer.NODE_KEY).asText();
    }
  }
  return null;
}
 
Example 17
Source File: KnnModelTrigger.java    From samantha with MIT License 5 votes vote down vote up
public List<ObjectNode> getTriggeredFeatures(List<ObjectNode> bases) {
    Object2DoubleMap<String> item2score = new Object2DoubleOpenHashMap<>();
    int numInter = 0;
    for (ObjectNode inter : bases) {
        double weight = 1.0;
        if (inter.has(weightAttr)) {
            weight = inter.get(weightAttr).asDouble();
        }
        String key = FeatureExtractorUtilities.composeConcatenatedKey(inter, feaAttrs);
        if (weight >= 0.5 && featureKnnModel != null) {
            getNeighbors(item2score, featureKnnModel, key, weight);
        }
        if (weight < 0.5 && featureKdnModel != null) {
            getNeighbors(item2score, featureKdnModel, key, weight);
        }
        numInter++;
        if (numInter >= maxInter) {
            break;
        }
    }
    List<ObjectNode> results = new ArrayList<>();
    for (Map.Entry<String, Double> entry : item2score.entrySet()) {
        ObjectNode entity = Json.newObject();
        Map<String, String> attrVals = FeatureExtractorUtilities.decomposeKey(entry.getKey());
        for (Map.Entry<String, String> ent : attrVals.entrySet()) {
            entity.put(ent.getKey(), ent.getValue());
        }
        entity.put(scoreAttr, entry.getValue());
        results.add(entity);
    }
    results.sort(SortingUtilities.jsonFieldReverseComparator(scoreAttr));
    return results;
}
 
Example 18
Source File: OAuthServiceImpl.java    From BIMserver with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public String getRemoteToken(Long soid, String code, Long serverId) throws ServerException, UserException {
	try (DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.READ_ONLY)) {
		NewService newService = session.get(soid, OldQuery.getDefault());
		ObjectNode objectNode = OBJECT_MAPPER.createObjectNode();
		objectNode.put("grant_type", "authorization_code");
		objectNode.put("code", code);
		OAuthServer oAuthServer = session.get(serverId, OldQuery.getDefault());
		objectNode.put("client_id", oAuthServer.getClientId());
		objectNode.put("client_secret", oAuthServer.getClientSecret());
		
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost post = new HttpPost(newService.getTokenUrl());
			post.setHeader("Content-Type", "application/x-www-form-urlencoded");
			List <NameValuePair> nvps = new ArrayList <NameValuePair>();
			nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
			nvps.add(new BasicNameValuePair("code", code));
			nvps.add(new BasicNameValuePair("client_id", oAuthServer.getClientId()));
			nvps.add(new BasicNameValuePair("client_secret", oAuthServer.getClientSecret()));
			nvps.add(new BasicNameValuePair("redirect_uri", "crap"));
			post.setEntity(new UrlEncodedFormEntity(nvps));
			CloseableHttpResponse httpResponse = httpclient.execute(post);
			ObjectNode response = OBJECT_MAPPER.readValue(httpResponse.getEntity().getContent(), ObjectNode.class);
			
			if (response.has("access_token")) {
				String accessToken = response.get("access_token").asText();
				newService.setAccessToken(accessToken);
				newService.setStatus(ServiceStatus.AUTHENTICATED);
				newService.setResourceUrl(response.get("resource_url").asText());
				session.store(newService);
				session.commit();
				
				return accessToken;
			} else {
				throw new UserException("No access_token received from oauth server");
			}
		} finally {
		    httpclient.close();
		}
	} catch (Exception e) {
		return handleException(e);
	}
}
 
Example 19
Source File: JsonRpcClient.java    From jsonrpc4j with MIT License 4 votes vote down vote up
protected boolean hasError(ObjectNode jsonObject) {
	return jsonObject.has(ERROR) && jsonObject.get(ERROR) != null && !jsonObject.get(ERROR).isNull();
}
 
Example 20
Source File: ActionProcessor.java    From syndesis with Apache License 2.0 4 votes vote down vote up
/**
 * Add action properties to the global properties.
 */
private void addActionProperties(ObjectNode root, Element element) throws InvocationTargetException, IllegalAccessException {

    Annotation[] annotations = element.getAnnotationsByType(propertyAnnotationClass);
    for (int i = 0; i < annotations.length; i++) {
        Annotation annotation = annotations[i];
        ObjectNode propertyNode = mapper.createObjectNode();

        gatherProperties(propertyNode, annotation);

        if (element.getKind() == ElementKind.FIELD) {
            VariableElement field = (VariableElement)element;

            TypeMirror typeMirror = field.asType();
            TypeElement typeElement = processingEnv.getElementUtils().getTypeElement(typeMirror.toString());
            String javaType = typeMirror.toString();
            String type = propertyNode.get("type").asText();

            final boolean doesntHaveEnums = !propertyNode.has("enums");
            final boolean typeIsEnum = typeElement != null && typeElement.getKind() == ElementKind.ENUM;
            if (doesntHaveEnums && typeIsEnum) {
                // don't auto detect enum if enums are set through
                // annotations
                for (Element enumElement : typeElement.getEnclosedElements()) {
                    if (enumElement.getKind() == ElementKind.ENUM_CONSTANT) {
                        ObjectNode enumNode = mapper.createObjectNode();

                        writeIfNotEmpty(enumNode, "label", enumElement.toString());
                        writeIfNotEmpty(enumNode, "value", enumElement.toString());

                        propertyNode.withArray("enums").add(enumNode);
                    }
                }

                javaType = String.class.getName();
                type = String.class.getName();
            }

            if (type == null || "".equals(type.trim())){
                if (String.class.getName().equals(type)) {
                    type = "string";
                } else if (Boolean.class.getName().equals(type)) {
                    type = "boolean";
                } else if (Integer.class.getName().equals(type)) {
                    type = "int";
                } else if (Float.class.getName().equals(type)) {
                    type = "float";
                } else if (Double.class.getName().equals(type)) {
                    type = "double";
                }
            }

            writeIfNotEmpty(propertyNode, "javaType", javaType);
            writeIfNotEmpty(propertyNode, "type", type);
        }

        root.withArray("properties").add(propertyNode);
    }
}