Example usage for com.fasterxml.jackson.databind JsonNode size

List of usage examples for com.fasterxml.jackson.databind JsonNode size

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode size.

Prototype

public int size() 

Source Link

Usage

From source file:org.apache.drill.exec.store.http.HttpRecordReader.java

private void parseResult(String content) {
    String key = scanSpec.getResultKey();
    JsonNode root = (key == null || key.length() == 0) ? JsonConverter.parse(content)
            : JsonConverter.parse(content, key);
    if (root != null) {
        logger.debug("response object count {}", root.size());
        jsonIt = root.elements();//from w  w w  . j a v  a 2  s .c  o  m
    }
}

From source file:com.unboundid.scim2.common.utils.JsonDiff.java

/**
 * Generate a value filter that may be used to uniquely identify this value
 * in an array node.//from  w w  w  .  j  a va2s.  co m
 *
 * @param value The value to generate a filter from.
 * @return The value filter or {@code null} if a value filter can not be used
 *         to uniquely identify the node.
 */
private Filter generateValueFilter(final JsonNode value) {
    if (value.isValueNode()) {
        // Use the implicit "value" sub-attribute to reference this value.
        return Filter.eq(Path.root().attribute("value"), (ValueNode) value);
    }
    if (value.isObject()) {
        List<Filter> filters = new ArrayList<Filter>(value.size());
        Iterator<Map.Entry<String, JsonNode>> fieldsIterator = value.fields();
        while (fieldsIterator.hasNext()) {
            Map.Entry<String, JsonNode> field = fieldsIterator.next();
            if (!field.getValue().isValueNode()) {
                // We can't nest value filters.
                return null;
            }
            filters.add(Filter.eq(Path.root().attribute(field.getKey()), (ValueNode) field.getValue()));
        }

        if (filters.size() == 0) {
            return null;
        } else if (filters.size() == 1) {
            return filters.get(0);
        } else {
            return Filter.and(filters);
        }
    }

    // We can't uniquely identify this value with a filter.
    return null;
}

From source file:de.undercouch.bson4jackson.BsonParserTest.java

/**
 * Tests reading an embedded document through
 * {@link BsonParser#readValueAsTree()}. Refers issue #9
 * @throws Exception if something went wrong
 * @author audistard/*  w  ww. j av a  2 s  .  c o m*/
 */
@Test
public void parseEmbeddedDocumentAsTree() throws Exception {
    BSONObject o2 = new BasicBSONObject();
    o2.put("Int64", 10L);

    BSONObject o3 = new BasicBSONObject();
    o3.put("Int64", 11L);

    BSONObject o1 = new BasicBSONObject();
    o1.put("Obj2", o2);
    o1.put("Obj3", o3);

    BSONEncoder enc = new BasicBSONEncoder();
    byte[] b = enc.encode(o1);

    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    BsonFactory fac = new BsonFactory();
    ObjectMapper mapper = new ObjectMapper(fac);
    fac.setCodec(mapper);

    BsonParser dec = fac.createParser(bais);

    assertEquals(JsonToken.START_OBJECT, dec.nextToken());

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Obj2", dec.getCurrentName());
    assertEquals(JsonToken.START_OBJECT, dec.nextToken());
    JsonNode obj2 = dec.readValueAsTree();
    assertEquals(1, obj2.size());
    assertNotNull(obj2.get("Int64"));
    assertEquals(10L, obj2.get("Int64").longValue());

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Obj3", dec.getCurrentName());
    assertEquals(JsonToken.START_OBJECT, dec.nextToken());

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Int64", dec.getCurrentName());
    assertEquals(JsonToken.VALUE_NUMBER_INT, dec.nextToken());
    assertEquals(11L, dec.getLongValue());

    assertEquals(JsonToken.END_OBJECT, dec.nextToken());

    assertEquals(JsonToken.END_OBJECT, dec.nextToken());
}

From source file:org.bedework.notifier.outbound.email.EmailAdaptor.java

private List<TemplateResult> applyTemplates(final Action action) throws NoteException {
    final Note note = action.getNote();
    final NotificationType nt = note.getNotification();
    final EmailSubscription sub = EmailSubscription.rewrap(action.getSub());

    List<TemplateResult> results = new ArrayList<TemplateResult>();
    try {// w ww.ja  v a  2 s  .c o  m
        String prefix = nt.getParsed().getDocumentElement().getPrefix();

        if (prefix == null) {
            prefix = "default";
        }

        final String abstractPath = Util.buildPath(false, Note.DeliveryMethod.email.toString(), "/", prefix,
                "/", nt.getNotification().getElementName().getLocalPart());

        File templateDir = new File(Util.buildPath(false, globalConfig.getTemplatesPath(), "/", abstractPath));
        if (templateDir.isDirectory()) {

            Map<String, Object> root = new HashMap<String, Object>();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(nt.toXml(true))));
            Element el = doc.getDocumentElement();
            NodeModel.simplify(el);
            NodeModel.useJaxenXPathSupport();
            root.put("notification", el);

            HashSet<String> recipients = new HashSet<String>();
            for (String email : sub.getEmails()) {
                recipients.add(MAILTO + email);
            }
            root.put("recipients", recipients);

            if (globalConfig.getCardDAVHost() != null && globalConfig.getCardDAVPort() != 0
                    && globalConfig.getCardDAVContextPath() != null) {
                HashMap<String, Object> vcards = new HashMap<String, Object>();
                BasicHttpClient client;
                try {
                    ArrayList<Header> hdrs = new ArrayList<Header>();
                    BasicHeader h = new BasicHeader(HEADER_ACCEPT, globalConfig.getVCardContentType());
                    hdrs.add(h);

                    client = new BasicHttpClient(globalConfig.getCardDAVHost(), globalConfig.getCardDAVPort(),
                            null, 15 * 1000);

                    XPathExpression exp = xPath.compile("//*[local-name() = 'href']");
                    NodeList nl = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);

                    HashSet<String> vcardLookups = new HashSet<String>();
                    for (int i = 0; i < nl.getLength(); i++) {
                        Node n = nl.item(i);
                        String text = n.getTextContent();

                        text = pMailto.matcher(text).replaceFirst(MAILTO);
                        if (text.startsWith(MAILTO)
                                || text.startsWith(globalConfig.getCardDAVPrincipalsPath())) {
                            vcardLookups.add(text);
                        }
                    }

                    // Get vCards for recipients too. They may not be referenced in the notification.
                    vcardLookups.addAll(recipients);

                    for (String lookup : vcardLookups) {
                        String path = Util.buildPath(false,
                                globalConfig.getCardDAVContextPath() + "/" + lookup.replace(':', '/'));

                        final InputStream is = client.get(path + VCARD_SUFFIX, "application/text", hdrs);
                        if (is != null) {
                            ObjectMapper om = new ObjectMapper();
                            @SuppressWarnings("unchecked")
                            ArrayList<Object> hm = om.readValue(is, ArrayList.class);
                            vcards.put(lookup, hm);
                        }
                    }
                    root.put("vcards", vcards);
                } catch (final Throwable t) {
                    error(t);
                }
            }

            if (nt.getNotification() instanceof ResourceChangeType) {
                ResourceChangeType chg = (ResourceChangeType) nt.getNotification();
                BedeworkConnectorConfig cfg = ((BedeworkConnector) action.getConn()).getConnectorConfig();
                BasicHttpClient cl = getClient(cfg);
                List<Header> hdrs = getHeaders(cfg, new BedeworkSubscription(action.getSub()));

                String href = null;
                if (chg.getCreated() != null) {
                    href = chg.getCreated().getHref();
                } else if (chg.getDeleted() != null) {
                    href = chg.getDeleted().getHref();
                } else if (chg.getUpdated() != null && chg.getUpdated().size() > 0) {
                    href = chg.getUpdated().get(0).getHref();
                }

                if (href != null) {
                    if (chg.getDeleted() == null) {
                        // We only have an event for the templates on a create or update, not on delete.
                        ObjectMapper om = new ObjectMapper();
                        final InputStream is = cl.get(cfg.getSystemUrl() + href, null, hdrs);
                        JsonNode a = om.readValue(is, JsonNode.class);

                        // Check for a recurrence ID on this notification.
                        XPathExpression exp = xPath.compile("//*[local-name() = 'recurrenceid']/text()");
                        String rid = exp.evaluate(doc);
                        if (rid != null && !rid.isEmpty()) {
                            Calendar rcal = Calendar.getInstance();
                            recurIdFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                            rcal.setTime(recurIdFormat.parse(rid));

                            // Find the matching recurrence ID in the JSON, and make that the only vevent object.
                            Calendar c = Calendar.getInstance();
                            ArrayNode vevents = (ArrayNode) a.get(2);
                            for (JsonNode vevent : vevents) {
                                if (vevent.size() > 1 && vevent.get(1).size() > 1) {
                                    JsonNode n = vevent.get(1).get(0);
                                    if (n.get(0).asText().equals("recurrence-id")) {
                                        if (n.get(1).size() > 0 && n.get(1).get("tzid") != null) {
                                            jsonIdFormatTZ.setTimeZone(
                                                    TimeZone.getTimeZone(n.get(1).get("tzid").asText()));
                                            c.setTime(jsonIdFormatTZ.parse(n.get(3).asText()));
                                        } else {
                                            jsonIdFormatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
                                            c.setTime(jsonIdFormatUTC.parse(n.get(3).asText()));
                                        }
                                        if (rcal.compareTo(c) == 0) {
                                            vevents.removeAll();
                                            vevents.add(vevent);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        root.put("vevent", (ArrayList<Object>) om.convertValue(a, ArrayList.class));
                    }

                    // TODO: Provide some calendar information to the templates. This is currently the publisher's
                    // calendar, but needs to be fixed to be the subscriber's calendar.
                    String chref = href.substring(0, href.lastIndexOf("/"));
                    hdrs.add(new BasicHeader(HEADER_DEPTH, "0"));
                    int rc = cl.sendRequest("PROPFIND", cfg.getSystemUrl() + chref, hdrs, "text/xml",
                            CALENDAR_PROPFIND.length(), CALENDAR_PROPFIND.getBytes());
                    if (rc == HttpServletResponse.SC_OK || rc == SC_MULTISTATUS) {
                        Document d = builder.parse(new InputSource(cl.getResponseBodyAsStream()));
                        HashMap<String, String> hm = new HashMap<String, String>();
                        XPathExpression exp = xPath.compile("//*[local-name() = 'href']/text()");
                        hm.put("href", exp.evaluate(d));
                        exp = xPath.compile("//*[local-name() = 'displayname']/text()");
                        hm.put("name", (String) exp.evaluate(d));
                        exp = xPath.compile("//*[local-name() = 'calendar-description']/text()");
                        hm.put("description", (String) exp.evaluate(d));
                        root.put("calendar", hm);
                    }
                }
            }

            if (note.getExtraValues() != null) {
                root.putAll(note.getExtraValues());
            }

            DefaultObjectWrapper wrapper = new DefaultObjectWrapperBuilder(
                    Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build();
            root.put("timezone", (TemplateHashModel) wrapper.getStaticModels().get("java.util.TimeZone"));

            // Sort files so the user can control the order of content types/body parts of the email by template file name.
            File[] templates = templateDir.listFiles(templateFilter);
            Arrays.sort(templates);
            for (File f : templates) {
                Template template = fmConfig.getTemplate(Util.buildPath(false, abstractPath, "/", f.getName()));
                Writer out = new StringWriter();
                Environment env = template.createProcessingEnvironment(root, out);
                env.process();

                TemplateResult r = new TemplateResult(f.getName(), out.toString(), env);
                if (!r.getBooleanVariable("skip")) {
                    results.add(new TemplateResult(f.getName(), out.toString(), env));
                }
            }
        }
    } catch (final Throwable t) {
        throw new NoteException(t);
    }
    return results;
}

From source file:org.activiti.rest.service.api.runtime.ProcessInstanceVariablesCollectionResourceTest.java

/**
 * Test creating multiple process variables in a single call. POST runtime/process-instance/{processInstanceId}/variables
 *//*from  w w  w  . j a  va  2 s  . co  m*/
@Deployment(resources = {
        "org/activiti/rest/service/api/runtime/ProcessInstanceVariablesCollectionResourceTest.testProcess.bpmn20.xml" })
public void testCreateMultipleProcessVariables() throws Exception {

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

    ArrayNode requestNode = objectMapper.createArrayNode();

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

    // Integer
    ObjectNode integerVarNode = requestNode.addObject();
    integerVarNode.put("name", "integerVariable");
    integerVarNode.put("value", 1234);
    integerVarNode.put("type", "integer");

    // Short
    ObjectNode shortVarNode = requestNode.addObject();
    shortVarNode.put("name", "shortVariable");
    shortVarNode.put("value", 123);
    shortVarNode.put("type", "short");

    // Long
    ObjectNode longVarNode = requestNode.addObject();
    longVarNode.put("name", "longVariable");
    longVarNode.put("value", 4567890L);
    longVarNode.put("type", "long");

    // Double
    ObjectNode doubleVarNode = requestNode.addObject();
    doubleVarNode.put("name", "doubleVariable");
    doubleVarNode.put("value", 123.456);
    doubleVarNode.put("type", "double");

    // Boolean
    ObjectNode booleanVarNode = requestNode.addObject();
    booleanVarNode.put("name", "booleanVariable");
    booleanVarNode.put("value", Boolean.TRUE);
    booleanVarNode.put("type", "boolean");

    // Date
    Calendar varCal = Calendar.getInstance();
    String isoString = getISODateString(varCal.getTime());

    ObjectNode dateVarNode = requestNode.addObject();
    dateVarNode.put("name", "dateVariable");
    dateVarNode.put("value", isoString);
    dateVarNode.put("type", "date");

    // Create local variables with a single request
    HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_VARIABLE_COLLECTION, processInstance.getId()));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertTrue(responseNode.isArray());
    assertEquals(7, responseNode.size());

    // Check if engine has correct variables set
    Map<String, Object> variables = runtimeService.getVariablesLocal(processInstance.getId());
    assertEquals(7, variables.size());

    assertEquals("simple string value", variables.get("stringVariable"));
    assertEquals(1234, variables.get("integerVariable"));
    assertEquals((short) 123, variables.get("shortVariable"));
    assertEquals(4567890L, variables.get("longVariable"));
    assertEquals(123.456, variables.get("doubleVariable"));
    assertEquals(Boolean.TRUE, variables.get("booleanVariable"));
    assertEquals(dateFormat.parse(isoString), variables.get("dateVariable"));
}

From source file:org.flowable.rest.service.api.runtime.ProcessInstanceVariablesCollectionResourceTest.java

/**
 * Test creating multiple process variables in a single call. POST runtime/process-instance/{processInstanceId}/variables
 *///from ww w .  j  a  v  a  2  s  .  c  o m
@Deployment(resources = {
        "org/flowable/rest/service/api/runtime/ProcessInstanceVariablesCollectionResourceTest.testProcess.bpmn20.xml" })
public void testCreateMultipleProcessVariables() throws Exception {

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

    ArrayNode requestNode = objectMapper.createArrayNode();

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

    // Integer
    ObjectNode integerVarNode = requestNode.addObject();
    integerVarNode.put("name", "integerVariable");
    integerVarNode.put("value", 1234);
    integerVarNode.put("type", "integer");

    // Short
    ObjectNode shortVarNode = requestNode.addObject();
    shortVarNode.put("name", "shortVariable");
    shortVarNode.put("value", 123);
    shortVarNode.put("type", "short");

    // Long
    ObjectNode longVarNode = requestNode.addObject();
    longVarNode.put("name", "longVariable");
    longVarNode.put("value", 4567890L);
    longVarNode.put("type", "long");

    // Double
    ObjectNode doubleVarNode = requestNode.addObject();
    doubleVarNode.put("name", "doubleVariable");
    doubleVarNode.put("value", 123.456);
    doubleVarNode.put("type", "double");

    // Boolean
    ObjectNode booleanVarNode = requestNode.addObject();
    booleanVarNode.put("name", "booleanVariable");
    booleanVarNode.put("value", Boolean.TRUE);
    booleanVarNode.put("type", "boolean");

    // Date
    Calendar varCal = Calendar.getInstance();
    String isoString = getISODateString(varCal.getTime());

    ObjectNode dateVarNode = requestNode.addObject();
    dateVarNode.put("name", "dateVariable");
    dateVarNode.put("value", isoString);
    dateVarNode.put("type", "date");

    // Create local variables with a single request
    HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_VARIABLE_COLLECTION, processInstance.getId()));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertTrue(responseNode.isArray());
    assertEquals(7, responseNode.size());

    // Check if engine has correct variables set
    Map<String, Object> variables = runtimeService.getVariablesLocal(processInstance.getId());
    assertEquals(7, variables.size());

    assertEquals("simple string value", variables.get("stringVariable"));
    assertEquals(1234, variables.get("integerVariable"));
    assertEquals((short) 123, variables.get("shortVariable"));
    assertEquals(4567890L, variables.get("longVariable"));
    assertEquals(123.456, variables.get("doubleVariable"));
    assertEquals(Boolean.TRUE, variables.get("booleanVariable"));
    assertEquals(dateFormat.parse(isoString), variables.get("dateVariable"));
}

From source file:org.activiti.rest.service.api.runtime.ProcessInstanceCollectionResourceTest.java

/**
 * Test starting a process instance passing in variables to set.
 *//* w w  w.j  a va 2 s .  co  m*/
@Deployment(resources = {
        "org/activiti/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testStartProcessWithVariablesAndReturnVariables() throws Exception {
    ArrayNode variablesNode = objectMapper.createArrayNode();

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

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

    ObjectNode requestNode = objectMapper.createObjectNode();

    // Start using process definition key, passing in variables
    requestNode.put("processDefinitionKey", "processOne");
    requestNode.put("returnVariables", true);
    requestNode.put("variables", variablesNode);

    HttpPost httpPost = new HttpPost(
            SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_COLLECTION));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertEquals(false, responseNode.get("ended").asBoolean());
    JsonNode variablesArrayNode = responseNode.get("variables");
    assertEquals(2, variablesArrayNode.size());
    for (JsonNode variableNode : variablesArrayNode) {
        if ("stringVariable".equals(variableNode.get("name").asText())) {
            assertEquals("simple string value", variableNode.get("value").asText());
            assertEquals("string", variableNode.get("type").asText());

        } else if ("integerVariable".equals(variableNode.get("name").asText())) {
            assertEquals(1234, variableNode.get("value").asInt());
            assertEquals("integer", variableNode.get("type").asText());

        } else {
            fail("Unexpected variable " + variableNode.get("name").asText());
        }
    }

    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().singleResult();
    assertNotNull(processInstance);

    // Check if engine has correct variables set
    Map<String, Object> processVariables = runtimeService.getVariables(processInstance.getId());
    assertEquals(2, processVariables.size());

    assertEquals("simple string value", processVariables.get("stringVariable"));
    assertEquals(1234, processVariables.get("integerVariable"));
}

From source file:org.flowable.rest.service.api.runtime.ProcessInstanceCollectionResourceTest.java

/**
 * Test starting a process instance passing in variables to set.
 *//*from   w  ww.  j  a  va  2s  . c o  m*/
@Deployment(resources = {
        "org/flowable/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testStartProcessWithVariablesAndReturnVariables() throws Exception {
    ArrayNode variablesNode = objectMapper.createArrayNode();

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

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

    ObjectNode requestNode = objectMapper.createObjectNode();

    // Start using process definition key, passing in variables
    requestNode.put("processDefinitionKey", "processOne");
    requestNode.put("returnVariables", true);
    requestNode.set("variables", variablesNode);

    HttpPost httpPost = new HttpPost(
            SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_COLLECTION));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertFalse(responseNode.get("ended").asBoolean());
    JsonNode variablesArrayNode = responseNode.get("variables");
    assertEquals(2, variablesArrayNode.size());
    for (JsonNode variableNode : variablesArrayNode) {
        if ("stringVariable".equals(variableNode.get("name").asText())) {
            assertEquals("simple string value", variableNode.get("value").asText());
            assertEquals("string", variableNode.get("type").asText());

        } else if ("integerVariable".equals(variableNode.get("name").asText())) {
            assertEquals(1234, variableNode.get("value").asInt());
            assertEquals("integer", variableNode.get("type").asText());

        } else {
            fail("Unexpected variable " + variableNode.get("name").asText());
        }
    }

    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().singleResult();
    assertNotNull(processInstance);

    // Check if engine has correct variables set
    Map<String, Object> processVariables = runtimeService.getVariables(processInstance.getId());
    assertEquals(2, processVariables.size());

    assertEquals("simple string value", processVariables.get("stringVariable"));
    assertEquals(1234, processVariables.get("integerVariable"));
}

From source file:org.apache.taverna.scufl2.wfdesc.WfdescSerialiser.java

protected OntModel save(final WorkflowBundle bundle) {
    final OntModel model = ModelFactory.createOntologyModel();
    bundle.accept(new VisitorWithPath() {
        Scufl2Tools scufl2Tools = new Scufl2Tools();

        public boolean visit() {
            WorkflowBean node = getCurrentNode();
            // System.out.println(node);
            if (node instanceof WorkflowBundle) {
                return true;
            }/*from   w w w  .  j a v  a  2s . co m*/
            // @SuppressWarnings("rawtypes")

            if (node instanceof org.apache.taverna.scufl2.api.core.Workflow) {
                entityForBean(node, Wfdesc.Workflow);
            } else if (node instanceof Processor) {
                Processor processor = (Processor) node;
                Individual process = entityForBean(processor, Wfdesc.Process);
                Individual wf = entityForBean(processor.getParent(), Wfdesc.Workflow);
                wf.addProperty(Wfdesc.hasSubProcess, process);
            } else if (node instanceof InputPort) {
                WorkflowBean parent = ((Child) node).getParent();
                Individual input = entityForBean(node, Wfdesc.Input);
                Individual process = entityForBean(parent, Wfdesc.Process);
                process.addProperty(Wfdesc.hasInput, input);

            } else if (node instanceof OutputPort) {
                WorkflowBean parent = ((Child) node).getParent();
                Individual output = entityForBean(node, Wfdesc.Output);
                Individual process = entityForBean(parent, Wfdesc.Process);
                process.addProperty(Wfdesc.hasOutput, output);
            } else if (node instanceof DataLink) {
                WorkflowBean parent = ((Child) node).getParent();
                DataLink link = (DataLink) node;
                Individual dl = entityForBean(link, Wfdesc.DataLink);

                Individual source = entityForBean(link.getReceivesFrom(), Wfdesc.Output);
                dl.addProperty(Wfdesc.hasSource, source);

                Individual sink = entityForBean(link.getSendsTo(), Wfdesc.Input);
                dl.addProperty(Wfdesc.hasSink, sink);
                Individual wf = entityForBean(parent, Wfdesc.Workflow);
                wf.addProperty(Wfdesc.hasDataLink, dl);
            } else if (node instanceof Profile) {
                // So that we can get at the ProcessorBinding - buy only if
                // it is the main Profile
                return node == bundle.getMainProfile();
            } else if (node instanceof ProcessorBinding) {
                ProcessorBinding b = (ProcessorBinding) node;
                Activity a = b.getBoundActivity();
                Processor boundProcessor = b.getBoundProcessor();
                Individual process = entityForBean(boundProcessor, Wfdesc.Process);

                // Note: We don't describe the activity and processor
                // binding in wfdesc. Instead we
                // assign additional types and attributes to the parent
                // processor

                try {
                    URI type = a.getType();
                    Configuration c = scufl2Tools.configurationFor(a, b.getParent());
                    JsonNode json = c.getJson();
                    if (type.equals(BEANSHELL)) {
                        process.addRDFType(Wf4ever.BeanshellScript);
                        String s = json.get("script").asText();
                        process.addProperty(Wf4ever.script, s);
                        JsonNode localDep = json.get("localDependency");
                        if (localDep != null && localDep.isArray()) {
                            for (int i = 0; i < localDep.size(); i++) {
                                String depStr = localDep.get(i).asText();
                                // FIXME: Better class for dependency?
                                Individual dep = model.createIndividual(OWL.Thing);
                                dep.addLabel(depStr, null);
                                dep.addComment("JAR dependency", "en");
                                process.addProperty(Roterms.requiresSoftware, dep);
                                // Somehow this gets the whole thing to fall
                                // out of the graph!
                                // QName depQ = new
                                // QName("http://google.com/", ""+
                                // UUID.randomUUID());
                                // sesameManager.rename(dep, depQ);

                            }
                        }
                    }
                    if (type.equals(RSHELL)) {
                        process.addRDFType(Wf4ever.RScript);
                        String s = json.get("script").asText();
                        process.addProperty(Wf4ever.script, s);
                    }
                    if (type.equals(WSDL)) {
                        process.addRDFType(Wf4ever.SOAPService);
                        JsonNode operation = json.get("operation");
                        URI wsdl = URI.create(operation.get("wsdl").asText());
                        process.addProperty(Wf4ever.wsdlURI, wsdl.toASCIIString());
                        process.addProperty(Wf4ever.wsdlOperationName, operation.get("name").asText());
                        process.addProperty(Wf4ever.rootURI, wsdl.resolve("/").toASCIIString());
                    }
                    if (type.equals(REST)) {
                        process.addRDFType(Wf4ever.RESTService);
                        // System.out.println(json);
                        JsonNode request = json.get("request");
                        String absoluteURITemplate = request.get("absoluteURITemplate").asText();
                        String uriTemplate = absoluteURITemplate.replace("{", "");
                        uriTemplate = uriTemplate.replace("}", "");
                        // TODO: Detect {}
                        try {
                            URI root = new URI(uriTemplate).resolve("/");
                            process.addProperty(Wf4ever.rootURI, root.toASCIIString());
                        } catch (URISyntaxException e) {
                            logger.warning("Potentially invalid URI template: " + absoluteURITemplate);
                            // Uncomment to temporarily break
                            // TestInvalidURITemplate:
                            // rest.getWfRootURI().add(URI.create("http://example.com/FRED"));
                        }
                    }
                    if (type.equals(TOOL)) {
                        process.addRDFType(Wf4ever.CommandLineTool);
                        JsonNode desc = json.get("toolDescription");
                        // System.out.println(json);
                        JsonNode command = desc.get("command");
                        if (command != null) {
                            process.addProperty(Wf4ever.command, command.asText());
                        }
                    }
                    if (type.equals(NESTED_WORKFLOW)) {
                        Workflow nestedWf = scufl2Tools.nestedWorkflowForProcessor(boundProcessor,
                                b.getParent());
                        // The parent process is a specialization of the
                        // nested workflow
                        // (because the nested workflow could exist as
                        // several processors)
                        specializationOf(boundProcessor, nestedWf);
                        process.addRDFType(Wfdesc.Workflow);

                        // Just like the Processor specializes the nested
                        // workflow, the
                        // ProcessorPorts specialize the WorkflowPort
                        for (ProcessorPortBinding portBinding : b.getInputPortBindings()) {
                            // Map from activity port (not in wfdesc) to
                            // WorkflowPort
                            WorkflowPort wfPort = nestedWf.getInputPorts()
                                    .getByName(portBinding.getBoundActivityPort().getName());
                            if (wfPort == null) {
                                continue;
                            }
                            specializationOf(portBinding.getBoundProcessorPort(), wfPort);
                        }
                        for (ProcessorPortBinding portBinding : b.getOutputPortBindings()) {
                            WorkflowPort wfPort = nestedWf.getOutputPorts()
                                    .getByName(portBinding.getBoundActivityPort().getName());
                            if (wfPort == null) {
                                continue;
                            }
                            specializationOf(portBinding.getBoundProcessorPort(), wfPort);
                        }
                    }
                } catch (IndexOutOfBoundsException ex) {
                }
                return false;
            } else {
                // System.out.println("--NO!");
                return false;
            }
            for (Annotation ann : scufl2Tools.annotationsFor(node, bundle)) {
                String annotationBody = ann.getBody().toASCIIString();
                String baseURI = bundle.getGlobalBaseURI().resolve(ann.getBody()).toASCIIString();
                InputStream annotationStream;
                try {
                    annotationStream = bundle.getResources().getResourceAsInputStream(annotationBody);

                    try {
                        // FIXME: Don't just assume Lang.TURTLE
                        RDFDataMgr.read(model, annotationStream, baseURI, Lang.TURTLE);
                    } catch (RiotException e) {
                        logger.log(Level.WARNING, "Can't parse RDF Turtle from " + annotationBody, e);
                    } finally {
                        annotationStream.close();
                    }
                } catch (IOException e) {
                    logger.log(Level.WARNING, "Can't read " + annotationBody, e);
                }
            }
            if (node instanceof Named) {
                Named named = (Named) node;
                entityForBean(node, OWL.Thing).addLabel(named.getName(), null);
            }
            return true;
        }

        private void specializationOf(WorkflowBean special, WorkflowBean general) {
            Individual specialEnt = entityForBean(special, Prov_o.Entity);
            Individual generalEnt = entityForBean(general, Prov_o.Entity);
            specialEnt.addProperty(Prov_o.specializationOf, generalEnt);
        }

        private Individual entityForBean(WorkflowBean bean, Resource thing) {
            return model.createIndividual(uriForBean(bean), thing);
        }

        // @Override
        // public boolean visitEnter(WorkflowBean node) {
        // if (node instanceof Processor
        // || node instanceof org.apache.taverna.scufl2.api.core.Workflow
        // || node instanceof Port || node instanceof DataLink) {
        // visit(node);
        // return true;
        // }
        // // The other node types (e.g. dispatch stack, configuration) are
        // // not (directly) represented in wfdesc
        //// System.out.println("Skipping " + node);
        // return false;
        // };
    });
    return model;
}