Java Code Examples for com.fasterxml.jackson.databind.node.ArrayNode#addObject()

The following examples show how to use com.fasterxml.jackson.databind.node.ArrayNode#addObject() . 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: CmmnLoggingSessionUtil.java    From flowable-engine with Apache License 2.0 7 votes vote down vote up
public static void addEvaluateSentryLoggingData(List<SentryOnPart> sentryOnParts, SentryIfPart sentryIfPart, EntityWithSentryPartInstances instance) {
    ObjectNode loggingNode = fillEvaluateSentryInstanceEntity(instance);
    ArrayNode onPartArrayNode = loggingNode.putArray("onParts");
    for (SentryOnPart onPart : sentryOnParts) {
        ObjectNode onPartNode = onPartArrayNode.addObject();
        onPartNode.put("id", onPart.getId());
        onPartNode.put("source", onPart.getSourceRef());
        onPartNode.put("elementId", onPart.getSource().getPlanItemDefinition().getId());
        onPartNode.put("standardEvent", onPart.getStandardEvent());
    }
    
    ObjectNode ifPartNode = loggingNode.putObject("ifPart");
    ifPartNode.put("condition", sentryIfPart.getCondition());
    
    LoggingSessionUtil.addLoggingData(CmmnLoggingSessionConstants.TYPE_EVALUATE_SENTRY, loggingNode);
}
 
Example 2
Source File: Dashboard.java    From kafka-metrics with Apache License 2.0 6 votes vote down vote up
private ObjectNode newPanel(ArrayNode rowPanels, String title, int span, String type) {
    ObjectNode panel = rowPanels.addObject();
    panel.put("title", title);
    panel.put("span", span);
    panel.put("id", ++numPanels);
    panel.put("datasource", dataSource);
    panel.put("type", type);
    panel.put("renderer", "flot");
    //
    panel.put("timeFrom", (String) null);
    panel.put("timeShift", (String) null);

    //
    panel.put("editable", true);
    panel.put("error", false);
    panel.put("isNew", true);
    //
    panel.set("targets", mapper.createArrayNode());
    return panel;
}
 
Example 3
Source File: BpmnLoggingSessionUtil.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public static void addTaskIdentityLinkData(String type, String message, boolean isUser, List<IdentityLinkEntity> identityLinkEntities, 
                TaskEntity task, DelegateExecution execution) {
    
    ObjectNode loggingNode = fillBasicTaskLoggingData(message, task, execution);
    ArrayNode identityLinkArray = null;
    if (isUser) {
        identityLinkArray = loggingNode.putArray("taskUserIdentityLinks");
    } else {
        identityLinkArray = loggingNode.putArray("taskGroupIdentityLinks");
    }
    
    for (IdentityLinkEntity identityLink : identityLinkEntities) {
        ObjectNode identityLinkNode = identityLinkArray.addObject();
        identityLinkNode.put("id", identityLink.getId());
        identityLinkNode.put("type", identityLink.getType());
        if (isUser) {
            identityLinkNode.put("userId", identityLink.getUserId());
        } else {
            identityLinkNode.put("groupId", identityLink.getGroupId());
        }
    }
    
    LoggingSessionUtil.addLoggingData(type, loggingNode);
}
 
Example 4
Source File: AmbariClustersHostsResponse.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void addComponentNode(ObjectNode dataNode, String category, String componentName, String serviceName, String hostName) {
    ArrayNode dataNodeComponents = dataNode.putArray("component");
    ObjectNode componentNode = dataNodeComponents.addObject();
    componentNode.putObject("ServiceComponentInfo")
            .put("category", category)
            .put("cluster_name", "clustername")
            .put("component_name", componentName)
            .put("service_name", serviceName);
}
 
Example 5
Source File: GetDataAvailabilityJsonEncoder.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
private void encodeObservationFormatDescriptor(Set<ObservationFormatDescriptor> observationFormatDescriptors,
        ObjectNode fdNode) {
    ArrayNode ofdArray = fdNode.putArray(GetDataAvailabilityConstants.OBSERVATION_FORMAT_DESCRIPTOR);
    for (ObservationFormatDescriptor ofd : observationFormatDescriptors) {
        ObjectNode ofdNode = ofdArray.addObject();
        ofdNode.put(GetDataAvailabilityConstants.RESPONSE_FORMAT, ofd.getResponseFormat());
        ArrayNode otArray = ofdNode.putArray(GetDataAvailabilityConstants.OBSERVATION_TYPE);
        for (String obsType : ofd.getObservationTypes()) {
            otArray.add(obsType);
        }
    }
}
 
Example 6
Source File: CaseInstanceVariablesCollectionResourceTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Test creating multiple case variables in a single call. POST cmmn-runtime/case-instance/{caseInstanceId}/variables?override=true
 */
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/repository/oneHumanTaskCase.cmmn" })
public void testCreateMultipleCaseVariablesWithOverride() throws Exception {

    CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").start();
    runtimeService.setVariable(caseInstance.getId(), "stringVariable", "initialValue");
    ArrayNode requestNode = objectMapper.createArrayNode();

    // String variable
    ObjectNode stringVarNode = requestNode.addObject();
    stringVarNode.put("name", "stringVariable");
    stringVarNode.put("value", "simple string value");
    stringVarNode.put("type", "string");

    ObjectNode anotherVariable = requestNode.addObject();
    anotherVariable.put("name", "stringVariable2");
    anotherVariable.put("value", "another string value");
    anotherVariable.put("type", "string");

    // Create local variables with a single request
    HttpPut httpPut = new HttpPut(
            SERVER_URL_PREFIX + CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_CASE_INSTANCE_VARIABLE_COLLECTION, caseInstance.getId()));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_CREATED);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertThat(responseNode).isNotNull();
    assertThat(responseNode.isArray()).isTrue();
    assertThat(responseNode).hasSize(2);

    // Check if engine has correct variables set
    Map<String, Object> variables = runtimeService.getVariables(caseInstance.getId());
    assertThat(variables).hasSize(2);

    assertThat(variables.get("stringVariable")).isEqualTo("simple string value");
    assertThat(variables.get("stringVariable2")).isEqualTo("another string value");
}
 
Example 7
Source File: CopyingFormat.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private static JsonNode getOrCreateNode(JsonNode node, String key, boolean getObjectNode){
    if (node instanceof  ObjectNode) {
        ObjectNode obj = (ObjectNode) node;
        return obj.has(key) ? obj.get(key) : getObjectNode ? obj.putObject(key) : obj.putArray(key);
    } else if (node instanceof ArrayNode) {
        ArrayNode arrayNode = (ArrayNode) node;
        return getObjectNode ? arrayNode.addObject() : arrayNode.addArray();
    }

    return null;
}
 
Example 8
Source File: NavigateResponseConverter.java    From graphhopper-navigation with Apache License 2.0 5 votes vote down vote up
private static void putSingleBannerInstruction(Instruction instruction, Locale locale, TranslationMap translationMap, ObjectNode singleBannerInstruction) {
    String bannerInstructionName = instruction.getName();
    if (bannerInstructionName == null || bannerInstructionName.isEmpty()) {
        // Fix for final instruction and for instructions without name
        bannerInstructionName = instruction.getTurnDescription(translationMap.getWithFallBack(locale));

        // Uppercase first letter
        // TODO: should we do this for all cases? Then we might change the spelling of street names though
        bannerInstructionName = Helper.firstBig(bannerInstructionName);
    }

    singleBannerInstruction.put("text", bannerInstructionName);

    ArrayNode components = singleBannerInstruction.putArray("components");
    ObjectNode component = components.addObject();
    component.put("text", bannerInstructionName);
    component.put("type", "text");

    singleBannerInstruction.put("type", getTurnType(instruction, false));
    String modifier = getModifier(instruction);
    if (modifier != null)
        singleBannerInstruction.put("modifier", modifier);

    if (instruction.getSign() == Instruction.USE_ROUNDABOUT) {
        if (instruction instanceof RoundaboutInstruction) {
            double turnAngle = ((RoundaboutInstruction) instruction).getTurnAngle();
            if (Double.isNaN(turnAngle)) {
                singleBannerInstruction.putNull("degrees");
            } else {
                double degree = (Math.abs(turnAngle) * 180) / Math.PI;
                singleBannerInstruction.put("degrees", degree);
            }
        }
    }
}
 
Example 9
Source File: BpmnJsonConverterUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public static void convertMessagesToJson(BpmnModel bpmnModel, ObjectNode propertiesNode) {
    if (bpmnModel.getMessages() != null) {
        ArrayNode messageDefinitions = objectMapper.createArrayNode();
        for (Message message : bpmnModel.getMessages()) {
            ObjectNode messageNode = messageDefinitions.addObject();
            messageNode.put(PROPERTY_MESSAGE_DEFINITION_ID, message.getId());
            messageNode.put(PROPERTY_MESSAGE_DEFINITION_NAME, message.getName());
        }
        propertiesNode.set(PROPERTY_MESSAGE_DEFINITIONS, messageDefinitions);
    }
}
 
Example 10
Source File: EventJsonConverter.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public String convertToJson(EventModel definition) {
    ObjectNode modelNode = objectMapper.createObjectNode();

    if (definition.getKey() != null) {
        modelNode.put("key", definition.getKey());
    }

    if (definition.getName() != null) {
        modelNode.put("name", definition.getName());
    }

    Collection<EventPayload> payload = definition.getPayload();
    if (!payload.isEmpty()) {
        ArrayNode payloadNode = modelNode.putArray("payload");
        for (EventPayload eventPayload : payload) {
            ObjectNode eventPayloadNode = payloadNode.addObject();
            if (eventPayload.getName() != null) {
                eventPayloadNode.put("name", eventPayload.getName());
            }

            if (eventPayload.getType() != null) {
                eventPayloadNode.put("type", eventPayload.getType());
            }

            if (eventPayload.isCorrelationParameter()) {
                eventPayloadNode.put("correlationParameter", true);
            }
        }
    }

    try {
        return objectMapper.writeValueAsString(modelNode);
    } catch (Exception e) {
        throw new FlowableEventJsonException("Error writing event json", e);
    }
}
 
Example 11
Source File: NavigateResponseConverter.java    From graphhopper-navigation with Apache License 2.0 5 votes vote down vote up
private static void putRouteInformation(ObjectNode pathJson, ResponsePath path, int routeNr, TranslationMap translationMap, TranslationMap navigateResponseConverterTranslationMap, Locale locale, DistanceConfig distanceConfig) {
    InstructionList instructions = path.getInstructions();

    pathJson.put("geometry", WebHelper.encodePolyline(path.getPoints(), false, 1e6));
    ArrayNode legsJson = pathJson.putArray("legs");

    ObjectNode legJson = legsJson.addObject();
    ArrayNode steps = legJson.putArray("steps");

    long time = 0;
    double distance = 0;
    boolean isFirstInstructionOfLeg = true;

    for (int i = 0; i < instructions.size(); i++) {
        ObjectNode instructionJson = steps.addObject();
        putInstruction(instructions, i, locale, translationMap, navigateResponseConverterTranslationMap, instructionJson, isFirstInstructionOfLeg, distanceConfig);
        Instruction instruction = instructions.get(i);
        time += instruction.getTime();
        distance += instruction.getDistance();
        isFirstInstructionOfLeg = false;
        if (instruction.getSign() == Instruction.REACHED_VIA || instruction.getSign() == Instruction.FINISH) {
            putLegInformation(legJson, path, routeNr, time, distance);
            isFirstInstructionOfLeg = true;
            time = 0;
            distance = 0;

            if (instruction.getSign() == Instruction.REACHED_VIA) {
                // Create new leg and steps after a via points
                legJson = legsJson.addObject();
                steps = legJson.putArray("steps");
            }
        }
    }

    pathJson.put("weight_name", "routability");
    pathJson.put("weight", Helper.round(path.getRouteWeight(), 1));
    pathJson.put("duration", convertToSeconds(path.getTime()));
    pathJson.put("distance", Helper.round(path.getDistance(), 1));
    pathJson.put("voiceLocale", locale.toLanguageTag());
}
 
Example 12
Source File: SignalsResourceTest.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@Deployment(resources = { "org/activiti/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml" })
public void testSignalEventReceivedSync() throws Exception {

  org.activiti.engine.repository.Deployment tenantDeployment = repositoryService.createDeployment()
      .addClasspathResource("org/activiti/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml").tenantId("my tenant").deploy();

  try {

    // Signal without vars, without tenant
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("signalName", "The Signal");

    HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_SIGNALS));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

    // Check if process is started as a result of the signal without
    // tenant ID set
    assertEquals(1, runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId().processDefinitionKey("processWithSignalStart1").count());

    // Signal with tenant
    requestNode.put("tenantId", "my tenant");
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

    // Check if process is started as a result of the signal, in the
    // right tenant
    assertEquals(1, runtimeService.createProcessInstanceQuery().processInstanceTenantId("my tenant").processDefinitionKey("processWithSignalStart1").count());

    // Signal with tenant AND variables
    ArrayNode vars = requestNode.putArray("variables");
    ObjectNode var = vars.addObject();
    var.put("name", "testVar");
    var.put("value", "test");

    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

    // Check if process is started as a result of the signal, in the
    // right tenant and with var set
    assertEquals(1, runtimeService.createProcessInstanceQuery().processInstanceTenantId("my tenant").processDefinitionKey("processWithSignalStart1").variableValueEquals("testVar", "test").count());

    // Signal without tenant AND variables
    requestNode.remove("tenantId");

    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

    // Check if process is started as a result of the signal, witout
    // tenant and with var set
    assertEquals(1, runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId().processDefinitionKey("processWithSignalStart1").variableValueEquals("testVar", "test").count());

  } finally {
    // Clean up tenant-specific deployment
    if (tenantDeployment != null) {
      repositoryService.deleteDeployment(tenantDeployment.getId(), true);
    }
  }
}
 
Example 13
Source File: TableViewPreferencesIOUtilities.java    From constellation with Apache License 2.0 4 votes vote down vote up
/**
 * Save details of the currently displayed tables displayed columns and
 * their order as well as details of any sorting being performed on it. The
 * user will be prompted for a name to save the configuration file as which
 * will be appended to a tag indicating the type of content being displayed
 * in the table.
 *
 * @param tableType Indication of whether the table is displaying in vertex
 * of transaction mode.
 * @param table the tables content.
 */
public static void savePreferences(GraphElementType tableType, final TableView<ObservableList<String>> table) {
    final Preferences prefs = NbPreferences.forModule(ApplicationPreferenceKeys.class);
    final String userDir = ApplicationPreferenceKeys.getUserDir(prefs);
    final File prefDir = new File(userDir, TABLE_VIEW_PREF_DIR);
    String filePrefix = (tableType == GraphElementType.VERTEX ? VERTEX_FILE_PREFIX : TRANSACTION_FILE_PREFIX);
    final ObservableList<TableColumn<ObservableList<String>, ?>> columns = table.getColumns();

    // Ensure preferences directory exists.
    if (!prefDir.exists()) {
        prefDir.mkdir();
    }
    if (!prefDir.isDirectory()) {
        final String msg = String.format("Can't create data access directory '%s'.", prefDir);
        final NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE);
        DialogDisplayer.getDefault().notify(nd);
        return;
    }

    // Create the core structure of the JSON object containing nodes for the key characteristics
    // of the graph that are being saved
    final ObjectMapper mapper = new ObjectMapper();
    final ArrayNode rootNode = mapper.createArrayNode();
    final ObjectNode global = rootNode.addObject();
    final ArrayNode colOrderArrayNode = global.putArray(COLUMN_ORDER_NODE);
    final ObjectNode colSortNode = global.putObject(COLUMN_SORT_NODE);

    // Populate elements of JSON structure based on supplied graph information
    int i = 0;
    while (i < columns.size() && columns.get(i).isVisible()) {
        colOrderArrayNode.add(columns.get(i).getText());
        i++;
    }

    // Store details of the column being sorted by, and its direction if sorting has been enabled.
    // The node will cotain a name/value pair, the name representing the column name, the value
    // representing the direction.
    if (!table.getSortOrder().isEmpty()) {
        colSortNode.put(table.getSortOrder().get(0).getText(), table.getSortOrder().get(0).getSortType().name());
    } else {
        // the table isn't being sorted by any column so don't save anything
        colSortNode.put("", "");
    }
    JsonIO.saveJsonPreferences(TABLE_VIEW_PREF_DIR, mapper, rootNode, filePrefix);
}
 
Example 14
Source File: NavigateResponseConverter.java    From graphhopper-navigation with Apache License 2.0 4 votes vote down vote up
private static ObjectNode putInstruction(InstructionList instructions, int index, Locale locale, TranslationMap translationMap, TranslationMap navigateResponseConverterTranslationMap, ObjectNode instructionJson, boolean isFirstInstructionOfLeg, DistanceConfig distanceConfig) {
    Instruction instruction = instructions.get(index);
    ArrayNode intersections = instructionJson.putArray("intersections");
    ObjectNode intersection = intersections.addObject();
    intersection.putArray("entry");
    intersection.putArray("bearings");
    //Make pointList mutable
    PointList pointList = instruction.getPoints().clone(false);

    if (index + 2 < instructions.size()) {
        // Add the first point of the next instruction
        PointList nextPoints = instructions.get(index + 1).getPoints();
        pointList.add(nextPoints.getLat(0), nextPoints.getLon(0), nextPoints.getEle(0));
    } else if (pointList.size() == 1) {
        // Duplicate the last point in the arrive instruction, if the size is 1
        pointList.add(pointList.getLat(0), pointList.getLon(0), pointList.getEle(0));
    }

    putLocation(pointList.getLat(0), pointList.getLon(0), intersection);

    instructionJson.put("driving_side", "right");

    // Does not include elevation
    instructionJson.put("geometry", WebHelper.encodePolyline(pointList, false, 1e6));

    // TODO: how about other modes?
    instructionJson.put("mode", "driving");

    putManeuver(instruction, instructionJson, locale, translationMap, isFirstInstructionOfLeg);

    // TODO distance = weight, is weight even important?
    double distance = Helper.round(instruction.getDistance(), 1);
    instructionJson.put("weight", distance);
    instructionJson.put("duration", convertToSeconds(instruction.getTime()));
    instructionJson.put("name", instruction.getName());
    instructionJson.put("distance", distance);

    ArrayNode voiceInstructions = instructionJson.putArray("voiceInstructions");
    ArrayNode bannerInstructions = instructionJson.putArray("bannerInstructions");

    // Voice and banner instructions are empty for the last element
    if (index + 1 < instructions.size()) {
        putVoiceInstructions(instructions, distance, index, locale, translationMap, navigateResponseConverterTranslationMap, voiceInstructions, distanceConfig);
        putBannerInstructions(instructions, distance, index, locale, translationMap, bannerInstructions);
    }

    return instructionJson;
}
 
Example 15
Source File: SignalsResourceTest.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@Deployment(resources = { "org/activiti/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml" })
public void testSignalEventReceivedAsync() throws Exception {

  org.activiti.engine.repository.Deployment tenantDeployment = repositoryService.createDeployment()
      .addClasspathResource("org/activiti/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml").tenantId("my tenant").deploy();

  try {

    // Signal without vars, without tenant
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("signalName", "The Signal");
    requestNode.put("async", true);

    HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_SIGNALS));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_ACCEPTED));

    // Check if job is queued as a result of the signal without tenant
    // ID set
    assertEquals(1, managementService.createJobQuery().jobWithoutTenantId().count());

    // Signal with tenant
    requestNode.put("tenantId", "my tenant");
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_ACCEPTED));

    // Check if job is queued as a result of the signal, in the right
    // tenant
    assertEquals(1, managementService.createJobQuery().jobTenantId("my tenant").count());

    // Signal with variables and async, should fail as it's not
    // supported
    ArrayNode vars = requestNode.putArray("variables");
    ObjectNode var = vars.addObject();
    var.put("name", "testVar");
    var.put("value", "test");

    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));

  } finally {
    // Clean up tenant-specific deployment
    if (tenantDeployment != null) {
      repositoryService.deleteDeployment(tenantDeployment.getId(), true);
    }

    // Clear jobs
    List<Job> jobs = managementService.createJobQuery().list();
    for (Job job : jobs) {
      managementService.deleteJob(job.getId());
    }
  }
}
 
Example 16
Source File: ProcessInstanceVariablesCollectionResourceTest.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
/**
 * Test creating a single process variable, testing default types when omitted. POST runtime/process-instances/{processInstanceId}/variables
 */
@Deployment(resources = { "org/activiti/rest/service/api/runtime/ProcessInstanceVariablesCollectionResourceTest.testProcess.bpmn20.xml" })
public void testCreateSingleProcessVariableDefaultTypes() throws Exception {
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

  // String type detection
  ArrayNode requestNode = objectMapper.createArrayNode();
  ObjectNode varNode = requestNode.addObject();
  varNode.put("name", "stringVar");
  varNode.put("value", "String value");

  HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_VARIABLE_COLLECTION, processInstance.getId()));
  httpPost.setEntity(new StringEntity(requestNode.toString()));
  closeResponse(executeRequest(httpPost, HttpStatus.SC_CREATED));

  assertEquals("String value", runtimeService.getVariable(processInstance.getId(), "stringVar"));

  // Integer type detection
  varNode.put("name", "integerVar");
  varNode.put("value", 123);

  httpPost.setEntity(new StringEntity(requestNode.toString()));
  closeResponse(executeRequest(httpPost, HttpStatus.SC_CREATED));

  assertEquals(123, runtimeService.getVariable(processInstance.getId(), "integerVar"));

  // Double type detection
  varNode.put("name", "doubleVar");
  varNode.put("value", 123.456);

  httpPost.setEntity(new StringEntity(requestNode.toString()));
  closeResponse(executeRequest(httpPost, HttpStatus.SC_CREATED));

  assertEquals(123.456, runtimeService.getVariable(processInstance.getId(), "doubleVar"));

  // Boolean type detection
  varNode.put("name", "booleanVar");
  varNode.put("value", Boolean.TRUE);

  httpPost.setEntity(new StringEntity(requestNode.toString()));
  closeResponse(executeRequest(httpPost, HttpStatus.SC_CREATED));

  assertEquals(Boolean.TRUE, runtimeService.getVariable(processInstance.getId(), "booleanVar"));
}
 
Example 17
Source File: ProcessInstanceVariablesCollectionResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Test creating a single process variable, testing default types when omitted. POST runtime/process-instances/{processInstanceId}/variables
 */
@Test
@Deployment(resources = { "org/flowable/rest/service/api/runtime/ProcessInstanceVariablesCollectionResourceTest.testProcess.bpmn20.xml" })
public void testCreateSingleProcessVariableDefaultTypes() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

    // String type detection
    ArrayNode requestNode = objectMapper.createArrayNode();
    ObjectNode varNode = requestNode.addObject();
    varNode.put("name", "stringVar");
    varNode.put("value", "String value");

    HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_VARIABLE_COLLECTION, processInstance.getId()));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_CREATED));

    assertThat(runtimeService.getVariable(processInstance.getId(), "stringVar")).isEqualTo("String value");

    // Integer type detection
    varNode.put("name", "integerVar");
    varNode.put("value", 123);

    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_CREATED));

    assertThat(runtimeService.getVariable(processInstance.getId(), "integerVar")).isEqualTo(123);

    // Double type detection
    varNode.put("name", "doubleVar");
    varNode.put("value", 123.456);

    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_CREATED));

    assertThat(runtimeService.getVariable(processInstance.getId(), "doubleVar")).isEqualTo(123.456);

    // Boolean type detection
    varNode.put("name", "booleanVar");
    varNode.put("value", Boolean.TRUE);

    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_CREATED));

    assertThat(runtimeService.getVariable(processInstance.getId(), "booleanVar")).isEqualTo(Boolean.TRUE);
}
 
Example 18
Source File: CaseInstanceCollectionResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/runtime/oneHumanTaskCaseWithStartForm.cmmn",
        "org/flowable/cmmn/rest/service/api/runtime/simple.form" })
public void testStartCaseWithForm() throws Exception {
    CaseDefinition caseDefinition = repositoryService.createCaseDefinitionQuery().caseDefinitionKey("oneHumanTaskCase").singleResult();
    try {
        FormDefinition formDefinition = formRepositoryService.createFormDefinitionQuery().formDefinitionKey("form1").singleResult();
        assertThat(formDefinition).isNotNull();

        FormInstance formInstance = formEngineFormService.createFormInstanceQuery().formDefinitionId(formDefinition.getId()).singleResult();
        assertThat(formInstance).isNull();

        String url = CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_CASE_DEFINITION_START_FORM, caseDefinition.getId());
        CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertThatJson(responseNode)
                .when(Option.IGNORING_EXTRA_FIELDS)
                .isEqualTo("{"
                        + " id: '" + formDefinition.getId() + "',"
                        + " key: '" + formDefinition.getKey() + "',"
                        + " name: '" + formDefinition.getName() + "'"
                        + "}");
        assertThat(responseNode.get("fields")).hasSize(2);

        ArrayNode formVariablesNode = objectMapper.createArrayNode();

        // String variable
        ObjectNode stringVarNode = formVariablesNode.addObject();
        stringVarNode.put("name", "user");
        stringVarNode.put("value", "simple string value");
        stringVarNode.put("type", "string");

        ObjectNode integerVarNode = formVariablesNode.addObject();
        integerVarNode.put("name", "number");
        integerVarNode.put("value", 1234);
        integerVarNode.put("type", "integer");

        ObjectNode requestNode = objectMapper.createObjectNode();

        // Start using case definition key
        requestNode.put("caseDefinitionKey", "oneHumanTaskCase");
        requestNode.set("startFormVariables", formVariablesNode);

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_CASE_INSTANCE_COLLECTION));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        response = executeRequest(httpPost, HttpStatus.SC_CREATED);

        CaseInstance caseInstance = runtimeService.createCaseInstanceQuery().singleResult();
        assertThat(caseInstance).isNotNull();

        assertThat(runtimeService.getVariable(caseInstance.getId(), "user")).isEqualTo("simple string value");
        assertThat(runtimeService.getVariable(caseInstance.getId(), "number")).isEqualTo(1234);

        formInstance = formEngineFormService.createFormInstanceQuery().formDefinitionId(formDefinition.getId()).singleResult();
        assertThat(formInstance).isNotNull();
        byte[] valuesBytes = formEngineFormService.getFormInstanceValues(formInstance.getId());
        assertThat(valuesBytes).isNotNull();
        JsonNode instanceNode = objectMapper.readTree(valuesBytes);
        JsonNode valuesNode = instanceNode.get("values");
        assertThatJson(valuesNode)
                .when(Option.IGNORING_EXTRA_FIELDS)
                .isEqualTo("{"
                        + " user: 'simple string value',"
                        + " number: '1234'"
                        + "}");

    } finally {
        formEngineFormService.deleteFormInstancesByScopeDefinition(caseDefinition.getId());

        List<FormDeployment> formDeployments = formRepositoryService.createDeploymentQuery().list();
        for (FormDeployment formDeployment : formDeployments) {
            formRepositoryService.deleteDeployment(formDeployment.getId(), true);
        }
    }
}
 
Example 19
Source File: SignalsResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@Deployment(resources = { "org/flowable/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml" })
public void testSignalEventReceivedAsync() throws Exception {

    org.flowable.engine.repository.Deployment tenantDeployment = repositoryService.createDeployment()
            .addClasspathResource("org/flowable/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml").tenantId("my tenant").deploy();

    try {

        // Signal without vars, without tenant
        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("signalName", "The Signal");
        requestNode.put("async", true);

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_SIGNALS));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_ACCEPTED));

        // Check if job is queued as a result of the signal without tenant ID set
        assertThat(managementService.createJobQuery().jobWithoutTenantId().count()).isEqualTo(1);

        // Signal with tenant
        requestNode.put("tenantId", "my tenant");
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_ACCEPTED));

        // Check if job is queued as a result of the signal, in the right tenant
        assertThat(managementService.createJobQuery().jobTenantId("my tenant").count()).isEqualTo(1);

        // Signal with variables and async, should fail as it's not supported
        ArrayNode vars = requestNode.putArray("variables");
        ObjectNode var = vars.addObject();
        var.put("name", "testVar");
        var.put("value", "test");

        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));

    } finally {
        // Clean up tenant-specific deployment
        if (tenantDeployment != null) {
            repositoryService.deleteDeployment(tenantDeployment.getId(), true);
        }

        // Clear jobs
        List<Job> jobs = managementService.createJobQuery().list();
        for (Job job : jobs) {
            managementService.deleteJob(job.getId());
        }
    }
}
 
Example 20
Source File: SignalsResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@Deployment(resources = { "org/flowable/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml" })
public void testSignalEventReceivedSync() throws Exception {

    org.flowable.engine.repository.Deployment tenantDeployment = repositoryService.createDeployment()
            .addClasspathResource("org/flowable/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml").tenantId("my tenant").deploy();

    try {

        // Signal without vars, without tenant
        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("signalName", "The Signal");

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_SIGNALS));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

        // Check if process is started as a result of the signal without tenant ID set
        assertThat(runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId().processDefinitionKey("processWithSignalStart1").count())
                .isEqualTo(1);

        // Signal with tenant
        requestNode.put("tenantId", "my tenant");
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

        // Check if process is started as a result of the signal, in the right tenant
        assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantId("my tenant").processDefinitionKey("processWithSignalStart1").count())
                .isEqualTo(1);

        // Signal with tenant AND variables
        ArrayNode vars = requestNode.putArray("variables");
        ObjectNode var = vars.addObject();
        var.put("name", "testVar");
        var.put("value", "test");

        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

        // Check if process is started as a result of the signal, in the right tenant and with var set
        assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantId("my tenant").processDefinitionKey("processWithSignalStart1")
                .variableValueEquals("testVar", "test").count()).isEqualTo(1);

        // Signal without tenant AND variables
        requestNode.remove("tenantId");

        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

        // Check if process is started as a result of the signal, without tenant and with var set
        assertThat(runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId().processDefinitionKey("processWithSignalStart1")
                .variableValueEquals("testVar", "test").count()).isEqualTo(1);

    } finally {
        // Clean up tenant-specific deployment
        if (tenantDeployment != null) {
            repositoryService.deleteDeployment(tenantDeployment.getId(), true);
        }
    }
}