Example usage for com.fasterxml.jackson.databind.node ObjectNode putNull

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode putNull

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ObjectNode putNull.

Prototype

public ObjectNode putNull(String paramString) 

Source Link

Usage

From source file:scott.barleyrs.rest.EntityResultMessageBodyWriter.java

private void putNode(ObjectMapper mapper, ObjectNode jsonEntity, Node node, Set<Entity> started) {
    if (node instanceof ValueNode) {
        setValue(jsonEntity, node.getName(), (ValueNode) node);
    } else if (node instanceof RefNode) {
        Entity reffedEntity = ((RefNode) node).getReference(false);
        if (reffedEntity != null) {
            if (reffedEntity.isLoadedOrNew()) {
                JsonNode je = toJson(mapper, reffedEntity, started);
                if (je != null) {
                    jsonEntity.set(node.getName(), je);
                }/*from   www .j  a  v a  2 s.  co m*/
            } else if (reffedEntity.isFetchRequired()) {
                /*
                 * a fetch is required, we just output the ID
                 */
                jsonEntity.put(node.getName(), reffedEntity.getKey().getValue().toString());
            }

        } else {
            jsonEntity.putNull(node.getName());
        }
    } else if (node instanceof ToManyNode) {
        ToManyNode tm = (ToManyNode) node;
        if (!tm.getList().isEmpty()) {
            ArrayNode array = jsonEntity.arrayNode();
            for (Entity e : tm.getList()) {
                JsonNode je = toJson(mapper, e, started);
                if (je != null) {
                    array.add(je);
                }
            }
            jsonEntity.set(tm.getName(), array);
        }
    }
}

From source file:com.unboundid.scim2.common.DiffTestCase.java

/**
 * Test comparison of single-valued attributes.
 *
 * @throws Exception if an error occurs.
 */// w ww  .j av  a 2 s.co m
@Test
public void testDiffSingularAttribute() throws Exception {
    // *** singular ***
    ObjectNode source = JsonUtils.getJsonNodeFactory().objectNode();
    ObjectNode target = JsonUtils.getJsonNodeFactory().objectNode();

    // - unchanged
    source.put("userName", "bjensen");
    target.put("userName", "bjensen");
    // - added
    target.put("nickName", "bjj3");
    // - removed
    source.put("title", "hot shot");
    target.putNull("title");
    // - updated
    source.put("userType", "employee");
    target.put("userType", "manager");
    // - non-asserted
    source.put("displayName", "don't touch");

    List<PatchOperation> d = JsonUtils.diff(source, target, false);

    assertEquals(d.size(), 2);

    assertTrue(d.contains(PatchOperation.remove(Path.root().attribute("title"))));
    ObjectNode replaceValue = JsonUtils.getJsonNodeFactory().objectNode();
    replaceValue.put("userType", "manager");
    replaceValue.put("nickName", "bjj3");
    assertTrue(d.contains(PatchOperation.replace(replaceValue)));

    List<PatchOperation> d2 = JsonUtils.diff(source, target, true);
    for (PatchOperation op : d2) {
        op.apply(source);
    }
    removeNullNodes(target);
    assertEquals(source, target);
}

From source file:com.glaf.activiti.web.rest.ActivitiResource.java

@SuppressWarnings("unchecked")
private void getActivity(ActivityImpl activity, ArrayNode activityArray, ArrayNode sequenceFlowArray) {
    ObjectNode activityJSON = new ObjectMapper().createObjectNode();

    // Gather info on the multi instance marker
    String multiInstance = (String) activity.getProperty("multiInstance");

    if (multiInstance != null) {
        if (!"sequential".equals(multiInstance)) {
            multiInstance = "parallel";
        }/*from w ww. j  av a2 s  . c om*/
    }

    ActivityBehavior activityBehavior = activity.getActivityBehavior();

    // Gather info on the collapsed marker
    Boolean collapsed = (activityBehavior instanceof CallActivityBehavior);
    Boolean expanded = (Boolean) activity.getProperty(BpmnParse.PROPERTYNAME_ISEXPANDED);

    if (expanded != null) {
        collapsed = !expanded;
    }

    Boolean isInterrupting = null;

    if (activityBehavior instanceof BoundaryEventActivityBehavior) {
        isInterrupting = ((BoundaryEventActivityBehavior) activityBehavior).isInterrupting();
    }

    // Outgoing transitions of activity
    for (PvmTransition sequenceFlow : activity.getOutgoingTransitions()) {
        String flowName = (String) sequenceFlow.getProperty("name");
        boolean isHighLighted = (highLightedFlows.contains(sequenceFlow.getId()));
        boolean isConditional = (sequenceFlow.getProperty(BpmnParse.PROPERTYNAME_CONDITION) != null)
                && !((String) activity.getProperty("type")).toLowerCase().contains("gateway");
        boolean isDefault = sequenceFlow.getId().equals(activity.getProperty("default"))
                && ((String) activity.getProperty("type")).toLowerCase().contains("gateway");

        List<Integer> waypoints = ((TransitionImpl) sequenceFlow).getWaypoints();
        ArrayNode xPointArray = new ObjectMapper().createArrayNode();
        ArrayNode yPointArray = new ObjectMapper().createArrayNode();

        for (int i = 0; i < waypoints.size(); i += 2) {
            xPointArray.add(waypoints.get(i));
            yPointArray.add(waypoints.get(i + 1));
        }

        ObjectNode flowJSON = new ObjectMapper().createObjectNode();
        flowJSON.put("id", sequenceFlow.getId());
        flowJSON.put("name", flowName);
        flowJSON.put("flow", "(" + sequenceFlow.getSource().getId() + ")--" + sequenceFlow.getId() + "-->("
                + sequenceFlow.getDestination().getId() + ")");

        if (isConditional) {
            flowJSON.put("isConditional", isConditional);
        }

        if (isDefault) {
            flowJSON.put("isDefault", isDefault);
        }

        if (isHighLighted) {
            flowJSON.put("isHighLighted", isHighLighted);
        }

        flowJSON.set("xPointArray", xPointArray);
        flowJSON.set("yPointArray", yPointArray);

        sequenceFlowArray.add(flowJSON);
    }

    // Nested activities (boundary events)
    ArrayNode nestedActivityArray = new ObjectMapper().createArrayNode();

    for (ActivityImpl nestedActivity : activity.getActivities()) {
        nestedActivityArray.add(nestedActivity.getId());
    }

    Map<String, Object> properties = activity.getProperties();
    ObjectNode propertiesJSON = new ObjectMapper().createObjectNode();

    for (String key : properties.keySet()) {
        Object prop = properties.get(key);

        if (prop instanceof String) {
            propertiesJSON.put(key, (String) properties.get(key));
        } else if (prop instanceof Integer) {
            propertiesJSON.put(key, (Integer) properties.get(key));
        } else if (prop instanceof Boolean) {
            propertiesJSON.put(key, (Boolean) properties.get(key));
        } else if ("initial".equals(key)) {
            ActivityImpl act = (ActivityImpl) properties.get(key);
            propertiesJSON.put(key, act.getId());
        } else if ("timerDeclarations".equals(key)) {
            List<TimerDeclarationImpl> timerDeclarations = (ArrayList<TimerDeclarationImpl>) properties
                    .get(key);
            ArrayNode timerDeclarationArray = new ObjectMapper().createArrayNode();

            if (timerDeclarations != null) {
                for (TimerDeclarationImpl timerDeclaration : timerDeclarations) {
                    ObjectNode timerDeclarationJSON = new ObjectMapper().createObjectNode();

                    timerDeclarationJSON.put("isExclusive", timerDeclaration.isExclusive());

                    if (timerDeclaration.getRepeat() != null) {
                        timerDeclarationJSON.put("repeat", timerDeclaration.getRepeat());
                    }

                    timerDeclarationJSON.put("retries", String.valueOf(timerDeclaration.getRetries()));
                    timerDeclarationJSON.put("type", timerDeclaration.getJobHandlerType());
                    timerDeclarationJSON.put("configuration", timerDeclaration.getJobHandlerConfiguration());
                    // timerDeclarationJSON.put("expression",
                    // timerDeclaration.getDescription());
                    timerDeclarationArray.add(timerDeclarationJSON);
                }
            }

            if (timerDeclarationArray.size() > 0) {
                propertiesJSON.set(key, timerDeclarationArray);
            }

        } else if ("eventDefinitions".equals(key)) {
            ArrayList<EventSubscriptionDeclaration> eventDefinitions = (ArrayList<EventSubscriptionDeclaration>) properties
                    .get(key);
            ArrayNode eventDefinitionsArray = new ObjectMapper().createArrayNode();

            if (eventDefinitions != null) {
                for (EventSubscriptionDeclaration eventDefinition : eventDefinitions) {
                    ObjectNode eventDefinitionJSON = new ObjectMapper().createObjectNode();

                    if (eventDefinition.getActivityId() != null) {
                        eventDefinitionJSON.put("activityId", eventDefinition.getActivityId());
                    }

                    eventDefinitionJSON.put("eventName", eventDefinition.getEventName());
                    eventDefinitionJSON.put("eventType", eventDefinition.getEventType());
                    eventDefinitionJSON.put("isAsync", eventDefinition.isAsync());
                    eventDefinitionJSON.put("isStartEvent", eventDefinition.isStartEvent());
                    eventDefinitionsArray.add(eventDefinitionJSON);
                }
            }

            if (eventDefinitionsArray.size() > 0) {
                propertiesJSON.set(key, eventDefinitionsArray);
            }

        } else if ("errorEventDefinitions".equals(key)) {
            ArrayList<ErrorEventDefinition> errorEventDefinitions = (ArrayList<ErrorEventDefinition>) properties
                    .get(key);
            ArrayNode errorEventDefinitionsArray = new ObjectMapper().createArrayNode();

            if (errorEventDefinitions != null) {
                for (ErrorEventDefinition errorEventDefinition : errorEventDefinitions) {
                    ObjectNode errorEventDefinitionJSON = new ObjectMapper().createObjectNode();

                    if (errorEventDefinition.getErrorCode() != null) {
                        errorEventDefinitionJSON.put("errorCode", errorEventDefinition.getErrorCode());
                    } else {
                        errorEventDefinitionJSON.putNull("errorCode");
                    }

                    errorEventDefinitionJSON.put("handlerActivityId",
                            errorEventDefinition.getHandlerActivityId());

                    errorEventDefinitionsArray.add(errorEventDefinitionJSON);
                }
            }

            if (errorEventDefinitionsArray.size() > 0) {
                propertiesJSON.set(key, errorEventDefinitionsArray);
            }
        }
    }

    if ("callActivity".equals(properties.get("type"))) {
        CallActivityBehavior callActivityBehavior = null;

        if (activityBehavior instanceof CallActivityBehavior) {
            callActivityBehavior = (CallActivityBehavior) activityBehavior;
        }

        if (callActivityBehavior != null) {
            propertiesJSON.put("processDefinitonKey", callActivityBehavior.getProcessDefinitonKey());

            ArrayNode processInstanceArray = new ObjectMapper().createArrayNode();

            if (processInstance != null) {
                List<Execution> executionList = runtimeService.createExecutionQuery()
                        .processInstanceId(processInstanceId).activityId(activity.getId()).list();

                if (executionList.size() > 0) {
                    for (Execution execution : executionList) {
                        ObjectNode processInstanceJSON = subProcessInstanceMap.get(execution.getId());
                        processInstanceArray.add(processInstanceJSON);
                    }
                }
            }

            // If active activities nas no instance of this callActivity
            // then add
            // last definition
            if (processInstanceArray.size() == 0) {
                // Get last definition by key
                ProcessDefinition lastProcessDefinition = repositoryService.createProcessDefinitionQuery()
                        .processDefinitionKey(callActivityBehavior.getProcessDefinitonKey()).latestVersion()
                        .singleResult();

                ObjectNode processInstanceJSON = new ObjectMapper().createObjectNode();
                processInstanceJSON.put("processDefinitionId", lastProcessDefinition.getId());
                processInstanceJSON.put("processDefinitionKey", lastProcessDefinition.getKey());
                processInstanceJSON.put("processDefinitionName", lastProcessDefinition.getName());
                processInstanceArray.add(processInstanceJSON);
            }

            if (processInstanceArray.size() > 0) {
                propertiesJSON.set("processDefinitons", processInstanceArray);
            }
        }
    }

    activityJSON.put("activityId", activity.getId());
    activityJSON.set("properties", propertiesJSON);

    if (multiInstance != null) {
        activityJSON.put("multiInstance", multiInstance);
    }

    if (collapsed) {
        activityJSON.put("collapsed", collapsed);
    }

    if (nestedActivityArray.size() > 0) {
        activityJSON.set("nestedActivities", nestedActivityArray);
    }

    if (isInterrupting != null) {
        activityJSON.put("isInterrupting", isInterrupting);
    }

    activityJSON.put("x", activity.getX());
    activityJSON.put("y", activity.getY());
    activityJSON.put("width", activity.getWidth());
    activityJSON.put("height", activity.getHeight());

    activityArray.add(activityJSON);

    // Nested activities (boundary events)
    for (ActivityImpl nestedActivity : activity.getActivities()) {
        getActivity(nestedActivity, activityArray, sequenceFlowArray);
    }
}

From source file:scott.barleyrs.rest.QueryResultMessageBodyWriter.java

private void putNode(ObjectMapper mapper, ObjectNode jsonEntity, Node node, Set<Entity> started) {
    if (node instanceof ValueNode) {
        setValue(jsonEntity, node.getName(), (ValueNode) node);
    } else if (node instanceof RefNode) {
        if (((RefNode) node).getEntityKey() == NotLoaded.VALUE) {
            return;
        }// w ww . j a v a2  s .  c o  m
        Entity reffedEntity = ((RefNode) node).getReference(false);
        if (reffedEntity != null) {
            if (reffedEntity.isLoadedOrNew()) {
                /*
                 * we have the entities properties so we convert it to a json object
                 */
                JsonNode je = toJson(mapper, reffedEntity, started);
                if (je != null) {
                    jsonEntity.set(node.getName(), je);
                }
            } else if (reffedEntity.isFetchRequired()) {
                /*
                 * a fetch is required, we just output the ID
                 */
                jsonEntity.put(node.getName(), reffedEntity.getKey().getValue().toString());
            }
        } else {
            jsonEntity.putNull(node.getName());
        }
    } else if (node instanceof ToManyNode) {
        ToManyNode tm = (ToManyNode) node;
        if (!tm.getList().isEmpty()) {
            ArrayNode array = jsonEntity.arrayNode();
            for (Entity e : tm.getList()) {
                JsonNode je = toJson(mapper, e, started);
                if (je != null) {
                    array.add(je);
                }
            }
            jsonEntity.set(tm.getName(), array);
        }
    }
}

From source file:org.activiti.rest.service.api.legacy.process.LegacyProcessInstanceResource.java

private void addVariableList(String processInstanceId, ObjectNode responseJSON) {

    try {/*from   w  w  w. j ava 2s .c o  m*/
        Map<String, Object> variableMap = ActivitiUtil.getRuntimeService().getVariables(processInstanceId);

        if (variableMap != null && variableMap.size() > 0) {
            ArrayNode variablesJSON = new ObjectMapper().createArrayNode();
            responseJSON.put("variables", variablesJSON);
            for (String key : variableMap.keySet()) {
                Object variableValue = variableMap.get(key);
                ObjectNode variableJSON = new ObjectMapper().createObjectNode();
                variableJSON.put("variableName", key);
                if (variableValue != null) {
                    if (variableValue instanceof Boolean) {
                        variableJSON.put("variableValue", (Boolean) variableValue);
                    } else if (variableValue instanceof Long) {
                        variableJSON.put("variableValue", (Long) variableValue);
                    } else if (variableValue instanceof Double) {
                        variableJSON.put("variableValue", (Double) variableValue);
                    } else if (variableValue instanceof Float) {
                        variableJSON.put("variableValue", (Float) variableValue);
                    } else if (variableValue instanceof Integer) {
                        variableJSON.put("variableValue", (Integer) variableValue);
                    } else {
                        variableJSON.put("variableValue", variableValue.toString());
                    }
                } else {
                    variableJSON.putNull("variableValue");
                }
                variablesJSON.add(variableJSON);
            }
        }
    } catch (Exception e) {
        // Absorb possible error that the execution could not be found
    }

    List<HistoricDetail> historyVariableList = ActivitiUtil.getHistoryService().createHistoricDetailQuery()
            .processInstanceId(processInstanceId).variableUpdates().orderByTime().desc().list();

    if (historyVariableList != null && historyVariableList.size() > 0) {
        ArrayNode variablesJSON = new ObjectMapper().createArrayNode();
        responseJSON.put("historyVariables", variablesJSON);
        for (HistoricDetail historicDetail : historyVariableList) {
            HistoricVariableUpdate variableUpdate = (HistoricVariableUpdate) historicDetail;
            ObjectNode variableJSON = new ObjectMapper().createObjectNode();
            variableJSON.put("variableName", variableUpdate.getVariableName());
            if (variableUpdate.getValue() != null) {
                if (variableUpdate.getValue() instanceof Boolean) {
                    variableJSON.put("variableValue", (Boolean) variableUpdate.getValue());
                } else if (variableUpdate.getValue() instanceof Long) {
                    variableJSON.put("variableValue", (Long) variableUpdate.getValue());
                } else if (variableUpdate.getValue() instanceof Double) {
                    variableJSON.put("variableValue", (Double) variableUpdate.getValue());
                } else if (variableUpdate.getValue() instanceof Float) {
                    variableJSON.put("variableValue", (Float) variableUpdate.getValue());
                } else if (variableUpdate.getValue() instanceof Integer) {
                    variableJSON.put("variableValue", (Integer) variableUpdate.getValue());
                } else {
                    variableJSON.put("variableValue", variableUpdate.getValue().toString());
                }
            } else {
                variableJSON.putNull("variableValue");
            }
            variableJSON.put("variableType", variableUpdate.getVariableTypeName());
            variableJSON.put("revision", variableUpdate.getRevision());
            variableJSON.put("time", RequestUtil.dateToString(variableUpdate.getTime()));

            variablesJSON.add(variableJSON);
        }
    }
}

From source file:org.springframework.data.rest.webmvc.json.DomainObjectReader.java

/**
 * Reads the given source node onto the given target object and applies PUT semantics, i.e. explicitly
 * //  w ww  .  j  a v  a 2  s .c  o m
 * @param source must not be {@literal null}.
 * @param target must not be {@literal null}.
 * @param mapper
 * @return
 */
public <T> T readPut(final ObjectNode source, T target, final ObjectMapper mapper) {

    Assert.notNull(source, "ObjectNode must not be null!");
    Assert.notNull(target, "Existing object instance must not be null!");
    Assert.notNull(mapper, "ObjectMapper must not be null!");

    Class<? extends Object> type = target.getClass();

    final PersistentEntity<?, ?> entity = entities.getPersistentEntity(type);

    Assert.notNull(entity, "No PersistentEntity found for ".concat(type.getName()).concat("!"));

    final MappedProperties properties = getJacksonProperties(entity, mapper);

    entity.doWithProperties(new SimplePropertyHandler() {

        /*
         * (non-Javadoc)
         * @see org.springframework.data.mapping.SimplePropertyHandler#doWithPersistentProperty(org.springframework.data.mapping.PersistentProperty)
         */
        @Override
        public void doWithPersistentProperty(PersistentProperty<?> property) {

            if (property.isIdProperty() || property.isVersionProperty()) {
                return;
            }

            String mappedName = properties.getMappedName(property);

            boolean isMappedProperty = mappedName != null;
            boolean noValueInSource = !source.has(mappedName);

            if (isMappedProperty && noValueInSource) {
                source.putNull(mappedName);
            }
        }
    });

    return merge(source, target, mapper);
}

From source file:com.unboundid.scim2.server.utils.SchemaCheckerTestCase.java

/**
 * Provider for testRequiredAttributes./*from  ww w .  j  av a2 s. c om*/
 *
 * @return The test data.
 */
@DataProvider
public Object[][] requiredAttributesProvider() {
    // Optional attribute
    AttributeDefinition optAttr = new AttributeDefinition.Builder().setName("test")
            .setType(AttributeDefinition.Type.STRING).setRequired(false).build();

    // Required attribute
    AttributeDefinition reqAttr = new AttributeDefinition.Builder().setName("test")
            .setType(AttributeDefinition.Type.STRING).setRequired(true).build();

    // Optional attribute, optional sub-attribute
    AttributeDefinition optAttrOptSub = new AttributeDefinition.Builder().setName("test")
            .setType(AttributeDefinition.Type.COMPLEX).setRequired(false).addSubAttributes(optAttr).build();

    // Optional attribute, required sub-attribute
    AttributeDefinition optAttrReqSub = new AttributeDefinition.Builder().setName("test")
            .setType(AttributeDefinition.Type.COMPLEX).setRequired(false).addSubAttributes(reqAttr).build();

    // Required attribute, required sub-attribute
    AttributeDefinition reqAttrReqSub = new AttributeDefinition.Builder().setName("test")
            .setType(AttributeDefinition.Type.COMPLEX).setRequired(true).addSubAttributes(reqAttr).build();

    // Optional multi-valeud attribute
    AttributeDefinition optMVAttr = new AttributeDefinition.Builder().setName("test")
            .setType(AttributeDefinition.Type.STRING).setRequired(false).setMultiValued(true).build();

    // Required multi-valued attribute
    AttributeDefinition reqMVAttr = new AttributeDefinition.Builder().setName("test")
            .setType(AttributeDefinition.Type.STRING).setRequired(true).setMultiValued(true).build();

    // Optional multi-valued attribute, optional sub-attribute
    AttributeDefinition optMVAttrOptSub = new AttributeDefinition.Builder().setName("test")
            .setType(AttributeDefinition.Type.COMPLEX).setRequired(false).addSubAttributes(optAttr)
            .setMultiValued(true).build();

    // Optional multi-valued attribute, required sub-attribute
    AttributeDefinition optMVAttrReqSub = new AttributeDefinition.Builder().setName("test")
            .setType(AttributeDefinition.Type.COMPLEX).setRequired(false).addSubAttributes(reqAttr)
            .setMultiValued(true).build();

    // Required multi-valued attribute, required sub-attribute
    AttributeDefinition reqMVAttrReqSub = new AttributeDefinition.Builder().setName("test")
            .setType(AttributeDefinition.Type.COMPLEX).setRequired(true).addSubAttributes(reqAttr)
            .setMultiValued(true).build();

    // Attribute not present
    ObjectNode notPresent = JsonUtils.getJsonNodeFactory().objectNode();
    notPresent.putArray("schemas").add("urn:id:test");

    // Attribute with null value
    ObjectNode nullValue = JsonUtils.getJsonNodeFactory().objectNode();
    nullValue.putArray("schemas").add("urn:id:test");
    nullValue.putNull("test");

    // Attribute with not present sub-attribute
    ObjectNode subNotPresent = JsonUtils.getJsonNodeFactory().objectNode();
    subNotPresent.putArray("schemas").add("urn:id:test");
    subNotPresent.putObject("test");

    // Attribute with null value sub-attribute
    ObjectNode subNullValue = JsonUtils.getJsonNodeFactory().objectNode();
    subNullValue.putArray("schemas").add("urn:id:test");
    subNullValue.putObject("test").putNull("test");

    // Attribute with empty array
    ObjectNode emptyArray = JsonUtils.getJsonNodeFactory().objectNode();
    emptyArray.putArray("schemas").add("urn:id:test");
    emptyArray.putArray("test");

    // Attribute with one element not present sub-attribute
    ObjectNode arrayNotPresent = JsonUtils.getJsonNodeFactory().objectNode();
    arrayNotPresent.putArray("schemas").add("urn:id:test");
    arrayNotPresent.putArray("test").addObject();

    // Attribute with one element null value sub-attribute
    ObjectNode arrayNullValue = JsonUtils.getJsonNodeFactory().objectNode();
    arrayNullValue.putArray("schemas").add("urn:id:test");
    arrayNullValue.putArray("test").addObject().putNull("test");

    return new Object[][] { new Object[] { optAttr, notPresent, 0 }, new Object[] { optAttr, nullValue, 0 },
            new Object[] { reqAttr, notPresent, 1 }, new Object[] { reqAttr, nullValue, 1 },
            new Object[] { optAttrOptSub, notPresent, 0 }, new Object[] { optAttrOptSub, nullValue, 0 },
            new Object[] { optAttrOptSub, subNotPresent, 0 }, new Object[] { optAttrOptSub, subNullValue, 0 },
            new Object[] { optAttrReqSub, notPresent, 0 }, new Object[] { optAttrReqSub, nullValue, 0 },
            new Object[] { optAttrReqSub, subNotPresent, 1 }, new Object[] { optAttrReqSub, subNullValue, 1 },
            new Object[] { reqAttrReqSub, notPresent, 1 }, new Object[] { reqAttrReqSub, nullValue, 1 },
            new Object[] { reqAttrReqSub, subNotPresent, 1 }, new Object[] { reqAttrReqSub, subNullValue, 1 },
            new Object[] { optMVAttr, notPresent, 0 }, new Object[] { optMVAttr, emptyArray, 0 },
            new Object[] { reqMVAttr, notPresent, 1 }, new Object[] { reqMVAttr, emptyArray, 1 },
            new Object[] { optMVAttrOptSub, notPresent, 0 }, new Object[] { optMVAttrOptSub, emptyArray, 0 },
            new Object[] { optMVAttrOptSub, arrayNotPresent, 0 },
            new Object[] { optMVAttrOptSub, arrayNullValue, 0 },
            new Object[] { optMVAttrReqSub, notPresent, 0 }, new Object[] { optMVAttrReqSub, emptyArray, 0 },
            new Object[] { optMVAttrReqSub, arrayNotPresent, 1 },
            new Object[] { optMVAttrReqSub, arrayNullValue, 1 },
            new Object[] { reqMVAttrReqSub, notPresent, 1 }, new Object[] { reqMVAttrReqSub, emptyArray, 1 },
            new Object[] { reqMVAttrReqSub, arrayNotPresent, 1 },
            new Object[] { reqMVAttrReqSub, arrayNullValue, 1 }, };
}

From source file:org.waarp.gateway.kernel.rest.RestArgument.java

/**
 * Set values according to the request URI
 * //w  w w .  j  a  va 2s.c o  m
 * @param request
 */
public void setRequest(HttpRequest request) {
    arguments.put(REST_ROOT_FIELD.ARG_HASBODY.field, (request instanceof FullHttpRequest
            && ((FullHttpRequest) request).content() != Unpooled.EMPTY_BUFFER));
    arguments.put(REST_ROOT_FIELD.ARG_METHOD.field, request.method().name());
    QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
    String path = decoderQuery.path();
    arguments.put(REST_ROOT_FIELD.ARG_PATH.field, path);
    // compute path main uri
    String basepath = path;
    int pos = basepath.indexOf('/');
    if (pos >= 0) {
        if (pos == 0) {
            int pos2 = basepath.indexOf('/', 1);
            if (pos2 < 0) {
                basepath = basepath.substring(1);
            } else {
                basepath = basepath.substring(1, pos2);
            }
        } else {
            basepath = basepath.substring(0, pos);
        }
    }
    arguments.put(REST_ROOT_FIELD.ARG_BASEPATH.field, basepath);
    // compute sub path args
    if (pos == 0) {
        pos = path.indexOf('/', 1);
    }
    if (pos >= 0) {
        int pos2 = path.indexOf('/', pos + 1);
        if (pos2 > 0) {
            ArrayNode array = arguments.putArray(REST_ROOT_FIELD.ARGS_SUBPATH.field);
            while (pos2 > 0) {
                array.add(path.substring(pos + 1, pos2));
                pos = pos2;
                pos2 = path.indexOf('/', pos + 1);
            }
        }
        pos2 = path.indexOf('?', pos + 1);
        if (pos2 > 0 && pos2 > pos + 1) {
            ArrayNode array = (ArrayNode) arguments.get(REST_ROOT_FIELD.ARGS_SUBPATH.field);
            if (array == null) {
                array = arguments.putArray(REST_ROOT_FIELD.ARGS_SUBPATH.field);
            }
            array.add(path.substring(pos + 1, pos2));
        } else {
            String last = path.substring(pos + 1);
            if (!last.isEmpty()) {
                ArrayNode array = (ArrayNode) arguments.get(REST_ROOT_FIELD.ARGS_SUBPATH.field);
                if (array == null) {
                    array = arguments.putArray(REST_ROOT_FIELD.ARGS_SUBPATH.field);
                }
                array.add(last);
            }
        }
    }
    Map<String, List<String>> map = decoderQuery.parameters();
    ObjectNode node = arguments.putObject(REST_GROUP.ARGS_URI.group);
    for (String key : map.keySet()) {
        if (key.equalsIgnoreCase(REST_ROOT_FIELD.ARG_X_AUTH_KEY.field)) {
            arguments.put(REST_ROOT_FIELD.ARG_X_AUTH_KEY.field, map.get(key).get(0));
            continue;
        }
        if (key.equalsIgnoreCase(REST_ROOT_FIELD.ARG_X_AUTH_USER.field)) {
            arguments.put(REST_ROOT_FIELD.ARG_X_AUTH_USER.field, map.get(key).get(0));
            continue;
        }
        if (key.equalsIgnoreCase(REST_ROOT_FIELD.ARG_X_AUTH_TIMESTAMP.field)) {
            arguments.put(REST_ROOT_FIELD.ARG_X_AUTH_TIMESTAMP.field, map.get(key).get(0));
            continue;
        }
        List<String> list = map.get(key);
        if (list.size() > 1) {
            ArrayNode array = node.putArray(key);
            for (String val : map.get(key)) {
                array.add(val);
            }
        } else if (list.isEmpty()) {
            node.putNull(key);
        } else {
            //1
            node.put(key, list.get(0));
        }
    }
}

From source file:com.unboundid.scim2.common.DiffTestCase.java

/**
 * Test comparison of single-valued complex attributes.
 *
 * @throws Exception if an error occurs.
 *//*from   w  w w .  ja  va  2s.  c  o  m*/
@Test
public void testDiffSingularComplexAttribute() throws Exception {
    // *** singular complex ***
    // - unchanged
    ObjectNode source = JsonUtils.getJsonNodeFactory().objectNode();
    ObjectNode target = JsonUtils.getJsonNodeFactory().objectNode();

    ObjectNode name = JsonUtils.valueToNode(
            new Name().setFormatted("Ms. Barbara J Jensen III").setFamilyName("Jensen").setMiddleName("J")
                    .setGivenName("Barbara").setHonorificPrefix("Ms.").setHonorificSuffix("III"));

    source.set("name", name);
    target.set("name", name);

    List<PatchOperation> d = JsonUtils.diff(source, target, false);
    assertEquals(d.size(), 0);

    List<PatchOperation> d2 = JsonUtils.diff(source, target, true);
    for (PatchOperation op : d2) {
        op.apply(source);
    }
    removeNullNodes(target);
    assertEquals(source, target);

    // - added
    source = JsonUtils.getJsonNodeFactory().objectNode();
    target = JsonUtils.getJsonNodeFactory().objectNode();

    target.set("name", name);

    d = JsonUtils.diff(source, target, false);
    assertEquals(d.size(), 1);
    assertTrue(d.contains(PatchOperation
            .replace((ObjectNode) JsonUtils.getJsonNodeFactory().objectNode().set("name", name))));

    d2 = JsonUtils.diff(source, target, true);
    for (PatchOperation op : d2) {
        op.apply(source);
    }
    removeNullNodes(target);
    assertEquals(source, target);

    // - removed
    source = JsonUtils.getJsonNodeFactory().objectNode();
    target = JsonUtils.getJsonNodeFactory().objectNode();

    source.set("name", name);
    target.putNull("name");

    d = JsonUtils.diff(source, target, false);
    assertEquals(d.size(), 1);
    assertTrue(d.contains(PatchOperation.remove(Path.root().attribute("name"))));

    d2 = JsonUtils.diff(source, target, true);
    for (PatchOperation op : d2) {
        op.apply(source);
    }
    removeNullNodes(target);
    assertEquals(source, target);

    // - removed a sub-attribute
    source = JsonUtils.getJsonNodeFactory().objectNode();
    target = JsonUtils.getJsonNodeFactory().objectNode();

    source.set("name", name);
    target.set("name", name.deepCopy().putNull("honorificSuffix"));

    d = JsonUtils.diff(source, target, false);
    assertEquals(d.size(), 1);
    assertTrue(d.contains(PatchOperation.remove(Path.root().attribute("name").attribute("honorificSuffix"))));

    d2 = JsonUtils.diff(source, target, true);
    for (PatchOperation op : d2) {
        op.apply(source);
    }
    removeNullNodes(target);
    assertEquals(source, target);

    // - updated
    source = JsonUtils.getJsonNodeFactory().objectNode();
    target = JsonUtils.getJsonNodeFactory().objectNode();

    source.set("name", name);
    target.set("name", name.deepCopy().put("familyName", "Johnson"));

    d = JsonUtils.diff(source, target, false);
    assertEquals(d.size(), 1);
    ObjectNode replaceValue = JsonUtils.getJsonNodeFactory().objectNode();
    replaceValue.putObject("name").put("familyName", "Johnson");
    assertTrue(d.contains(PatchOperation.replace(replaceValue)));

    d2 = JsonUtils.diff(source, target, true);
    for (PatchOperation op : d2) {
        op.apply(source);
    }
    removeNullNodes(target);
    assertEquals(source, target);

    // - non-asserted
    source = JsonUtils.getJsonNodeFactory().objectNode();
    target = JsonUtils.getJsonNodeFactory().objectNode();

    ObjectNode nameCopy = name.deepCopy();
    nameCopy.remove("middleName");
    source.set("name", name);
    target.set("name", nameCopy);

    d = JsonUtils.diff(source, target, false);
    assertEquals(d.size(), 0);

    d2 = JsonUtils.diff(source, target, true);
    for (PatchOperation op : d2) {
        op.apply(source);
    }
    removeNullNodes(target);
    assertEquals(source, target);
}

From source file:org.activiti.editor.language.json.converter.BaseBpmnJsonConverter.java

protected void addFormProperties(List<FormProperty> formProperties, ObjectNode propertiesNode) {
    ObjectNode formPropertiesNode = objectMapper.createObjectNode();
    ArrayNode itemsNode = objectMapper.createArrayNode();
    for (FormProperty property : formProperties) {
        ObjectNode propertyItemNode = objectMapper.createObjectNode();
        propertyItemNode.put(PROPERTY_FORM_ID, property.getId());
        propertyItemNode.put(PROPERTY_FORM_NAME, property.getName());
        propertyItemNode.put(PROPERTY_FORM_TYPE, property.getType());
        if (StringUtils.isNotEmpty(property.getExpression())) {
            propertyItemNode.put(PROPERTY_FORM_EXPRESSION, property.getExpression());
        } else {/*from  w w w.  jav  a  2 s .c  o  m*/
            propertyItemNode.putNull(PROPERTY_FORM_EXPRESSION);
        }
        if (StringUtils.isNotEmpty(property.getVariable())) {
            propertyItemNode.put(PROPERTY_FORM_VARIABLE, property.getVariable());
        } else {
            propertyItemNode.putNull(PROPERTY_FORM_VARIABLE);
        }

        propertyItemNode.put(PROPERTY_FORM_REQUIRED,
                property.isRequired() ? PROPERTY_VALUE_YES : PROPERTY_VALUE_NO);
        propertyItemNode.put(PROPERTY_FORM_READABLE,
                property.isReadable() ? PROPERTY_VALUE_YES : PROPERTY_VALUE_NO);
        propertyItemNode.put(PROPERTY_FORM_WRITEABLE,
                property.isWriteable() ? PROPERTY_VALUE_YES : PROPERTY_VALUE_NO);

        ObjectNode formValueNode = objectMapper.createObjectNode();
        ArrayNode formValueItemNode = objectMapper.createArrayNode();

        for (FormValue formValue : property.getFormValues()) {
            ObjectNode propertyFormValueNode = objectMapper.createObjectNode();
            propertyFormValueNode.put(PROPERTY_FORM_FORM_VALUE_ID, formValue.getId());
            propertyFormValueNode.put(PROPERTY_FORM_FORM_VALUE_NAME, formValue.getName());
            formValueItemNode.add(propertyFormValueNode);
        }
        formValueNode.put("totalCount", formValueItemNode.size());
        formValueNode.put(EDITOR_PROPERTIES_GENERAL_ITEMS, formValueItemNode);
        propertyItemNode.put(PROPERTY_FORM_FORM_VALUES, formValueNode.toString());

        itemsNode.add(propertyItemNode);
    }

    formPropertiesNode.put("totalCount", itemsNode.size());
    formPropertiesNode.put(EDITOR_PROPERTIES_GENERAL_ITEMS, itemsNode);
    propertiesNode.put("formproperties", formPropertiesNode);
}