Commit a53a4f91 by Mikhail Gashenko

JsonNode: (draft7) added updatable class variables

parent 9b3b8a29
package kz.arta.synergy.api.rest.sample.asforms;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
* класс демонстрации работы метода save класса APIFormsService
*
* Created by root on 7/12/14.
*/
public class APIFormsServiceSave {
/**
* Переменная логина пользователя вызывающего метод.
*/
private String login;
/**
* Переменная пароля пользователя вызывающего метод.
*/
private String password;
private String encoded;
/**
* Переменная URL Arta Synergy.
*/
private String address;
// UUID формы (параметр запроса)
private String formUUID;
// UUID данных по форме (параметр запроса)
private String uuid;
//идентификатор папки в хранилище, в которой должен быть создан файл по форме (имеет смысл только если uuid равен null)
private String parentID;
// json с данными по форме (параметр формы)
private String data;
public APIFormsServiceSave(String login, String password, String address) {
this.login = login;
this.password = password;
this.address = address;
encoded = Base64.encode((login + ":" + password).getBytes());
}
public void save() throws Exception {
URL url = new URL(address + "/rest/api/asforms/data/save");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json; charset=utf-8");
connection.setRequestProperty("Authorization", "Basic " + encoded);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(true);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream request = new DataOutputStream(connection.getOutputStream());
request.writeBytes("formUUID=" + formUUID);
request.writeBytes("&");
if (uuid != null) {
request.writeBytes("uuid=" + uuid);
} else {
request.writeBytes("parentID=" + parentID);
}
request.writeBytes("&");
request.writeBytes("data=" + data);
request.flush();
request.close();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
br.close();
is.close();
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createJsonParser(response.toString());
JsonToken token = null;
while ((token = parser.nextToken()) != null) {
if (token == JsonToken.FIELD_NAME) {
System.out.println();
System.out.print(parser.getText() + " -> ");
token = parser.nextToken();
if (token == JsonToken.VALUE_STRING) {
System.out.print(parser.getText());
}
}
}
}
public void setFormUUID(String formUUID) {
this.formUUID = formUUID;
}
public void setUUID(String uuid) {
this.uuid = uuid;
}
public void setParentID(String parentID) {
this.parentID = parentID;
}
public void setData(String data) {
this.data = data;
}
public String getFormUUID() {
return this.formUUID;
}
public String getUUID() {
return this.uuid;
}
public String getData() {
return this.data;
}
public String getParentID() {
return this.parentID;
}
}
...@@ -17,16 +17,12 @@ import java.io.IOException; ...@@ -17,16 +17,12 @@ 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;
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.NameNotFoundException;
import javax.naming.directory.AttributeModificationException; import javax.naming.directory.AttributeModificationException;
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.ObjectNode;
import org.codehaus.jackson.type.TypeReference; import org.codehaus.jackson.type.TypeReference;
/** /**
...@@ -47,7 +43,6 @@ public class Main implements MessageListener { ...@@ -47,7 +43,6 @@ public class Main implements MessageListener {
private static enum fieldType { private static enum fieldType {
DATE, TEXTBOX, USER DATE, TEXTBOX, USER
} }
private static enum fields { private static enum fields {
ID, TYPE, LABEL, KEY, VALUE ID, TYPE, LABEL, KEY, VALUE
} }
...@@ -56,6 +51,9 @@ public class Main implements MessageListener { ...@@ -56,6 +51,9 @@ public class Main implements MessageListener {
private String executionID = null; // идентификатор блокирующего процесса private String executionID = null; // идентификатор блокирующего процесса
private String documentID = null; // идентификатор документа реестра private String documentID = null; // идентификатор документа реестра
private List<AsNode> sourceFormData = null;
private List<AsNode> targetFormData = null;
/** /**
* *
* @param message * @param message
...@@ -94,18 +92,36 @@ public class Main implements MessageListener { ...@@ -94,18 +92,36 @@ public class Main implements MessageListener {
// Получение данных исходной формы (той, по которой запущен маршрут) // Получение данных исходной формы (той, по которой запущен маршрут)
URL sourceFormURL = new URL("http://127.0.0.1:8080/Synergy/rest/api/asforms/data/" + dataUUID); URL sourceFormURL = new URL("http://127.0.0.1:8080/Synergy/rest/api/asforms/data/" + dataUUID);
String sourceFormData = synergyApiGetString(sourceFormURL); String sourceFormDataAsString = synergyApiGetString(sourceFormURL);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode SourceRootNode = objectMapper.readTree(sourceFormDataAsString); // read the whole tree
if (SourceRootNode.isNull()) {
throw new AttributeModificationException("GMP: Passed data has no JSON content");
}
JsonNode SourceRootDataNode = SourceRootNode.get("data"); // read single root 'data' node
if (SourceRootDataNode == null) {
throw new AttributeModificationException("GMP: Invalid form data, root \"data\" node does not exists");
}
sourceFormData = objectMapper.readValue(SourceRootDataNode, new TypeReference<List<AsNode>>() {}); // map content of single root 'data' node
// Получение ID пользователя указанного в форме
String userID = getComponentValueByID(sourceFormData, "user1", fields.KEY);
// По ID пользователя указанного в карточке и ID формы получаем DataUUID целевой карточки // Получение ID пользователя указанного в форме
// String userCardDataUUID = getCardDataUUID(userID, "04f7809d-f44c-4a2d-950d-6aa8e6c3fea1"); String userID = getComponentValueByID(sourceFormDataAsString, "user1", fields.KEY); // TODO: Pass JsonNode, not String
// По ID пользователя указанного в карточке и ID формы получаем DataUUID целевой карточки (ID for work: "04f7809d-f44c-4a2d-950d-6aa8e6c3fea1")
String userCardDataUUID = getCardDataUUID(userID, "fb44d99d-1579-4ac3-884a-01a6d4f71f9c"); String userCardDataUUID = getCardDataUUID(userID, "fb44d99d-1579-4ac3-884a-01a6d4f71f9c");
// Получение данных целевой карточки по dataUUID // Получение данных целевой карточки по dataUUID
URL targetFormURL = new URL("http://127.0.0.1:8080/Synergy/rest/api/asforms/data/" + userCardDataUUID); URL targetFormURL = new URL("http://127.0.0.1:8080/Synergy/rest/api/asforms/data/" + userCardDataUUID);
String targetFormData = synergyApiGetString(targetFormURL); String targetFormDataAsString = synergyApiGetString(targetFormURL);
JsonNode TargetRootNode = objectMapper.readTree(targetFormDataAsString);
if (TargetRootNode.isNull()) {
throw new AttributeModificationException("GMP: Passed data has no JSON content");
}
JsonNode TargetRootDataNode = TargetRootNode.get("data");
if (TargetRootDataNode == null) {
throw new AttributeModificationException("GMP: Invalid form data, root \"data\" node does not exists");
}
targetFormData = objectMapper.readValue(TargetRootDataNode, new TypeReference<List<AsNode>>() {});
// Получение значений текущих дат исходной формы // Получение значений текущих дат исходной формы
String b5b1; String b5b1;
...@@ -118,12 +134,12 @@ public class Main implements MessageListener { ...@@ -118,12 +134,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", fields.KEY); String b2b1 = getComponentValueByID(this.sourceFormData, "b2-b1-b1", fields.KEY);
String b4b1 = getComponentValueByID(sourceFormData, "b4-b1-b1", fields.KEY); String b4b1 = getComponentValueByID(this.sourceFormData, "b4-b1-b1", fields.KEY);
if (!b2b1.isEmpty() && !b4b1.isEmpty()) { if (!b2b1.isEmpty() && !b4b1.isEmpty()) {
updateFieldValue(targetFormData, "start-b1", fields.KEY, b2b1); updateFieldValue(this.targetFormData, "start-b1", fields.KEY, b2b1);
updateFieldValue(targetFormData, "finish-b1", fields.KEY, b4b1); updateFieldValue(this.targetFormData, "finish-b1", fields.KEY, b4b1);
unlockRoute(); unlockRoute();
return; return;
...@@ -152,9 +168,6 @@ public class Main implements MessageListener { ...@@ -152,9 +168,6 @@ public class Main implements MessageListener {
LOGGER.error(exc.getMessage(), exc); LOGGER.error(exc.getMessage(), exc);
} }
} }
// NEW METHODS
/** /**
* Returns node which has specifies ID * Returns node which has specifies ID
...@@ -166,15 +179,12 @@ public class Main implements MessageListener { ...@@ -166,15 +179,12 @@ public class Main implements MessageListener {
AsNode result = null; AsNode result = null;
for (AsNode n : nodesList) { for (AsNode n : nodesList) {
if (result != null) break; // prevent relooping if result has already been found
if (componentID.equals(n.getId())) { if (componentID.equals(n.getId())) {
result = n; result = n;
break; } else if (n.getData() != null) {
}
if(n.getData() != null) {
result = findNode(n.getData(), componentID); result = findNode(n.getData(), componentID);
if (result != null) {
break;
}
} }
} }
...@@ -190,18 +200,9 @@ public class Main implements MessageListener { ...@@ -190,18 +200,9 @@ public class Main implements MessageListener {
* @throws AttributeModificationException * @throws AttributeModificationException
* @throws IOException * @throws IOException
*/ */
private void updateFieldValue (String targetJsonAsString, String componentID, fields fieldName, String newFieldValue) throws AttributeModificationException, IOException { private void updateFieldValue (List<AsNode> dataNodesList, String componentID, fields fieldName, String newFieldValue) throws AttributeModificationException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
try { 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
AsNode targetNode = findNode(dataNodesList, componentID); AsNode targetNode = findNode(dataNodesList, componentID);
if (targetNode == null) { if (targetNode == null) {
...@@ -233,7 +234,7 @@ public class Main implements MessageListener { ...@@ -233,7 +234,7 @@ public class Main implements MessageListener {
/** /**
* Returns user's card data UUID by form's UUID * Returns user's card data UUID by form's UUID
* @param userID - User identifier * @param userID - User identifier
* @param formUUID - Forms' data UUID * @param formUUID - Form's data UUID
* @return Specified user's card 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) {
...@@ -264,21 +265,9 @@ public class Main implements MessageListener { ...@@ -264,21 +265,9 @@ public class Main implements MessageListener {
* @throws NameNotFoundException * @throws NameNotFoundException
* @throws IOException * @throws IOException
*/ */
private static String getComponentValueByID(String targetJsonAsString, String componentID, fields fieldName) throws Exception { private static String getComponentValueByID(List<AsNode> dataNodesList, String componentID, fields fieldName) throws Exception {
// String b2b1 = getComponentValueByID(sourceFormData, "b2-b1-b1", fieldType.DATE);
ObjectMapper objectMapper = new ObjectMapper();
String result = null; String result = null;
try { try {
JsonNode rootNode = objectMapper.readTree(targetJsonAsString); // read the whole tree
if (rootNode.isNull()) {
throw new Exception("GMP: Passed data has no JSON content");
}
JsonNode rootDataNode = rootNode.get("data"); // read single root 'data' node
if (rootDataNode == null) {
throw new Exception("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
AsNode targetNode = findNode(dataNodesList, componentID); AsNode targetNode = findNode(dataNodesList, componentID);
if (targetNode == null) { if (targetNode == null) {
......
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