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

The following examples show how to use com.fasterxml.jackson.databind.node.ObjectNode#remove() . 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: AdditionalPropertiesDeserializer.java    From botbuilder-java with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    ObjectNode root = mapper.readTree(jp);
    ObjectNode copy = root.deepCopy();

    // compare top level fields and keep only missing fields
    final Class<?> tClass = this.defaultDeserializer.handledType();
    for (Class<?> c : TypeToken.of(tClass).getTypes().classes().rawTypes()) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            JsonProperty property = field.getAnnotation(JsonProperty.class);
            String key = property.value().split("((?<!\\\\))\\.")[0];
            if (!key.isEmpty() && copy.has(key)) {
                copy.remove(key);
            }
        }
    }

    // put into additional properties
    root.put("additionalProperties", copy);

    JsonParser parser = new JsonFactory().createParser(root.toString());
    parser.nextToken();
    return defaultDeserializer.deserialize(parser, ctxt);
}
 
Example 2
Source File: OutboundProfileHandler.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
@Override
public JsonNode handleProperty(IAPI desired, IAPI actual, JsonNode response) throws AppException {
	ObjectMapper objectMapper = new ObjectMapper();
	validateAuthenticationProfiles(desired);
	APIManagerAdapter.getInstance().translateMethodIds(desired.getOutboundProfiles(), actual);
	if(desired.getOutboundProfiles().size()!=0) {
		((ObjectNode)response).replace("outboundProfiles", objectMapper.valueToTree(desired.getOutboundProfiles()));
	}
	if(!APIManagerAdapter.hasAPIManagerVersion("7.6.2")){ // Versions before 7.6.2 don't support a FaultHandlerPolicy
		JsonNode outboundProfiles = response.get("outboundProfiles");
		if (outboundProfiles instanceof ObjectNode) {
			Iterator<JsonNode> it = outboundProfiles.elements();
			while(it.hasNext()) {
				ObjectNode profile = (ObjectNode)it.next();
				profile.remove("faultHandlerPolicy");
			}
	    }
	}
	return response;
}
 
Example 3
Source File: PrintingController.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void removeNulls(JsonNode tree) {
	if (tree instanceof ArrayNode) {
		ArrayNode array = (ArrayNode) tree;
		for (int i = array.size() - 1; i >= 0; i--) {
			if (array.get(i).isNull()) {
				array.remove(i);
			} else {
				removeNulls(array.get(i));
			}
		}
	} else if (tree instanceof ObjectNode) {
		ObjectNode object = (ObjectNode) tree;
		Set<String> nulls = new HashSet<String>();
		for (Iterator<String> it = object.fieldNames(); it.hasNext();) {
			String name = it.next();
			if (object.get(name).isNull()) {
				nulls.add(name);
			} else {
				removeNulls(object.get(name));
			}
		}
		object.remove(nulls);
	}
}
 
Example 4
Source File: ModelsResource.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected void internalDeleteNodeByNameFromBPMNModel(JsonNode editorJsonNode, String propertyName) {
  JsonNode childShapesNode = editorJsonNode.get("childShapes");
  if (childShapesNode != null && childShapesNode.isArray()) {
    ArrayNode childShapesArrayNode = (ArrayNode) childShapesNode;
    for (JsonNode childShapeNode : childShapesArrayNode) {
      // Properties
      ObjectNode properties = (ObjectNode) childShapeNode.get("properties");
      if (properties != null && properties.has(propertyName)) {
        JsonNode propertyNode = properties.get(propertyName);
        if (propertyNode != null) {
          properties.remove(propertyName);
        }
      }

      // Potential nested child shapes
      if (childShapeNode.has("childShapes")) {
        internalDeleteNodeByNameFromBPMNModel(childShapeNode, propertyName);
      }

    }
  }
}
 
Example 5
Source File: ElasticsearchOps.java    From immutables with Apache License 2.0 5 votes vote down vote up
private Single<WriteResult> insertBulkInternal(List<ObjectNode> documents) throws JsonProcessingException {
  Objects.requireNonNull(documents, "documents");

  if (documents.isEmpty()) {
    // nothing to process
    return Single.just(WriteResult.empty());
  }

  final List<String> bulk = new ArrayList<>(documents.size() * 2);
  for (ObjectNode doc: documents) {
    final ObjectNode header = mapper.createObjectNode();
    header.with("index").put("_index", index);
    if (doc.has("_id")) {
      // check if document has already an _id
      header.with("index").set("_id", doc.get("_id"));
      doc.remove("_id");
    }

    bulk.add(header.toString());
    bulk.add(mapper().writeValueAsString(doc));
  }

  final StringEntity entity = new StringEntity(String.join("\n", bulk) + "\n",
          ContentType.APPLICATION_JSON);

  final Request r = new Request("POST", "/_bulk?refresh");
  r.setEntity(entity);
  return transport.execute(r).map(x -> WriteResult.unknown());
}
 
Example 6
Source File: ForUpdateCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void clearBaseFields(final ObjectNode node) {
    node.remove("attributes");
    node.remove("Id");
    node.remove("IsDeleted");
    node.remove("CreatedDate");
    node.remove("CreatedById");
    node.remove("LastModifiedDate");
    node.remove("LastModifiedById");
    node.remove("SystemModstamp");
    node.remove("LastActivityDate");
}
 
Example 7
Source File: PubsubMessageToObjectNode.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Recursively descend into the fields of the passed map and compare to the passed BQ schema,
 * while modifying the structure to accommodate map types, nested arrays, etc.
 *
 * @param parent the map object to inspect and transform
 * @param bqFields the list of expected BQ fields inside this object
 * @param additionalProperties a map for storing fields absent in the BQ schema; if null, this
 *                             is "strict schema" mode and additional properties will be dropped
 */
@VisibleForTesting
void transformForBqSchema(ObjectNode parent, List<Field> bqFields,
    ObjectNode additionalProperties) {
  final Map<String, Field> bqFieldMap = bqFields.stream()
      .collect(Collectors.toMap(Field::getName, Function.identity()));

  for (String jsonFieldName : Lists.newArrayList(parent.fieldNames())) {
    final JsonNode value = parent.get(jsonFieldName);

    final String bqFieldName;
    if (bqFieldMap.containsKey(jsonFieldName)) {
      // The JSON field name already matches a BQ field.
      bqFieldName = jsonFieldName;
    } else {
      // Remove the json field from the parent because it does not match the BQ field name.
      parent.remove(jsonFieldName);

      // Try cleaning the name to match our BQ conventions.
      bqFieldName = getAndCacheBqName(jsonFieldName);
    }

    // If the field name matches a BQ field name, we process it and add it to the parent,
    // otherwise we add it to additionalProperties without renaming.
    if (bqFieldMap.containsKey(bqFieldName)) {
      processField(jsonFieldName, bqFieldMap.get(bqFieldName), value, parent,
          additionalProperties);
    } else if (additionalProperties != null) {
      additionalProperties.set(jsonFieldName, value);
    }
  }
}
 
Example 8
Source File: JsonNodeSupport.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
public static Boolean removeBoolean(ObjectNode json, String field) {
    JsonNode value = json.remove(field);
    if( value==null ) {
        return null;
    }
    if( value.isNull() ) {
        return null;
    }
    return value.asBoolean();
}
 
Example 9
Source File: Version122FinalMigrator.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.apiman.manager.api.migrator.IVersionMigrator#migrateOrg(com.fasterxml.jackson.databind.node.ObjectNode)
 */
@Override
public void migrateOrg(ObjectNode node) {
    ArrayNode clients = (ArrayNode) node.get("Clients"); //$NON-NLS-1$
    if (clients != null && clients.size() > 0) {
        for (JsonNode clientNode : clients) {
            ObjectNode client = (ObjectNode) clientNode;
            ArrayNode versions = (ArrayNode) client.get("Versions"); //$NON-NLS-1$
            if (versions != null && versions.size() > 0) {
                for (JsonNode versionNode : versions) {
                    ObjectNode version = (ObjectNode) versionNode;
                    
                    ObjectNode clientVersionBean = (ObjectNode) version.get("ClientVersionBean"); //$NON-NLS-1$
                    clientVersionBean.put("apikey", keyGenerator.generate()); //$NON-NLS-1$
                    
                    ArrayNode contracts = (ArrayNode) version.get("Contracts"); //$NON-NLS-1$
                    if (contracts != null && contracts.size() > 0) {
                        for (JsonNode contractNode : contracts) {
                            ObjectNode contract = (ObjectNode) contractNode;
                            contract.remove("apikey"); //$NON-NLS-1$
                        }
                    }
                }
            }
        }
    }
    
}
 
Example 10
Source File: C1X.java    From bidder with Apache License 2.0 5 votes vote down vote up
/**
 * Process special C1X stuff, sets the exchange name. Sets encoding.
 */
@Override
public boolean parseSpecial() {
        setExchange( "c1x" );
        usesEncodedAdm = false;

        if (rootNode == null)       // can happen on initialization of the template class
        	return false;
        
        // C1x can have protocol marker in the domain, need to strip it
        if (siteDomain != null) {
        	siteDomain = siteDomain.replaceAll("http://", "");
        	siteDomain = siteDomain.replaceAll("https://", "");
        	JsonNode node = rootNode.get("site");
        	if (node == null)
        		node = rootNode.get("app");
        	if (node.has("domain")) {
        		ObjectNode n = (ObjectNode)node;
        		n.remove("domain");
        		n.put("domain", siteDomain);
        	}
        }
        
        // C1X uses ISO2 country codes, we can't digest that with our campaign processor, so we
        // will convert it for them and patch the bid request.
        // Use a cache of country codes to keep from creating a lot of objects to be later garbage collected.
        normalizeCountryCode();
        
        return true;
}
 
Example 11
Source File: AdditionalPropertiesDeserializer.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    ObjectNode root = mapper.readTree(jp);
    ObjectNode copy = root.deepCopy();

    // compare top level fields and keep only missing fields
    final Class<?> tClass = this.defaultDeserializer.handledType();
    for (Class<?> c : TypeToken.of(tClass).getTypes().classes().rawTypes()) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            JsonProperty property = field.getAnnotation(JsonProperty.class);
            if (property != null) {
                String key = property.value().split("((?<!\\\\))\\.")[0];
                if (!key.isEmpty()) {
                    if (copy.has(key)) {
                        copy.remove(key);
                    }
                }
            }
        }
    }

    // put into additional properties
    root.put("additionalProperties", copy);

    JsonParser parser = new JsonFactory().createParser(root.toString());
    parser.nextToken();
    return defaultDeserializer.deserialize(parser, ctxt);
}
 
Example 12
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void updateSmtpConfig() throws Exception {
    ResultSet results =
            session.read("select value from central_config where key = 'smtp'");
    Row row = results.one();
    if (row == null) {
        return;
    }
    String smtpConfigText = row.getString(0);
    if (smtpConfigText == null) {
        return;
    }
    JsonNode jsonNode = mapper.readTree(smtpConfigText);
    if (jsonNode == null || !jsonNode.isObject()) {
        return;
    }
    ObjectNode smtpConfigNode = (ObjectNode) jsonNode;
    JsonNode sslNode = smtpConfigNode.remove("ssl");
    if (sslNode != null && sslNode.isBoolean() && sslNode.asBoolean()) {
        smtpConfigNode.put("connectionSecurity", "ssl-tls");
    }
    String updatedWebConfigText = mapper.writeValueAsString(smtpConfigNode);
    PreparedStatement preparedStatement =
            session.prepare("insert into central_config (key, value) values ('smtp', ?)");
    BoundStatement boundStatement = preparedStatement.bind();
    boundStatement.setString(0, updatedWebConfigText);
    session.write(boundStatement);
}
 
Example 13
Source File: ModelsResource.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected ObjectNode deleteEmbededReferencesFromStepModel(ObjectNode editorJsonNode) {
  try {
    JsonNode startFormNode = editorJsonNode.get("startForm");
    if (startFormNode != null) {
      editorJsonNode.remove("startForm");
    }
    internalDeleteNodeByNameFromStepModel(editorJsonNode.get("steps"), "formDefinition");
    internalDeleteNodeByNameFromStepModel(editorJsonNode.get("steps"), "subProcessDefinition");
    return editorJsonNode;
  } catch (Exception e) {
    throw new InternalServerErrorException("Cannot delete the external references");
  }
}
 
Example 14
Source File: ConfigFile.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static void upgradeJdbcPluginPropertiesIfNeeded(ObjectNode propertiesObjectNode) {
    if (propertiesObjectNode.path("captureBindParameters").asBoolean()
            && !propertiesObjectNode.has("captureBindParametersIncludes")) {
        // upgrade from 0.11.1 to 0.11.2
        propertiesObjectNode.set("captureBindParametersIncludes",
                mapper.createArrayNode().add(".*"));
        propertiesObjectNode.remove("captureBindParameters");
    }
}
 
Example 15
Source File: JsonEventConventionsTest.java    From tasmo with Apache License 2.0 4 votes vote down vote up
@Test (expectedExceptions = IllegalArgumentException.class)
public void testValidateNoTenantIdField() throws Exception {
    ObjectNode event = createValidEvent();
    event.remove(ReservedFields.TENANT_ID);
    jsonEventConventions.validate(event);
}
 
Example 16
Source File: JaxRsEnumRule.java    From apicurio-studio with Apache License 2.0 4 votes vote down vote up
/**
 * Applies this schema rule to take the required code generation steps.
 * <p>
 * A Java {@link Enum} is created, with constants for each of the enum
 * values present in the schema. The enum name is derived from the nodeName,
 * and the enum type itself is created as an inner class of the owning type.
 * In the rare case that no owning type exists (the enum is the root of the
 * schema), then the enum becomes a public class in its own right.
 * <p>
 * The actual JSON value for each enum constant is held in a property called
 * "value" in the generated type. A static factory method
 * <code>fromValue(String)</code> is added to the generated enum, and the
 * methods are annotated to allow Jackson to marshal/unmarshal values
 * correctly.
 *
 * @param nodeName
 *            the name of the property which is an "enum"
 * @param node
 *            the enum node
 * @param container
 *            the class container (class or package) to which this enum
 *            should be added
 * @return the newly generated Java type that was created to represent the
 *         given enum
 * @see org.jsonschema2pojo.rules.Rule#apply(java.lang.String, com.fasterxml.jackson.databind.JsonNode, com.fasterxml.jackson.databind.JsonNode, java.lang.Object, org.jsonschema2pojo.Schema)
 */
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer container,
        Schema schema) {

    JDefinedClass _enum;
    try {
        _enum = createEnum(node, nodeName, container);
    } catch (ClassAlreadyExistsException e) {
        return e.getExistingClass();
    }

    schema.setJavaTypeIfEmpty(_enum);

    if (node.has("javaInterfaces")) {
        addInterfaces(_enum, node.get("javaInterfaces"));
    }
    
    // copy our node; remove the javaType as it will throw off the TypeRule for our case
    ObjectNode typeNode = (ObjectNode)node.deepCopy();
    typeNode.remove("javaType");

    // If type is specified on the enum, get a type rule for it.  Otherwise, we're a string.
    // (This is different from the default of Object, which is why we don't do this for every case.)
    JType backingType = node.has("type") ? 
            ruleFactory.getTypeRule().apply(nodeName, typeNode, parent, container, schema) :
            container.owner().ref(String.class);
    
    JFieldVar valueField = addValueField(_enum, backingType);
    
    // override toString only if we have a sensible string to return
    if(isString(backingType)){
        addToString(_enum, valueField);
    }
    
    addValueMethod(_enum, valueField);
    
    addEnumConstants(node.path("enum"), _enum, node.path("javaEnumNames"), backingType);
    addFactoryMethod(_enum, backingType);

    return _enum;
}
 
Example 17
Source File: JsonEventConventionsTest.java    From tasmo with Apache License 2.0 4 votes vote down vote up
@Test (expectedExceptions = IllegalArgumentException.class)
public void testValidateNoClassNameField() throws Exception {
    ObjectNode event = createValidEvent();
    event.remove("TestEvent");
    jsonEventConventions.validate(event);
}
 
Example 18
Source File: JsonEventConventionsTest.java    From tasmo with Apache License 2.0 4 votes vote down vote up
@Test (expectedExceptions = IllegalArgumentException.class)
public void testValidateNoUserIdField() throws Exception {
    ObjectNode event = createValidEvent();
    event.remove(ReservedFields.USER_ID);
    jsonEventConventions.validate(event);
}
 
Example 19
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void consumeDeltaJsonNodeFields(EdmEntityType edmEntityType, ObjectNode node,
    Entity entity, ExpandTreeBuilder expandBuilder) 
    throws DeserializerException {
  if (constants instanceof Constantsv01) {
    List<String> navigationPropertyNames = edmEntityType.getNavigationPropertyNames();
    for (String navigationPropertyName : navigationPropertyNames) {
      // read expanded navigation property for delta
      String delta = navigationPropertyName + Constants.AT + Constants.DELTAVALUE;
      JsonNode jsonNode = node.get(delta);
      EdmNavigationProperty edmNavigationProperty = edmEntityType.getNavigationProperty(navigationPropertyName);
      if (jsonNode != null && jsonNode.isArray() && edmNavigationProperty.isCollection()) {
        checkNotNullOrValidNull(jsonNode, edmNavigationProperty);
        Link link = new Link();
        link.setType(Constants.ENTITY_SET_NAVIGATION_LINK_TYPE);
        link.setTitle(navigationPropertyName);
        Delta deltaValue = new Delta();
        for (JsonNode arrayElement : jsonNode) {
          String removed = Constants.AT + Constants.REMOVED;
          if (arrayElement.get(removed) != null) {
            //if @removed is present create a DeletedEntity Object
            JsonNode reasonNode = arrayElement.get(removed);
            DeletedEntity deletedEntity = new DeletedEntity();
            Reason reason = null;
            if (reasonNode.get(REASON) != null) {
              if(reasonNode.get(REASON).asText().equals(Reason.changed.name())){
                reason = Reason.changed;
              }else if(reasonNode.get(REASON).asText().equals(Reason.deleted.name())){
                reason = Reason.deleted;
              }
            }else{
              throw new DeserializerException("DeletedEntity reason is null.",
                  SerializerException.MessageKeys.MISSING_DELTA_PROPERTY, Constants.REASON);
            }
            deletedEntity.setReason(reason);
            try {
              deletedEntity.setId(new URI(arrayElement.get(constants.getId()).asText()));
            } catch (URISyntaxException e) {
              throw new DeserializerException("Could not set Id for deleted Entity", e,
                  DeserializerException.MessageKeys.UNKNOWN_CONTENT);
            }
            deltaValue.getDeletedEntities().add(deletedEntity);
          } else {
            //For @id and properties create normal entity
            Entity inlineEntity = consumeEntityNode(edmEntityType, (ObjectNode) arrayElement, expandBuilder);
            deltaValue.getEntities().add(inlineEntity);
          }
        }
        link.setInlineEntitySet(deltaValue);
        entity.getNavigationLinks().add(link);
        node.remove(navigationPropertyName);
      }
    }
  }

}
 
Example 20
Source File: JsonEntitySetDeserializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
protected ResWrap<EntityCollection> doDeserialize(final JsonParser parser) throws IOException {

    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);

    if (!tree.has(Constants.VALUE)) {
      return null;
    }

    final EntityCollection entitySet = new EntityCollection();

    URI contextURL;
    if (tree.hasNonNull(Constants.JSON_CONTEXT)) {
      contextURL = URI.create(tree.get(Constants.JSON_CONTEXT).textValue());
      tree.remove(Constants.JSON_CONTEXT);
    } else if (tree.hasNonNull(Constants.JSON_METADATA)) {
      contextURL = URI.create(tree.get(Constants.JSON_METADATA).textValue());
      tree.remove(Constants.JSON_METADATA);
    } else {
      contextURL = null;
    }
    if (contextURL != null) {
      entitySet.setBaseURI(URI.create(StringUtils.substringBefore(contextURL.toASCIIString(), Constants.METADATA)));
    }

    final String metadataETag;
    if (tree.hasNonNull(Constants.JSON_METADATA_ETAG)) {
      metadataETag = tree.get(Constants.JSON_METADATA_ETAG).textValue();
      tree.remove(Constants.JSON_METADATA_ETAG);
    } else {
      metadataETag = null;
    }

    if (tree.hasNonNull(Constants.JSON_COUNT)) {
      entitySet.setCount(tree.get(Constants.JSON_COUNT).asInt());
      tree.remove(Constants.JSON_COUNT);
    }
    if (tree.hasNonNull(Constants.JSON_NEXT_LINK)) {
      entitySet.setNext(URI.create(tree.get(Constants.JSON_NEXT_LINK).textValue()));
      tree.remove(Constants.JSON_NEXT_LINK);
    }
    if (tree.hasNonNull(Constants.JSON_DELTA_LINK)) {
      entitySet.setDeltaLink(URI.create(tree.get(Constants.JSON_DELTA_LINK).textValue()));
      tree.remove(Constants.JSON_DELTA_LINK);
    }

    if (tree.hasNonNull(Constants.VALUE)) {
      final JsonEntityDeserializer entityDeserializer = new JsonEntityDeserializer(serverMode);
      for (JsonNode jsonNode : tree.get(Constants.VALUE)) {
        entitySet.getEntities().add(
            entityDeserializer.doDeserialize(jsonNode.traverse(parser.getCodec())).getPayload());
      }
      tree.remove(Constants.VALUE);
    }
    final Set<String> toRemove = new HashSet<>();
    // any remaining entry is supposed to be an annotation or is ignored
    for (final Iterator<Map.Entry<String, JsonNode>> itor = tree.fields(); itor.hasNext();) {
      final Map.Entry<String, JsonNode> field = itor.next();
      if (field.getKey().charAt(0) == '@') {
        final Annotation annotation = new Annotation();
        annotation.setTerm(field.getKey().substring(1));

        try {
          value(annotation, field.getValue(), parser.getCodec());
        } catch (final EdmPrimitiveTypeException e) {
          throw new IOException(e);
        }
        entitySet.getAnnotations().add(annotation);
      } else if (field.getKey().charAt(0) == '#') {
        final Operation operation = new Operation();
        operation.setMetadataAnchor(field.getKey());

        final ObjectNode opNode = (ObjectNode) tree.get(field.getKey());
        operation.setTitle(opNode.get(Constants.ATTR_TITLE).asText());
        operation.setTarget(URI.create(opNode.get(Constants.ATTR_TARGET).asText()));
        entitySet.getOperations().add(operation);
        toRemove.add(field.getKey());
      }
    }
    tree.remove(toRemove);
    return new ResWrap<>(contextURL, metadataETag, entitySet);
  }