Commit a91e1e7d by Mikhail Gashenko

JsonNode: (draft4) new node value search and update with ObjectMapper

parent f58d6c80
/target/
\ No newline at end of file
...@@ -37,6 +37,12 @@ ...@@ -37,6 +37,12 @@
<version>1.9.10</version> <version>1.9.10</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId> <groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId> <artifactId>javaee-web-api</artifactId>
<version>6.0</version> <version>6.0</version>
......
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package kz.arta.synergy.astdev.custom_bp;
import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
/**
*
* @author drpsy
*/
public class AsNode {
@JsonProperty("id")
private String id;
@JsonProperty("type")
private String type;
@JsonProperty("label")
private String label;
@JsonProperty("key")
private String key;
@JsonProperty("value")
private String value;
@JsonProperty("data")
private List<AsNode> data;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<AsNode> getData() {
return data;
}
public void setData(List<AsNode> data) {
this.data = data;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package kz.arta.synergy.astdev.custom_bp; package kz.arta.synergy.astdev.custom_bp;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
...@@ -18,6 +13,7 @@ import javax.jms.Message; ...@@ -18,6 +13,7 @@ import javax.jms.Message;
import javax.jms.MessageListener; import javax.jms.MessageListener;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
...@@ -25,6 +21,8 @@ import java.util.Iterator; ...@@ -25,6 +21,8 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import javax.ejb.ActivationConfigProperty; import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven; import javax.ejb.MessageDriven;
import javax.naming.NameNotFoundException;
import javax.naming.directory.AttributeModificationException;
import javax.naming.directory.InvalidAttributesException; import javax.naming.directory.InvalidAttributesException;
import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode; import org.codehaus.jackson.node.ArrayNode;
...@@ -46,6 +44,10 @@ public class Main implements MessageListener { ...@@ -46,6 +44,10 @@ public class Main implements MessageListener {
DATE, TEXTBOX, USER DATE, TEXTBOX, USER
} }
private static enum fields {
ID, TYPE, LABEL, KEY, VALUE
}
private String dataUUID = null; // идентификатор данных по форме записи реестра private String dataUUID = null; // идентификатор данных по форме записи реестра
private String executionID = null; // идентификатор блокирующего процесса private String executionID = null; // идентификатор блокирующего процесса
private String documentID = null; // идентификатор документа реестра private String documentID = null; // идентификатор документа реестра
...@@ -87,7 +89,7 @@ public class Main implements MessageListener { ...@@ -87,7 +89,7 @@ public class Main implements MessageListener {
String sourceFormData = synergyApiGetString(sourceFormURL); String sourceFormData = synergyApiGetString(sourceFormURL);
// Получение ID пользователя // Получение ID пользователя
String userID = getComponentValueByID(sourceFormData, "user1", fieldType.USER); String userID = getComponentValueByID(sourceFormData, "user1", fields.KEY);
// По ID пользователя DataUUID целевой карточки // По ID пользователя DataUUID целевой карточки
String userCardDataUUID = getCardDataUUID(userID, "04f7809d-f44c-4a2d-950d-6aa8e6c3fea1"); String userCardDataUUID = getCardDataUUID(userID, "04f7809d-f44c-4a2d-950d-6aa8e6c3fea1");
...@@ -106,12 +108,12 @@ public class Main implements MessageListener { ...@@ -106,12 +108,12 @@ public class Main implements MessageListener {
// String t32b1, t30b1, t28b1; // String t32b1, t30b1, t28b1;
// first table // first table
String b2b1 = getComponentValueByID(sourceFormData, "b2-b1-b1", fieldType.DATE); String b2b1 = getComponentValueByID(sourceFormData, "b2-b1-b1", fields.KEY);
String b4b1 = getComponentValueByID(sourceFormData, "b4-b1-b1", fieldType.DATE); String b4b1 = getComponentValueByID(sourceFormData, "b4-b1-b1", fields.KEY);
if (!b2b1.isEmpty() && !b4b1.isEmpty()) { if (!b2b1.isEmpty() && !b4b1.isEmpty()) {
setComponentValueByID(targetFormData, "start-b1", "key", b2b1); updateFieldValue(targetFormData, "start-b1", fields.KEY, b2b1);
setComponentValueByID(targetFormData, "finish-b1", "key", b4b1); updateFieldValue(targetFormData, "finish-b1", fields.KEY, b4b1);
unlockRoute(); unlockRoute();
return; return;
...@@ -141,60 +143,77 @@ public class Main implements MessageListener { ...@@ -141,60 +143,77 @@ public class Main implements MessageListener {
} }
} }
private void setComponentValueByID (String targetJsonAsString, String componentID, String fieldName, String newFieldValue) throws InvalidAttributesException {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode rootNode = mapper.readTree(targetJsonAsString);
// getting first level (root) 'data' node, there may be only two levels // NEW METHODS
ArrayNode rootDN = (ArrayNode) rootNode.get("data");
Iterator<JsonNode> rootDNIterator = rootDN.getElements(); // all objects of first 'data'
// searching for field value in root 'data' node and setting new value if found /**
JsonNode node = searchInNode2(rootDNIterator, componentID, fieldName); * Returns node which has specifies ID
// setting node value * @param nodesList - List of nodes
if (node != null) { * @param componentID - Component ID
setValueInNode(node, componentID, newFieldValue, componentID); * @return AsNode if such exists, null otherwise
return; */
private static AsNode findNode(List<AsNode> nodesList, String componentID) {
AsNode result = null;
for (AsNode n : nodesList) {
if (componentID.equals(n.getId())) {
result = n;
break;
} }
if(!n.getData().isEmpty()) {
// root 'data' value does not contain the expected value, search in second (last possible) 'data' findNode(n.getData(), componentID);
Iterator<JsonNode> rootDNIterator2 = rootDN.getElements(); // all objects of first 'data'
while (rootDNIterator2.hasNext()) {
ArrayNode childNode = (ArrayNode) rootDNIterator2.next().get("data"); // get next 'data'
if (childNode != null) {
Iterator<JsonNode> childDNIterator = childNode.getElements();
node = searchInNode2(childDNIterator, componentID, fieldName);
} }
} }
return result;
if (node != null) {
setValueInNode(node, componentID, newFieldValue, componentID);
} else {
throw new InvalidAttributesException("GMP: Target form field cannot be updated");
} }
} catch (Exception exc) { private void updateFieldValue (String targetJsonAsString, String componentID, fields fieldName, String newFieldValue) throws AttributeModificationException, IOException {
LOGGER.error(exc.getMessage(), exc); ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode rootNode = objectMapper.readTree(targetJsonAsString); // read the whole tree
if (rootNode.isNull()) {
throw new AttributeModificationException("GMP: Passed data has no JSON content");
} }
JsonNode rootDataNode = rootNode.get("data"); // read single root 'data' node
if (rootDataNode == null) {
throw new AttributeModificationException("GMP: Invalid form data, root \"data\" node does not exists");
} }
List<AsNode> dataNodesList = objectMapper.readValue(rootDataNode, new TypeReference<List<AsNode>>(){}); // map content of single root 'data' node
private void unlockRoute() { AsNode targetNode = findNode(dataNodesList, componentID);
try { if (targetNode == null) {
String address = "http://127.0.0.1:8080/Synergy"; throw new AttributeModificationException("GMP: Node with specified ID is not found in passed JSON");
String signal = "got_agree"; } else {
URL url = new URL(address + "/rest/api/processes/signal?signal=" + signal + "&executionID=" + this.executionID + "&param1=resolution&value1=signal_is_" + signal); switch (fieldName) {
synergyApiGet(url); case ID:
} catch (Exception exc) { targetNode.setId(newFieldValue);
LOGGER.error(exc.getMessage(), exc); break;
case TYPE:
targetNode.setType(newFieldValue);
break;
case LABEL:
targetNode.setLabel(newFieldValue);
break;
case KEY:
targetNode.setKey(newFieldValue);
break;
case VALUE:
targetNode.setValue(newFieldValue);
break;
default: // TODO
break;
}
}
} catch (AttributeModificationException e) {
throw e;
} }
} }
// get user's card data uuid by formuuid /**
* Returns user's card data UUID by form's UUID
* @param userID - User identifier
* @param formUUID - Forms' data UUID
* @return Specified user's card data UUID
*/
private static String getCardDataUUID (String userID, String formUUID) { private static String getCardDataUUID (String userID, String formUUID) {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
try { try {
...@@ -214,95 +233,68 @@ public class Main implements MessageListener { ...@@ -214,95 +233,68 @@ public class Main implements MessageListener {
return new String(); return new String();
} }
private static void setValueInNode (JsonNode node, String componentID, String newFieldValue, String componentFieldName) throws InvalidAttributesException { private static String getComponentValueByID(String targetJsonAsString, String componentID, fields fieldName) throws NameNotFoundException, IOException {
if (node == null) { // String b2b1 = getComponentValueByID(sourceFormData, "b2-b1-b1", fieldType.DATE);
throw new InvalidAttributesException("JsonNode cannot be null"); ObjectMapper objectMapper = new ObjectMapper();
} String result = null;
try { try {
ObjectNode objectNode = (ObjectNode) node; JsonNode rootNode = objectMapper.readTree(targetJsonAsString); // read the whole tree
objectNode.put(componentFieldName, newFieldValue); if (rootNode.isNull()) {
} catch (Exception exc) { throw new NameNotFoundException("GMP: Passed data has no JSON content");
throw exc;
} }
JsonNode rootDataNode = rootNode.get("data"); // read single root 'data' node
if (rootDataNode == null) {
throw new NameNotFoundException("GMP: Invalid form data, root \"data\" node does not exists");
} }
List<AsNode> dataNodesList = objectMapper.readValue(rootDataNode, new TypeReference<List<AsNode>>() {}); // map content of single root 'data' node
private static String searchInNode(Iterator<JsonNode> iter, String fieldName, fieldType ft) { AsNode targetNode = findNode(dataNodesList, componentID);
String result = new String(); if (targetNode == null) {
// different form's component keeps data in different places throw new NameNotFoundException("GMP: Node with specified ID is not found in passed JSON");
String componentType = new String(); } else {
if (ft == fieldType.DATE || ft == fieldType.USER) { switch (fieldName) {
componentType = "key"; case ID:
} else if (ft == fieldType.TEXTBOX) { result = targetNode.getId(); // may be for cheking if component with such ID exists at all
componentType = "value"; break;
} case TYPE:
result = targetNode.getType();
while (iter.hasNext()) { break;
// search data through content of child 'data' nodes case LABEL:
JsonNode n = iter.next(); result = targetNode.getLabel();
break;
if (n.has("id") && n.has(componentType)) { case KEY:
if (fieldName.equals(n.get("id").asText())) { result = targetNode.getKey();
result = n.get(componentType).asText(); break;
} case VALUE:
result = targetNode.getValue();
break;
} }
} }
return result; return result;
} catch (NameNotFoundException e) {
throw e;
} }
private static JsonNode searchInNode2(Iterator<JsonNode> iter, String componentID, String componentFieldName) {
while (iter.hasNext()) {
// search data through content of child 'data' nodes
JsonNode n = iter.next();
if (n.has("id") && n.has(componentFieldName)) {
if (componentID.equals(n.get("id").asText())) {
return n;
}
}
}
return null;
} }
private static String getComponentValueByID(String formJson, String fieldName, fieldType ft) {
ObjectMapper mapper = new ObjectMapper();
String result = new String();
/**
* Route unlocking
*/
private void unlockRoute() {
try { try {
JsonNode rootNode = mapper.readTree(formJson); String address = "http://127.0.0.1:8080/Synergy";
String signal = "got_agree";
// getting first level (root) 'data' node, there may be only two levels URL url = new URL(address + "/rest/api/processes/signal?signal=" + signal + "&executionID=" + this.executionID + "&param1=resolution&value1=signal_is_" + signal);
ArrayNode rootDN = (ArrayNode) rootNode.get("data"); synergyApiGet(url);
Iterator<JsonNode> rootDNIterator = rootDN.getElements();
// searching for field value in root 'data' node
result = searchInNode(rootDNIterator, fieldName, ft);
if (!result.isEmpty()) {
return result;
}
// root 'data' value does not contain the expected value, search in second (last possible) 'data'
Iterator<JsonNode> rootDNIterator2 = rootDN.getElements(); // 'reset' iterator (create new one)
while (rootDNIterator2.hasNext()) {
ArrayNode childNode = (ArrayNode) rootDNIterator2.next().get("data");
Iterator<JsonNode> childDNIterator = childNode.getElements();
result = searchInNode(childDNIterator, fieldName, ft);
if (!result.isEmpty()) {
return result;
}
}
return result;
} catch (Exception exc) { } catch (Exception exc) {
LOGGER.error("GMP: Invalid form data");
LOGGER.error(exc.getMessage(), exc); LOGGER.error(exc.getMessage(), exc);
} }
return result;
} }
private static JsonParser synergyApiGet(final URL requestURL) { private static JsonParser synergyApiGet(final URL requestURL) {
String login = "Ипатьев"; String login = "111111";
String password = "1"; String password = "1";
try { try {
...@@ -333,7 +325,7 @@ public class Main implements MessageListener { ...@@ -333,7 +325,7 @@ public class Main implements MessageListener {
} }
private static String synergyApiGetString(final URL requestURL) { private static String synergyApiGetString(final URL requestURL) {
String login = "Ипатьев"; String login = "111111";
String password = "1"; String password = "1";
try { try {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment