initialize
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright (c) 2008 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part
|
||||
* of this file in any form be copied, printed, edited or otherwise distributed,
|
||||
* be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data;
|
||||
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlDatabase;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author frankp
|
||||
*/
|
||||
public interface IDatabaseSimulation {
|
||||
|
||||
public void executeUpdate(String sql, XmlDatabase xmlDatabase);
|
||||
|
||||
public void executeInsert(String sql, XmlDatabase xmlDatabase);
|
||||
|
||||
public void executeDelete(String sql, XmlDatabase xmlDatabase);
|
||||
|
||||
public void executeSelect(String sql, XmlDatabase xmlDatabase);
|
||||
|
||||
public void commit(XmlDatabase xmlDatabase) ;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package com.itac.mes.datainterface.data;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import org.w3c.dom.Attr;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.ProcessingInstruction;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import com.itac.mes.datainterface.VersionInfo;
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestCaseState;
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestSuite;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
import com.itac.util.logging.LogLevel;
|
||||
import com.itac.util.system.SysParameter;
|
||||
|
||||
public class UploadXmlTestPlanUnit extends BasicUploadUnit {
|
||||
|
||||
public static final String DESC = "desc";
|
||||
private static final String LOGGER = UploadXmlTestPlanUnit.class.getSimpleName();
|
||||
private String id;
|
||||
private String description = "";
|
||||
private ArrayList<XmlTestSuite> xmlTestSuites = new ArrayList<XmlTestSuite>();
|
||||
protected long startTime = 0L;
|
||||
protected long stopTime = 0L;
|
||||
private DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
private Document document;
|
||||
protected HashSet<String> idSet = new HashSet<String>();
|
||||
private String poolId;
|
||||
private String appId;
|
||||
private String host;
|
||||
private String user;
|
||||
private Element stats;
|
||||
private Element version;
|
||||
private String xsltFile;
|
||||
private boolean totalStatePass;
|
||||
private int suitePassed = 0;
|
||||
private int suiteFailed = 0;
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public UploadXmlTestPlanUnit() {
|
||||
super();
|
||||
poolId = "POOL-ID (hard-coded in UploadXmlTestPlanUnit";
|
||||
appId = "APP-ID (hard-coded in UploadXmlTestPlanUnit";
|
||||
host = new SysParameter().getJavaCanonicalHostName();
|
||||
user = System.getProperty("user.name");
|
||||
}
|
||||
|
||||
public void add(XmlTestSuite xmlTestSuite) throws Exception {
|
||||
if (!xmlTestSuite.getId().equals("") && idSet.contains(xmlTestSuite.getId())) {
|
||||
throw new Exception("TestSuite still contains a testplan with id " + xmlTestSuite.getId());
|
||||
}
|
||||
idSet.add(xmlTestSuite.getId());
|
||||
xmlTestSuites.add(xmlTestSuite);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "TestPlan id=" + id;
|
||||
}
|
||||
|
||||
public ArrayList<XmlTestSuite> getXmlTestSuites() {
|
||||
return xmlTestSuites;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
try {
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
String xml = "<testPlan id=\"" + id + " \"/>";
|
||||
InputSource is = new InputSource(new StringReader(xml));
|
||||
document = builder.parse(is);
|
||||
ProcessingInstruction pi = document.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + xsltFile
|
||||
+ "\"");
|
||||
|
||||
document.insertBefore(pi, document.getDocumentElement());
|
||||
|
||||
addAttribute(document.getDocumentElement(), "host", host);
|
||||
addAttribute(document.getDocumentElement(), UploadXmlTestPlanUnit.DESC, description);
|
||||
addAttribute(document.getDocumentElement(), "user", user);
|
||||
addAttribute(document.getDocumentElement(), "appId", appId);
|
||||
addAttribute(document.getDocumentElement(), "poolId", poolId);
|
||||
|
||||
stats = document.createElement("stats");
|
||||
document.getDocumentElement().appendChild(stats);
|
||||
|
||||
version = document.createElement("version");
|
||||
document.getDocumentElement().appendChild(version);
|
||||
|
||||
addAttribute(stats, "suites", String.valueOf(xmlTestSuites.size()));
|
||||
addAttribute(stats, "started", new Date().toString());
|
||||
|
||||
} catch (ParserConfigurationException e) {
|
||||
LogHandler.log(getClass().getSimpleName(), LogLevel.ERROR, "build construct failed", e);
|
||||
} catch (SAXException e) {
|
||||
LogHandler.log(getClass().getSimpleName(), LogLevel.ERROR, "build construct failed", e);
|
||||
} catch (IOException e) {
|
||||
LogHandler.log(getClass().getSimpleName(), LogLevel.ERROR, "build construct failed", e);
|
||||
}
|
||||
|
||||
LogHandler.log(LOGGER, INFO, "starte " + toString());
|
||||
startTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
/**
|
||||
* erzeugen eines neuen Attributes und anhaengen des Attributs an das Element
|
||||
*
|
||||
* @param superElement
|
||||
* @param attributeKey
|
||||
* @param attributeValue
|
||||
*/
|
||||
private void addAttribute(Element superElement, String attributeKey, String attributeValue) {
|
||||
Attr attr = document.createAttribute(attributeKey);
|
||||
attr.setNodeValue(attributeValue);
|
||||
superElement.setAttributeNode(attr);
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
stopTime = System.currentTimeMillis();
|
||||
addAttribute(stats, "ended", new Date().toString());
|
||||
addAttribute(stats, "executionTime", String.valueOf(getTestPlanMillies()));
|
||||
addAttribute(version, "mesSuite", VersionInfo.getVersion(VersionInfo.MES_SUITE_VERSION));
|
||||
addAttribute(version, "mesInterface", VersionInfo.getVersion(VersionInfo.MES_INTERFACE_VERSION));
|
||||
// Staistiken berechnen
|
||||
suitePassed = 0;
|
||||
suiteFailed = 0;
|
||||
for (XmlTestSuite suite : xmlTestSuites) {
|
||||
if (suite.getState() == XmlTestCaseState.PASS) {
|
||||
suitePassed++;
|
||||
} else {
|
||||
suiteFailed++;
|
||||
}
|
||||
}
|
||||
// Gesamtstatus aller enthaltenen Suites ermitteln
|
||||
totalStatePass = suiteFailed == 0;
|
||||
addAttribute(stats, "suitesPassed", String.valueOf(suitePassed));
|
||||
addAttribute(stats, "suitesFailed", String.valueOf(suiteFailed));
|
||||
LogHandler.info(toString() + " run in " + getTestPlanMillies() + " millies");
|
||||
}
|
||||
|
||||
/**
|
||||
* berechnet die Laufzeit der Ausfuehrung eines Testplanes
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public long getTestPlanMillies() {
|
||||
if (startTime == 0L && stopTime == 0L) {
|
||||
return 0L;
|
||||
}
|
||||
return stopTime - startTime;
|
||||
}
|
||||
|
||||
public Document getDocument() {
|
||||
return document;
|
||||
}
|
||||
|
||||
public void setDesc(String desc) {
|
||||
description = desc;
|
||||
}
|
||||
|
||||
public void setXsltFile(String xsltFile) {
|
||||
this.xsltFile = xsltFile;
|
||||
}
|
||||
|
||||
public boolean isTotalStatePass() {
|
||||
return totalStatePass;
|
||||
}
|
||||
|
||||
public boolean getTotalResult() {
|
||||
return suiteFailed == 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
|
||||
/**
|
||||
* @author frankp
|
||||
*
|
||||
*/
|
||||
public class TestcaseException extends Exception {
|
||||
|
||||
/**
|
||||
* @param message
|
||||
*/
|
||||
public TestcaseException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param message
|
||||
*/
|
||||
public TestcaseException(String message, Object... args) {
|
||||
super(MessageFormat.format(message, args));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param h
|
||||
*/
|
||||
public TestcaseException(Exception th) {
|
||||
super(th);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,616 @@
|
||||
/*
|
||||
* Copyright (c) 2010 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.DEBUG;
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
import static com.itac.util.logging.LogLevel.TRACE;
|
||||
import static com.itac.util.logging.LogLevel.WARN;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Writer;
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.Hashtable;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import com.itac.mes.datainterface.data.xml.XmlSerializer;
|
||||
import com.itac.util.date.DateConvert;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class VariableEngine extends Hashtable<String, Object> {
|
||||
|
||||
private static final String LOGGER = VariableEngine.class.getSimpleName();
|
||||
private static final long serialVersionUID = -723273036849946093L;
|
||||
private static long sequence = 0;
|
||||
private XmlSerializer serializer = new XmlSerializer();
|
||||
private XmlSerializer structuredSerializer = new XmlSerializer(true, true, false);
|
||||
|
||||
private enum IMODIFIER {
|
||||
PUBLIC(0x00000001), PRIVATE(0x00000002), PROTECTED(0x00000004), STATIC(0x00000008), FINAL(0x00000010), SYNCHRONIZED(
|
||||
0x00000020), VOLATILE(
|
||||
0x00000040), TRANSIENT(0x00000080), NATIVE(0x00000100), INTERFACE(0x00000200), ABSTRACT(0x00000400), STRICT(0x00000800);
|
||||
|
||||
private int value;
|
||||
|
||||
private IMODIFIER(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
private SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getTimeInstance();
|
||||
|
||||
public VariableEngine() {
|
||||
super();
|
||||
sdf.applyPattern("HH:mm:ss,S");
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Object put(String arg0, Object arg1) {
|
||||
if (arg1 == null) {
|
||||
LogHandler.log(LOGGER, TRACE, "modify variable value, use constant value $NULL for null variable ");
|
||||
arg1 = "$NULL";
|
||||
} else if (arg1.getClass() == String.class && ((String) arg1).isEmpty()) {
|
||||
LogHandler.log(LOGGER, TRACE, "modify variable value, use constant value $EMPTY for empty string variable ");
|
||||
arg1 = "$EMPTY";
|
||||
}
|
||||
|
||||
LogHandler.log(LOGGER, TRACE, "set variable " + arg0 + " currentValue: " + arg1);
|
||||
if (isVariable(arg0)) {
|
||||
arg0 = arg0.substring(1);
|
||||
}
|
||||
if (arg0.equals("TIME")) {
|
||||
return null;
|
||||
}
|
||||
return super.put(arg0, arg1);
|
||||
}
|
||||
|
||||
public Object get(String key) {
|
||||
String variableName = key;
|
||||
if (variableName.equalsIgnoreCase("$NULL")) {
|
||||
LogHandler.log(LOGGER, DEBUG, "return explicit null value");
|
||||
return null;
|
||||
} else if (variableName.equalsIgnoreCase("$EMPTY")) {
|
||||
LogHandler.log(LOGGER, DEBUG, "return explicit empty string value");
|
||||
return "";
|
||||
} else if (variableName.startsWith("$TIME")) {
|
||||
return getTimeVariable(variableName, System.currentTimeMillis());
|
||||
}
|
||||
if (isVariable(variableName)) {
|
||||
variableName = variableName.substring(1);
|
||||
}
|
||||
|
||||
// angelehnt an die C++ Syntax...
|
||||
if (variableName.contains("->")) {
|
||||
return getGetterValue(variableName);
|
||||
|
||||
}
|
||||
|
||||
// einige Sonderfaelle abhandeln
|
||||
if (variableName.endsWith(".length")) // Laenge eines Arrays oder eines Strings
|
||||
{
|
||||
String newVar = variableName.substring(0, variableName.length() - 7);
|
||||
if (newVar.contains("[")) {
|
||||
newVar = newVar.substring(0, newVar.indexOf("["));
|
||||
}
|
||||
Object x = super.get(newVar);
|
||||
if (x == null) {
|
||||
LogHandler.log(LOGGER, ERROR, "variable '" + newVar + "' not found");
|
||||
return null;
|
||||
}
|
||||
if (x.getClass() == String.class) {
|
||||
return ((String) x).length();
|
||||
} else if (x.getClass().isArray()) {
|
||||
return Array.getLength(x);
|
||||
} else if (x instanceof List<?>) {
|
||||
return ((List<?>) x).size();
|
||||
}
|
||||
} else if (variableName.contains("[")) {
|
||||
// zugriff auf Array-Indizes
|
||||
// Beispiel: productInfo.infos[4].partNr
|
||||
// die Variable ist productInfo.infos
|
||||
String varName = variableName.substring(0, variableName.indexOf("["));
|
||||
|
||||
LogHandler.log(LOGGER, TRACE, "looking for array-variable " + varName);
|
||||
Object variable = super.get(varName);
|
||||
if (variable == null) {
|
||||
LogHandler.log(LOGGER, ERROR, "variable '" + varName + "' not found");
|
||||
|
||||
// der Reihe nach suchen ob eine Object-Variable gefunden wurde...
|
||||
// bsp.: $r1.return.subPanelStates[0].place
|
||||
// 1. suchen nach einer Variable r1.return.subPanelStates,
|
||||
// wenn nicht gefunden, dann
|
||||
// r1.return
|
||||
// wenn nicht gefunden, dann
|
||||
// r1
|
||||
// wenn nicht gefunden, dann
|
||||
// wirklicher Fehler.
|
||||
// falls gefunden dann ab hier weiter aufloesen per reflection weiter durchgehen...
|
||||
int dotPosition = -1;
|
||||
while (variable == null && varName.length() > 0) {
|
||||
dotPosition = varName.lastIndexOf(".");
|
||||
if (dotPosition > 0) {
|
||||
varName = varName.substring(0, dotPosition);
|
||||
} else {
|
||||
varName = "";
|
||||
}
|
||||
variable = super.get(varName);
|
||||
}
|
||||
|
||||
if (variable == null) {
|
||||
return null;
|
||||
}
|
||||
String fieldDescription = variableName.substring(dotPosition + 1);
|
||||
|
||||
// ab hier sollte per reflection jedes Feld weiter gesucht werden
|
||||
return getFieldFromObject(variable, fieldDescription);
|
||||
}
|
||||
LogHandler.log(LOGGER, TRACE, "variable '" + varName + "' found");
|
||||
|
||||
if (!variable.getClass().isArray()) {
|
||||
LogHandler.log(LOGGER, WARN, "variable '" + varName + "' is not an array variable");
|
||||
if (!(variable instanceof List<?>)) {
|
||||
return null;
|
||||
}
|
||||
LogHandler.log(LOGGER, INFO, "variable '" + varName + "' is a list variable");
|
||||
}
|
||||
|
||||
String indexName = key.substring(key.indexOf("[") + 1, key.lastIndexOf("]"));
|
||||
String subIndexName = "";
|
||||
int subIndex = -1;
|
||||
if (indexName.contains(",")) {
|
||||
indexName = key.substring(key.indexOf("[") + 1, key.indexOf(",", key.indexOf("[") + 1));
|
||||
subIndexName = key.substring(key.indexOf(",", key.indexOf("[") + 1) + 1, key.lastIndexOf("]"));
|
||||
}
|
||||
int index = -1;
|
||||
if (isVariable(indexName)) {
|
||||
index = (Integer) get(indexName);
|
||||
} else {
|
||||
index = Integer.parseInt(indexName);
|
||||
}
|
||||
if (!subIndexName.equals("")) {
|
||||
if (isVariable(subIndexName)) {
|
||||
subIndex = (Integer) get(subIndexName);
|
||||
} else {
|
||||
subIndex = Integer.parseInt(subIndexName);
|
||||
}
|
||||
}
|
||||
|
||||
String[] fieldPath = null;
|
||||
try {
|
||||
fieldPath = key.substring(key.lastIndexOf("]") + 2, key.length()).split("\\.");
|
||||
} catch (Exception e) {
|
||||
}
|
||||
if (variable instanceof List<?>) {
|
||||
LogHandler.log(LOGGER, TRACE, "looking for index " + index + " for list variable " + varName);
|
||||
LogHandler.log(LOGGER, TRACE, "length for list variable " + varName + "is " + ((List<?>) variable).size());
|
||||
} else if (variable.getClass().isArray()) {
|
||||
LogHandler.log(LOGGER, TRACE, "looking for index " + index + " for array variable " + varName);
|
||||
LogHandler.log(LOGGER, TRACE, "length for array ariable " + varName + " is " + Array.getLength(variable));
|
||||
}
|
||||
|
||||
try {
|
||||
Object k = null;
|
||||
if (variable.getClass().isArray()) {
|
||||
k = Array.get(variable, index);
|
||||
} else if (variable instanceof List<?>) {
|
||||
k = ((List<?>) variable).get(index);
|
||||
} else {
|
||||
k = Array.get(variable, index);
|
||||
}
|
||||
if (fieldPath == null) {
|
||||
if (subIndex < 0) {
|
||||
return k;
|
||||
}
|
||||
if (k instanceof String[]) {
|
||||
return ((String[]) k)[subIndex];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// den Pfad entlang gehen. solange es Punkte gibt...
|
||||
for (int i = 0; i < fieldPath.length; i++) {
|
||||
LogHandler.log(LOGGER, TRACE, "looking for field " + fieldPath[i]);
|
||||
Field field = k.getClass().getDeclaredField(fieldPath[i]);
|
||||
field.setAccessible(true);
|
||||
k = field.get(k);
|
||||
LogHandler.log(LOGGER, TRACE,
|
||||
"value for field " + fieldPath[i] + " for array variable " + varName + " index " + index + " is " + k);
|
||||
}
|
||||
return k;
|
||||
|
||||
} catch (ArrayIndexOutOfBoundsException e) {
|
||||
LogHandler.log(LOGGER, ERROR, "index " + index + " for array variable " + varName + " is out of bound!");
|
||||
} catch (NoSuchFieldException e) {
|
||||
LogHandler.log(LOGGER, ERROR, "array variable " + varName + " does not contain field " + "" + "!");
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(LOGGER, ERROR, "getting value for array variable $" + varName + " failed", e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
Object variable = super.get(variableName);
|
||||
// strukturierter Parameter mit fields
|
||||
// wenn es eine strukturierte Variable ist
|
||||
if (variable == null && variableName.contains(".")) {
|
||||
// die strukturierte Variable holen
|
||||
|
||||
String varName = variableName;
|
||||
LogHandler.log(LOGGER, DEBUG, "variable " + varName + " not found");
|
||||
|
||||
int dotPosition = -1;
|
||||
while (variable == null && varName.length() > 0) {
|
||||
dotPosition = varName.lastIndexOf(".");
|
||||
if (dotPosition > 0) {
|
||||
varName = varName.substring(0, dotPosition);
|
||||
} else {
|
||||
varName = "";
|
||||
}
|
||||
|
||||
LogHandler.log(LOGGER, DEBUG, "locate variable " + varName);
|
||||
variable = super.get(varName);
|
||||
}
|
||||
|
||||
if (variable == null) {
|
||||
LogHandler.log(LOGGER, ERROR, "variable " + varName + " not available !!!");
|
||||
return null;
|
||||
}
|
||||
|
||||
LogHandler.log(LOGGER, DEBUG, "found variable " + varName + "!");
|
||||
|
||||
String structVariableFieldName = variableName.substring(varName.length() + 1);
|
||||
Object v = getFieldFromObject(variable, structVariableFieldName);
|
||||
return v;
|
||||
}
|
||||
|
||||
return variable;
|
||||
}
|
||||
|
||||
protected Object getGetterValue(String variableName) {
|
||||
// der Part vor dem -> ist der Variablenname, der Teil danach ist der Name einer Getter-Funktion
|
||||
String sVar = "$" + variableName.substring(0, variableName.indexOf("->"));
|
||||
String sGetterName = variableName.substring(variableName.indexOf("->") + 2, variableName.length());
|
||||
|
||||
// iterativ through all strings function1()->function2->function3()->function4()
|
||||
// the items in the result list does not contain (), an is here like function1, function2, function 3, function4
|
||||
|
||||
List<String> functionNames = getFunctionNames(sGetterName);
|
||||
Object x = get(sVar);
|
||||
if (x == null) {
|
||||
LogHandler.log(LOGGER, DEBUG, "object " + sVar + " not found in variableEngine");
|
||||
return null;
|
||||
}
|
||||
LogHandler.log(LOGGER, INFO, "object " + sVar + " found");
|
||||
for (String function : functionNames) {
|
||||
// if function has Params create simple integer parameter
|
||||
String origFunction = function;
|
||||
Object param = null;
|
||||
if (function.contains("(")) {
|
||||
String sParam = function.substring(function.indexOf("(") + 1, function.indexOf(")"));
|
||||
if (!sParam.isEmpty()) {
|
||||
param = Integer.valueOf(sParam);}
|
||||
function = function.substring(0, function.indexOf("("));
|
||||
}
|
||||
// call the functions on the determined object
|
||||
try {
|
||||
LogHandler.log(LOGGER, DEBUG, "locate method " + function + " on object");
|
||||
if (param != null) {
|
||||
Method method = x.getClass().getMethod(function, int.class);
|
||||
LogHandler.log(LOGGER, DEBUG, "call method " + function + "("+param+") on object");
|
||||
x = method.invoke(x, param);
|
||||
} else {
|
||||
Method method = x.getClass().getMethod(function);
|
||||
LogHandler.log(LOGGER, DEBUG, "call method " + function + " on object");
|
||||
x = method.invoke(x);
|
||||
}
|
||||
|
||||
if (origFunction.contains(".length") || origFunction.contains(".size")) {
|
||||
if (x.getClass().isArray()) {
|
||||
return Array.getLength(x);
|
||||
}
|
||||
if (x instanceof List<?>) {
|
||||
return ((List<?>) x).size();
|
||||
}
|
||||
}
|
||||
|
||||
} catch (NoSuchMethodException e) {
|
||||
LogHandler.log(LOGGER, DEBUG, "method " + sVar + " not found on object, available methods are");
|
||||
for (Method m : x.getClass().getMethods()) {
|
||||
LogHandler.log(LOGGER, DEBUG, getModifierString(m.getModifiers()) + m.getReturnType().getSimpleName() + " "
|
||||
+ m.getDeclaringClass().getSimpleName() + "." + m.getName() + "(" + ")");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(LOGGER, ERROR, "calling method on object failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
// split text function1()->function2()->function3()->function4()
|
||||
// the a list like function1, function2, function 3, function4
|
||||
protected List<String> getFunctionNames(String sGetterName) {
|
||||
String[] result = sGetterName.split("->");
|
||||
List<String> resultList = new ArrayList<String>();
|
||||
for (String item : result) {
|
||||
if (item.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (item.endsWith("()")) {
|
||||
resultList.add(item.substring(0, item.length() - 2));
|
||||
continue;
|
||||
}
|
||||
resultList.add(item);
|
||||
}
|
||||
|
||||
return resultList;
|
||||
}
|
||||
|
||||
private String getModifierString(int modifiers) {
|
||||
String k = "";
|
||||
for (IMODIFIER mod : IMODIFIER.values()) {
|
||||
if ((modifiers & mod.getValue()) == mod.value) {
|
||||
k = k + mod.name() + " ";
|
||||
}
|
||||
|
||||
}
|
||||
return k;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param variable
|
||||
* eine Objekt, das felder (einfache unStrkturierte Felder) als auch Arrays enthalten darf.
|
||||
* @param fieldDescription
|
||||
* ein String, enthaelt den Zugriff auf ein Objekt als Text, z.B. subPanelState[0].place
|
||||
* <p>
|
||||
* wenn das Objekt ein Feld subPanelStates enthaelt, und dieses ein Array ist, wird der Wert des Feldes
|
||||
* placed des ersten Elements des Arrays zu ermitteln
|
||||
* @return
|
||||
*/
|
||||
protected Object getFieldFromObject(Object variable, String fieldDescription) {
|
||||
// jeweils den Text bis zum nächsten Punkt oder bis zum ende holen...
|
||||
Object tempObject = variable;
|
||||
try {
|
||||
|
||||
String remainingFields = fieldDescription;
|
||||
do {
|
||||
LogHandler.log(LOGGER, DEBUG, "get " + remainingFields + " from object");
|
||||
String currentFieldName = remainingFields;
|
||||
int dotPosition = currentFieldName.indexOf(".");
|
||||
String fieldName = "";
|
||||
if (dotPosition > 0) {
|
||||
fieldName = currentFieldName.substring(0, dotPosition);
|
||||
} else {
|
||||
fieldName = currentFieldName;
|
||||
}
|
||||
// Array???
|
||||
String sIndex = "";
|
||||
int index = -1;
|
||||
if (fieldName.indexOf("[") > 0) {
|
||||
// index wegnehmen
|
||||
sIndex = currentFieldName.substring(fieldName.indexOf("[") + 1, dotPosition - 1);
|
||||
index = Integer.parseInt(sIndex);
|
||||
fieldName = fieldName.substring(0, fieldName.indexOf("["));
|
||||
}
|
||||
|
||||
if (index >= 0) {
|
||||
LogHandler.log(LOGGER, DEBUG, "get field: " + fieldName + "[" + index + "] from object");
|
||||
} else {
|
||||
LogHandler.log(LOGGER, DEBUG, "get field: " + fieldName + " from object");
|
||||
}
|
||||
|
||||
// dieses Feld holen, bei geerbten privaten Feldern bis zum Object hoch gehen
|
||||
Class<?> c = tempObject.getClass();
|
||||
Field field = null;
|
||||
while (field == null && c != Object.class) {
|
||||
try {
|
||||
field = c.getField(fieldName);
|
||||
} catch (NoSuchFieldException nsfe) {
|
||||
try {
|
||||
field = c.getDeclaredField(fieldName);
|
||||
} catch (NoSuchFieldException nsfdecl) {
|
||||
c = c.getSuperclass();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (field == null) {
|
||||
return null;
|
||||
}
|
||||
field.setAccessible(true);
|
||||
|
||||
// in diesem Objekt ein weiteres Unterfeld holen (verschachtelte struktur)
|
||||
tempObject = field.get(tempObject);
|
||||
LogHandler.log(LOGGER, DEBUG, "value for field " + fieldName + " resolved");
|
||||
if (index >= 0) {
|
||||
LogHandler.log(LOGGER, DEBUG, "value for array element " + index + " from object resolved");
|
||||
// vereinfachter Zugriff auf Listen wie auf Arrays via [index]
|
||||
if (tempObject.getClass().isArray()) {
|
||||
tempObject = Array.get(tempObject, index);
|
||||
} else if (tempObject instanceof List) {
|
||||
tempObject = ((List<?>) tempObject).get(index);
|
||||
}
|
||||
}
|
||||
|
||||
if (dotPosition >= 0) {
|
||||
remainingFields = remainingFields.substring(dotPosition + 1);
|
||||
} else {
|
||||
remainingFields = "";
|
||||
}
|
||||
} while (!remainingFields.isEmpty());
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(LOGGER, ERROR, "can not resolve field from object", e);
|
||||
}
|
||||
return tempObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* ausgeben aller Variablen des Testcase.
|
||||
*
|
||||
* @param withStructure
|
||||
* ist withStructure true werden alle Felder (auch private und protected Felder) mit ausgegeben
|
||||
*/
|
||||
public void dump(boolean withStructure) {
|
||||
LogHandler.log(LOGGER, INFO, "dump variables");
|
||||
// order list
|
||||
List<String> variableNames = new ArrayList<String>();
|
||||
variableNames.addAll(keySet());
|
||||
Collections.sort(variableNames);
|
||||
for (String key : variableNames) {
|
||||
Object varValue = get(key);
|
||||
if (varValue instanceof Number) {
|
||||
LogHandler.log(LOGGER, DEBUG, "variable $" + key + "=" + varValue.toString());
|
||||
} else if (varValue instanceof String) {
|
||||
LogHandler.log(LOGGER, DEBUG, "variable $" + key + "=" + varValue);
|
||||
} else {
|
||||
Writer k = null;
|
||||
try {
|
||||
if (withStructure) {
|
||||
k = structuredSerializer.serialize(varValue);
|
||||
} else {
|
||||
k = serializer.serialize(varValue);
|
||||
}
|
||||
LogHandler.log(LOGGER, DEBUG, "variable $" + key + "=" + k.toString());
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(LOGGER, ERROR, "writing variable $" + key + " to dump failed", e);
|
||||
} finally {
|
||||
if (k != null)
|
||||
try {
|
||||
k.close();
|
||||
} catch (IOException exception) {
|
||||
LogHandler.log(LOGGER, ERROR, "writing variable $" + key + " stream not closed", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
LogHandler.log(LOGGER, INFO, "dump finished");
|
||||
}
|
||||
|
||||
/**
|
||||
* Diese funktion prueft ob eine Variable bereits enthalten ist
|
||||
*
|
||||
* @param variable
|
||||
* darf am Anfang das $-Zeichen haben, muss es aber nicht<br>
|
||||
* Bsp.: <br>
|
||||
* <code>containsVariable("result")</code><br>
|
||||
* oder auch<br>
|
||||
* <code>containsVariable("$result")</code>
|
||||
* @return true, wenn es diese Variable gibt, false in allen anderen Faellen
|
||||
*/
|
||||
public boolean containsVariable(String variable) {
|
||||
if (isVariable(variable)) {
|
||||
variable = variable.substring(1);
|
||||
}
|
||||
if (variable.startsWith("TIME")) {
|
||||
return true;
|
||||
}
|
||||
return get(variable) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Diese Funktion liefert die aktuelle Zeit in einem besonderen Format. Es gibt die Moeglichkeiten das Datum in
|
||||
* verschiedenen Formaten zu erhalten,, z.B.als integer(Sekunden seit 1970), als long(millies seit 1970) und als
|
||||
* formatierter Text. Ausserdem kann eine Zeitdifferenz in addiert oder subtrahiert werden
|
||||
*
|
||||
* @param variableName
|
||||
* @param currentTime
|
||||
* @return
|
||||
*/
|
||||
protected Object getTimeVariable(String timeString, long currentTime) {
|
||||
if (timeString.startsWith("$TIMEGMT0")) {
|
||||
int gmtOffset = TimeZone.getDefault().getRawOffset();
|
||||
currentTime = currentTime - gmtOffset;
|
||||
// wenn in der Zeitzone des Host, auf dem das DataInterface läuft, Sommerzeit überhaupt benutzt werden kann
|
||||
// und diese Zeit sich im Sommerzeit-Bereich befindet, die Zeit um den Sommerzeitoffset korrigieren
|
||||
Date localeTime = new Date(currentTime);
|
||||
if (TimeZone.getDefault().inDaylightTime(localeTime)) {
|
||||
currentTime = currentTime - TimeZone.getDefault().getDSTSavings();
|
||||
}
|
||||
}
|
||||
|
||||
if (!timeString.contains("(") && !timeString.contains(")")) {
|
||||
// integer
|
||||
return DateConvert.convertLongDateToInt(currentTime);
|
||||
}
|
||||
long correctedTime = currentTime;
|
||||
String contentOption = timeString.substring(timeString.indexOf("(") + 1, timeString.indexOf(")"));
|
||||
|
||||
String[] temp = contentOption.split("\\,");
|
||||
String format = "";
|
||||
String offset = "";
|
||||
char sign = '+';
|
||||
if (temp != null) {
|
||||
if (temp.length >= 1) {
|
||||
format = temp[0].trim();
|
||||
}
|
||||
if (temp.length > 1) {
|
||||
offset = temp[1].trim();
|
||||
if (offset.charAt(0) == '+' || offset.charAt(0) == '-') {
|
||||
// vorzeichen wegnehmen
|
||||
sign = offset.charAt(0);
|
||||
offset = offset.substring(1, offset.length());
|
||||
}
|
||||
}
|
||||
if (temp.length > 2) {
|
||||
String millies = temp[2].trim();
|
||||
offset = offset + "," + millies;
|
||||
} else if (temp.length == 2) {
|
||||
offset = offset + ",000";
|
||||
}
|
||||
|
||||
if (!offset.isEmpty()) {
|
||||
long timeDifference = 0;
|
||||
try {
|
||||
timeDifference = sdf.parse(offset).getTime() + TimeZone.getDefault().getOffset(0);
|
||||
if (sign == '-') {
|
||||
timeDifference = -1 * timeDifference;
|
||||
}
|
||||
} catch (ParseException e) {
|
||||
LogHandler.log(LOGGER, ERROR, "parseException", e);
|
||||
return null;
|
||||
}
|
||||
correctedTime = currentTime + timeDifference;
|
||||
}
|
||||
}
|
||||
|
||||
if (format.equals("int")) {
|
||||
return DateConvert.convertLongDateToInt(correctedTime);
|
||||
} else if (format.equals("date")) {
|
||||
return new Date(correctedTime);
|
||||
} else if (format.equals("long")) {
|
||||
return correctedTime;
|
||||
} else {
|
||||
SimpleDateFormat customFormat = (SimpleDateFormat) SimpleDateFormat.getTimeInstance();
|
||||
customFormat.applyPattern(format);
|
||||
return customFormat.format(new Date(correctedTime));
|
||||
}
|
||||
}
|
||||
|
||||
public static long getSequence() {
|
||||
sequence++;
|
||||
if (sequence == 1000000) {
|
||||
sequence = 0;
|
||||
}
|
||||
return sequence;
|
||||
}
|
||||
|
||||
public static boolean isVariable(String keyName) {
|
||||
return keyName.startsWith("$");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
public class VariableExpression {
|
||||
private String text;
|
||||
private VariableExpression indexExpression;
|
||||
private VariableExpression nextExpression;
|
||||
private VariableExpression parent;
|
||||
|
||||
private int getLength() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
|
||||
String k = "";
|
||||
if (text != null) {
|
||||
k = k + text;
|
||||
}
|
||||
if (indexExpression != null) {
|
||||
k = k + '[' + indexExpression.toString() + ']';
|
||||
}
|
||||
if (nextExpression != null) {
|
||||
k = k + '.' + nextExpression.toString();
|
||||
}
|
||||
|
||||
return k;
|
||||
}
|
||||
|
||||
public String getVarPath() {
|
||||
|
||||
String k = "";
|
||||
if (parent != null) {
|
||||
k = parent.getVarPath();
|
||||
} else {
|
||||
return text;
|
||||
}
|
||||
|
||||
k = k + '.' + text;
|
||||
return k;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,708 @@
|
||||
/*
|
||||
* Copyright (c) 2014 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied, printed, edited
|
||||
* or otherwise distributed, be stored in a retrieval system, or be translated into another language without the written permission
|
||||
* of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
import static com.itac.util.logging.LogLevel.TRACE;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.lang.reflect.UndeclaredThrowableException;
|
||||
import java.util.Hashtable;
|
||||
|
||||
import org.omg.CORBA.IntHolder;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import com.itac.artes.ihap.CommunicationException;
|
||||
import com.itac.artes.ihas.LookupException;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.XmlParameter;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.mes.imsapi.domain.container.IMSApiSessionContextStruct;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlApiFunction extends XmlConstruct {
|
||||
|
||||
private static final String LOGGER = XmlApiFunction.class.getSimpleName();
|
||||
|
||||
public static final String EWAPI = "EWAPI";
|
||||
public static final String IMSAPI = "IMSAPI";
|
||||
public static final String TARGET = "target";
|
||||
public static final int EWAPI_FUNCTION = 0;
|
||||
public static final int IMSAPI_FUNCTION = 1;
|
||||
// beschreibt, in welchem service die Methode aufgerufen werden soll, also entweder EW-Api oder IMS-API
|
||||
public int apiSource;
|
||||
// die Methode die aufgerufen werden soll
|
||||
private Method method;
|
||||
|
||||
public XmlApiFunction(String id) {
|
||||
super(id);
|
||||
iName = "apiCall";
|
||||
}
|
||||
|
||||
/**
|
||||
* Der Name der API-Funktion, die ausgefuehrt werden soll
|
||||
*/
|
||||
private String functionName;
|
||||
/**
|
||||
* alle Parameter, die im urspruenglichen XML-File enthalten waren, nicht jedoch die strukturierten Typen
|
||||
*/
|
||||
private Hashtable<String, XmlParameter> params = new Hashtable<String, XmlParameter>();
|
||||
/**
|
||||
* die Namen der Parameter
|
||||
*/
|
||||
private String[] parameterNames;
|
||||
/**
|
||||
* alle Typen zu den Parametern
|
||||
*/
|
||||
private Class<?>[] paramTypes;
|
||||
private Hashtable<String, Node> structuredParameters = new Hashtable<String, Node>();
|
||||
|
||||
public void setFunctionName(String functionName) {
|
||||
this.functionName = functionName;
|
||||
}
|
||||
|
||||
public void add(XmlParameter xmlParameter) {
|
||||
params.put(xmlParameter.getName(), xmlParameter);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "api id(" + getId() + ")" + functionName;
|
||||
}
|
||||
|
||||
private String getErrorHeader() {
|
||||
return "functionID: " + getId() + "\nAPI function '" + functionName + "\n";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
// pruefen, od diese Funktion ueberhaupt ausgefuehrt werden darf
|
||||
super.execute(services);
|
||||
|
||||
// Assertion:
|
||||
// Funktion wird nur dann ausgefuehrt, wenn das parsen vorher auch in Ordnung war
|
||||
Element functionElement = getTestCase().getDocument().createElement(functionName);
|
||||
callElement.appendChild(functionElement);
|
||||
|
||||
if (apiSource == EWAPI_FUNCTION) {
|
||||
addAttribute(callElement, TARGET, EWAPI);
|
||||
} else {
|
||||
addAttribute(callElement, TARGET, IMSAPI);
|
||||
}
|
||||
|
||||
if (method == null) {
|
||||
throw new NullPointerException(getErrorHeader() + "API function not found");
|
||||
}
|
||||
|
||||
// Object mit allen Eingabeparametern erzeugen
|
||||
Object[] args = new Object[paramTypes.length];
|
||||
|
||||
// alle nicht bekannten Parameter als Variablen erzeugen
|
||||
try {
|
||||
createInputParameter(functionElement, args, services);
|
||||
} catch (NullPointerException npe) {
|
||||
throw npe;
|
||||
} catch (Throwable th) {
|
||||
throw new NullPointerException(th.getMessage());
|
||||
}
|
||||
boolean argsOK = true;
|
||||
LogHandler.log(LOGGER, INFO, "check input Parameter for API function " + method.getName());
|
||||
String emptyParams = "";
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
if (args[i] == null) {
|
||||
// Wenn ein eingabeparameter nicht gesetzt ist braucht man die API nicht aufzurufen; es kann nur
|
||||
// fehlschlagen
|
||||
argsOK = false;
|
||||
emptyParams += "input parameter(s) '" + parameterNames[i] + "' is null";
|
||||
continue;
|
||||
}
|
||||
}
|
||||
StringBuffer paramTypeTest = new StringBuffer(emptyParams);
|
||||
if (argsOK) {
|
||||
// Typen der Eingabeparameter prüfen
|
||||
LogHandler.log(LOGGER, INFO, "check input Parameter types for API function " + method.getName() + "', id ='" + getId() + "'");
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
if (!compareTypes(paramTypes[i], args[i].getClass(), parameterNames[i], paramTypeTest)) {
|
||||
argsOK = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!argsOK) {
|
||||
throw new NullPointerException(getErrorHeader() + "function not called, because " + paramTypeTest);
|
||||
}
|
||||
LogHandler.log(LOGGER, INFO, "all input parameters set");
|
||||
Object returnValue = null;
|
||||
try {
|
||||
// Der API-Call an sich
|
||||
if (apiSource == EWAPI_FUNCTION) {
|
||||
returnValue = method.invoke(services.getAPIServices(), args);
|
||||
} else {
|
||||
returnValue = method.invoke(services.getIMSApiService(), args);
|
||||
}
|
||||
getTestCase().getVariableEngine().put(getId() + "." + returnValue.getClass().getSimpleName(), returnValue);
|
||||
} catch (Throwable e) {
|
||||
Throwable th = e;
|
||||
do {
|
||||
if (th instanceof InvocationTargetException) {
|
||||
th = ((InvocationTargetException) th).getTargetException();
|
||||
} else if (th instanceof UndeclaredThrowableException) {
|
||||
th = ((UndeclaredThrowableException) th).getUndeclaredThrowable();
|
||||
} else if (th instanceof CommunicationException) {
|
||||
th = ((CommunicationException) th).getCause();
|
||||
} else if (th instanceof LookupException) {
|
||||
throw new TestcaseException((LookupException) th);
|
||||
} else {
|
||||
th = null;
|
||||
}
|
||||
} while (th != null);
|
||||
LogHandler.log(LOGGER, ERROR, "api-Call " + functionName + " failed", e);
|
||||
// die Exception als output-Parameter anhaengen
|
||||
Element outputParameter = getTestCase().getDocument().createElement("exception");
|
||||
functionElement.appendChild(outputParameter);
|
||||
addAttribute(outputParameter, "type", e.getClass().getSimpleName());
|
||||
addAttribute(outputParameter, "message", e.getMessage());
|
||||
endFail();
|
||||
return;
|
||||
}
|
||||
|
||||
// Struktur fuer rueckgabewerte erzeugen
|
||||
Element outputParameter = getTestCase().getDocument().createElement("output");
|
||||
functionElement.appendChild(outputParameter);
|
||||
|
||||
// RueckgabeWerte als Variablen und in XML-Struktur eintragen
|
||||
LogHandler.log(LOGGER, INFO, "api-Call " + functionName + " returned " + returnValue.toString());
|
||||
// jetzt nur noch die strukturierte Ausgabe erzeugen
|
||||
createOutputParameter(outputParameter, "$RETURN", returnValue);
|
||||
// wenn keine Exception oder sonstige Fehler aufgetreten sind ist diese funktion erfolgreich ausgeführt worden.
|
||||
endPass();
|
||||
}
|
||||
|
||||
private boolean compareTypes(Class<?> clazz1, Class<? extends Object> clazz2, String paramName, StringBuffer result) {
|
||||
if (clazz1.equals(clazz2)) {
|
||||
return true;
|
||||
}
|
||||
if ((clazz1.equals(int.class) || clazz1.equals(Integer.class)) && (clazz2.equals(int.class) || clazz2.equals(Integer.class))) {
|
||||
return true;
|
||||
}
|
||||
if ((clazz1.equals(long.class) || clazz1.equals(Long.class)) && (clazz2.equals(long.class) || clazz2.equals(Long.class))) {
|
||||
return true;
|
||||
}
|
||||
if ((clazz1.equals(boolean.class) || clazz1.equals(Boolean.class))
|
||||
&& (clazz2.equals(boolean.class) || clazz2.equals(Boolean.class))) {
|
||||
return true;
|
||||
}
|
||||
if ((clazz1.equals(double.class) || clazz1.equals(Double.class))
|
||||
&& (clazz2.equals(double.class) || clazz2.equals(Double.class))) {
|
||||
return true;
|
||||
}
|
||||
if ((clazz1.equals(float.class) || clazz1.equals(Float.class)) && (clazz2.equals(float.class) || clazz2.equals(Float.class))) {
|
||||
return true;
|
||||
}
|
||||
if ((clazz1.equals(char.class) || clazz1.equals(Character.class))
|
||||
&& (clazz2.equals(char.class) || clazz2.equals(Character.class))) {
|
||||
return true;
|
||||
}
|
||||
result.append("parameter '").append(paramName).append("' requested type='").append(clazz1.getSimpleName())
|
||||
.append("', given type='").append(clazz2.getClass().getSimpleName()).append("'\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* aus den Werten, die im args-Array enthalten sind und aus den Typen und Namen der Parameter werden die Ausgaben sowohl fuer das
|
||||
* Protokoll als auch fuer die Variablen erzeugt
|
||||
*
|
||||
* @param outputParameter
|
||||
* @param args
|
||||
*/
|
||||
private void createOutputParameter(Element outputParameter, String varName, Object value) {
|
||||
// ueber alle Parameter iterieren, fuer alle Holder die Werte in die entsprechenden Variablen eintragen
|
||||
try {
|
||||
getTestCase().getVariableEngine().put(varName, value);
|
||||
|
||||
// return-Parameter setzen aus return_value
|
||||
Field[] declaredFields = value.getClass().getDeclaredFields();
|
||||
for (Field declaredField : declaredFields) {
|
||||
if (declaredField.getModifiers() != Modifier.PUBLIC) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Field field = value.getClass().getField(declaredField.getName());
|
||||
Object attribute = field.get(value);
|
||||
if (attribute == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (declaredField.getName().equalsIgnoreCase("return_value")) {
|
||||
getTestCase().getVariableEngine().put("$RETURN", attribute);
|
||||
}
|
||||
|
||||
getTestCase().getVariableEngine().put(getId() + "." + declaredField.getName(), attribute);
|
||||
}
|
||||
|
||||
// einfacher strukturierter Parameter
|
||||
Element subElement = getStructuredElement(value);
|
||||
outputParameter.appendChild(subElement);
|
||||
} catch (Throwable e) {
|
||||
LogHandler.log(LOGGER, INFO, "MesExceptionHandler process throwable " + method.getName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void createInputParameter(Element functionElement, Object[] args, DataInterfaceServices services)
|
||||
throws InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException,
|
||||
InvocationTargetException {
|
||||
Element inputParameter = getTestCase().getDocument().createElement("input");
|
||||
functionElement.appendChild(inputParameter);
|
||||
|
||||
for (int i = 0; i < paramTypes.length; i++) {
|
||||
if (!params.containsKey(parameterNames[i])) {
|
||||
//
|
||||
LogHandler.log(LOGGER, TRACE, "create a new parameter for " + paramTypes[i].getSimpleName());
|
||||
if (paramTypes[i].getName().startsWith("com.itac.easyworks.api.idl")
|
||||
|| paramTypes[i].getName().startsWith("com.itac.mes.imsapi.domain.container")) {
|
||||
if (paramTypes[i].isArray()) {
|
||||
args[i] = paramTypes[i].newInstance();
|
||||
} else {
|
||||
String componentClassName = paramTypes[i].getSimpleName();
|
||||
args[i] = getStructuredValue(getTestCase().getDocument(), componentClassName, inputParameter, parameterNames[i]);
|
||||
}
|
||||
} else if (paramTypes[i].isArray()) {
|
||||
// Array-Strukturen zuweisen
|
||||
LogHandler.log(LOGGER, TRACE, "create empty parameter " + paramTypes[i].getName());
|
||||
// arrayClass =
|
||||
String arrayClassName = paramTypes[i].getSimpleName();
|
||||
String arrayComponentClassName = arrayClassName.substring(0, arrayClassName.length() - 2);
|
||||
args[i] = getStructuredArray(getTestCase().getDocument(), arrayComponentClassName, inputParameter, parameterNames[i]);
|
||||
}
|
||||
} else {
|
||||
// den uebergebenen Parameter mit dem richtigen Typ uebergeben
|
||||
// einfacher unstrukturierter Parameter, kein Array, sondern String, Integer, int, ...
|
||||
LogHandler.log(LOGGER, TRACE, "Parameter = " + parameterNames[i]);
|
||||
|
||||
args[i] = getParameterValue(paramTypes[i], parameterNames[i], params.get(parameterNames[i]).getValue());
|
||||
// wenn args[i] null ist dann handelt es sich um einen InOut -Parameter, der mit Werten gesetzt wird
|
||||
if (args[i] == null) {
|
||||
if (paramTypes[i] == char.class) {
|
||||
LogHandler.log(LOGGER, TRACE, "Parameter is simple char = " + parameterNames[i]);
|
||||
char c = Character.valueOf(params.get(parameterNames[i]).getValue().charAt(0));
|
||||
args[i] = c;
|
||||
} else if (paramTypes[i] == IMSApiSessionContextStruct.class) {
|
||||
args[i] = services.getImsSession();
|
||||
addAttribute(inputParameter, parameterNames[i], "" + services.getImsSession().sessionId);
|
||||
continue;
|
||||
} else if (paramTypes[i] == new String[] {}.getClass()) {
|
||||
LogHandler.log(LOGGER, TRACE, "Parameter is StringArray " + parameterNames[i]);
|
||||
args[i] = getStructuredArray(getTestCase().getDocument(), String[].class.getName(), inputParameter, parameterNames[i]);
|
||||
// params.get(parameterNames[i]).getValue().split("\\|");
|
||||
} else if (paramTypes[i] == IntHolder.class) {
|
||||
LogHandler.log(LOGGER, INFO, "Parameter is CORBA IntHolder " + parameterNames[i]);
|
||||
args[i] = getStructuredValue(getTestCase().getDocument(), IntHolder.class.getName(), inputParameter, parameterNames[i]);
|
||||
addAttribute(inputParameter, parameterNames[i], "" + ((IntHolder) args[i]).value);
|
||||
continue;
|
||||
}
|
||||
|
||||
}
|
||||
addAttribute(inputParameter, parameterNames[i], args[i].toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// aufbauen der wirklichen Struktur aus den XML-Daten
|
||||
public Object getStructuredValue(Document document, String elementClassName, Element inputParameter, String parameterName)
|
||||
throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException,
|
||||
InvocationTargetException {
|
||||
// den Wurzelknoten fuer diesen Parameter holen
|
||||
NodeList nodelist = structuredParameters.get(parameterName).getChildNodes();
|
||||
// Klasse der Elemente holen
|
||||
Class<?> componentClass = getClassForParameter(parameterName);
|
||||
if (componentClass.isArray()) {
|
||||
componentClass = componentClass.getComponentType();
|
||||
}
|
||||
|
||||
Element arrayElement = document.createElement(parameterName);
|
||||
for (int i = 0; i < nodelist.getLength(); i++) {
|
||||
Node subNode = nodelist.item(i);
|
||||
if (subNode.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
NamedNodeMap attributes = subNode.getAttributes();
|
||||
|
||||
Element strucElement = document.createElement(componentClass.getName());
|
||||
arrayElement.appendChild(strucElement);
|
||||
|
||||
// Instanz erzeugen (ein einzelnes array-Element
|
||||
Constructor<?> constructor = componentClass.getConstructor();
|
||||
Object object = constructor.newInstance();
|
||||
// Felder brauchen nicht mehr geprueft werden, das ist schon beim parsen passiert
|
||||
// Felder setzen
|
||||
|
||||
for (Field field : componentClass.getDeclaredFields()) {
|
||||
LogHandler.log(LOGGER, TRACE, "field =" + field.getName());
|
||||
Object value = attributes.getNamedItem(field.getName()).getNodeValue();
|
||||
LogHandler.log(LOGGER, TRACE, "attribute = " + value.toString());
|
||||
|
||||
if (VariableEngine.isVariable(value.toString())) {
|
||||
// ersetzen durch den Wert der Variablen
|
||||
String varName = value.toString().substring(1);
|
||||
value = getTestCase().getVariableEngine().get(varName);
|
||||
}
|
||||
safeSetField(field, object, value);
|
||||
addAttribute(document, strucElement, field.getName(), value.toString());
|
||||
}
|
||||
return object;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// aufbauen der wirklichen Struktur aus den XML-Daten
|
||||
public Object getStructuredArray(Document document, String elementClassName, Element inputParameter, String parameterName)
|
||||
throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException,
|
||||
InvocationTargetException {
|
||||
// Klasse der Elemente holen
|
||||
Class<?> componentClass = getClassForParameter(parameterName);
|
||||
if (componentClass.isArray()) {
|
||||
componentClass = componentClass.getComponentType();
|
||||
}
|
||||
String componentClassName = componentClass.getName().substring(componentClass.getName().lastIndexOf(".") + 1);
|
||||
|
||||
// den Wurzelknoten fuer diesen Parameter holen
|
||||
if (!structuredParameters.containsKey(parameterName)) {
|
||||
String subText = "";
|
||||
if (params.containsKey(parameterName)) {
|
||||
// unstrukturierten Wert fuer strukturierte Variable gefunden
|
||||
subText = ", found unstructured value " + params.get(parameterName).getValue() + " for parameter " + parameterName
|
||||
+ " instead";
|
||||
}
|
||||
throw new NullPointerException(getErrorHeader() + "missing values for variable " + parameterName + " of type "
|
||||
+ componentClassName + "[]" + subText);
|
||||
}
|
||||
NodeList nodelist = structuredParameters.get(parameterName).getChildNodes();
|
||||
|
||||
// arrayInstanz erstellen, die entsprechende Groesse feststellen, nur Elementknoten benutzen
|
||||
int arraySize = 0;
|
||||
String typeError = "";
|
||||
for (int i = 0; i < nodelist.getLength(); i++) {
|
||||
Node subNode = nodelist.item(i);
|
||||
if (subNode.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
// Die Tags muessen heissen wie der simpleClassName
|
||||
if (subNode.getNodeName().equals(elementClassName)) {
|
||||
arraySize++;
|
||||
} else {
|
||||
typeError += "wrong type for parameter '" + parameterName + "', expected='" + componentClassName + "', found='"
|
||||
+ subNode.getNodeName() + "'";
|
||||
}
|
||||
}
|
||||
if (!typeError.equals("")) {
|
||||
throw new NullPointerException(getErrorHeader() + typeError);
|
||||
}
|
||||
|
||||
Object arrayObject = Array.newInstance(componentClass, arraySize);
|
||||
// Jeder Elementknoten ist ein einzelnes Array-Element
|
||||
|
||||
Element arrayElement = document.createElement(parameterName);
|
||||
inputParameter.appendChild(arrayElement);
|
||||
int arrayIndex = 0;
|
||||
for (int i = 0; i < nodelist.getLength(); i++) {
|
||||
Node subNode = nodelist.item(i);
|
||||
if (subNode.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
NamedNodeMap attributes = subNode.getAttributes();
|
||||
|
||||
Element strucElement = document.createElement(componentClassName);
|
||||
arrayElement.appendChild(strucElement);
|
||||
|
||||
// Besonderbehandlung bei StringArray, jedes Element erwartet ein Attribut value
|
||||
if (componentClass.equals(String.class)) {
|
||||
// Es gibt ein Attribut value, in dem der Wert für dieses String-Array-Element steht
|
||||
String value = null;
|
||||
if (attributes == null || attributes.getLength() == 0) {
|
||||
// alternativ über den nodeValue...
|
||||
value = subNode.getTextContent();
|
||||
if (value != null) {
|
||||
LogHandler.log(LOGGER, TRACE, "direct text content");
|
||||
} else {
|
||||
LogHandler.log(LOGGER, ERROR, "no attributes and no direct text content found for String-Array parameter '"
|
||||
+ parameterName + "', function id ='" + getId() + "' ");
|
||||
return null;
|
||||
}
|
||||
} else if (attributes.getNamedItem("value") == null) {
|
||||
LogHandler.log(LOGGER, ERROR, "no attributes 'value' found, which is required for String-Array parameter '"
|
||||
+ parameterName + "', function id ='" + getId() + "' ");
|
||||
// current parameterName
|
||||
return null;
|
||||
} else {
|
||||
value = attributes.getNamedItem("value").getNodeValue();
|
||||
}
|
||||
if (VariableEngine.isVariable(value)) {
|
||||
value = getTestCase().getVariableEngine().get(value).toString();
|
||||
}
|
||||
Array.set(arrayObject, arrayIndex++, value);
|
||||
addAttribute(strucElement, "value", value.toString());
|
||||
} else {
|
||||
// Instanz erzeugen (ein einzelnes array-Element
|
||||
Constructor<?> constructor = componentClass.getConstructor();
|
||||
Object object = constructor.newInstance();
|
||||
// Felder brauchen nicht mehr geprueft werden, das ist schon beim parsen passiert
|
||||
// Felder setzen
|
||||
|
||||
for (Field field : componentClass.getDeclaredFields()) {
|
||||
LogHandler.log(LOGGER, TRACE, "field =" + field.getName());
|
||||
if (field.getName().startsWith("$jacoco")){continue;}
|
||||
Object value = attributes.getNamedItem(field.getName()).getNodeValue();
|
||||
LogHandler.log(LOGGER, TRACE, "attribute = " + value.toString());
|
||||
|
||||
if (VariableEngine.isVariable(value.toString())) {
|
||||
// ersetzen durch den Wert der Variablen
|
||||
String varName = value.toString().substring(1);
|
||||
value = getTestCase().getVariableEngine().get(varName);
|
||||
}
|
||||
safeSetField(field, object, value);
|
||||
addAttribute(document, strucElement, field.getName(), value.toString());
|
||||
}
|
||||
Array.set(arrayObject, arrayIndex++, object);
|
||||
}
|
||||
}
|
||||
return arrayObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* eine Variable (Array, strukturierte Variable oder Variable der impliziten Typen (int, bool, long..)) Darstellung: für eine
|
||||
* stukturierte Variable <code>
|
||||
* <MaterialBinData binLocationDescr="" binLocationNr="" chargeNr="ChargeQM2" cost="1.0" costBase="1" dateCode="28032007" .../>
|
||||
* </code> Darstellung für Array-Variablen, Besonderheit: es werden nur x items ausgegeben und der Hinweis, dass es weitere
|
||||
* Elemente gibt <code>
|
||||
* <workStationDataArray size="4">
|
||||
* <WorkStationData bookDate="07.11.2006 20:42:13" createDate="07.11.2006 20:42:13" cycleTime="0.0" position="1" resourceDesc="2001 - Laserbeschrifter" resourceNr="50100100" snr="4511" state="Gut" workOrderNr="test7"/>
|
||||
* <WorkStationData bookDate="07.11.2006 20:42:15" createDate="07.11.2006 20:42:15" cycleTime="0.0" position="1" resourceDesc="2002 - Schablonendrucker - Linie 1" resourceNr="50200002" snr="4511" state="Gut" workOrderNr="test8"/>
|
||||
* <WorkStationData bookDate="07.11.2006 20:42:16" createDate="07.11.2006 20:42:16" cycleTime="0.0" position="1" resourceDesc="1841 - Bestücker - Linie 1" resourceNr="50300101" snr="4511" state="Gut" workOrderNr="test8"/>
|
||||
* <WorkStationData skipMoreItems="true"/>
|
||||
* </workStationDataArray>
|
||||
* *
|
||||
*
|
||||
* @param item
|
||||
* das auszugebende Objekt
|
||||
* @return das Element das das Tag enthaelt
|
||||
*/
|
||||
private Element getStructuredElement(Object item) {
|
||||
String className = item.getClass().getSimpleName();
|
||||
LogHandler.log(LOGGER, TRACE, "create info for class " + className + " for output element in protocol document");
|
||||
Element element = getTestCase().getDocument().createElement(className);
|
||||
|
||||
// Sonderfall String
|
||||
if (item.getClass().equals(String.class)) {
|
||||
addAttribute(element, "value", item.toString());
|
||||
return element;
|
||||
}
|
||||
|
||||
// alle public felder als Attribute anhaengen
|
||||
Field[] declaredFields = item.getClass().getDeclaredFields();
|
||||
for (Field declaredField : declaredFields) {
|
||||
if ((declaredField.getModifiers() != Modifier.PUBLIC )&& !declaredField.getName().startsWith("$jacoco")) {
|
||||
LogHandler.log(LOGGER, TRACE, "skip non-public field '" + declaredField.getName() + "'");
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
Field field = item.getClass().getField(declaredField.getName());
|
||||
Object attribute = field.get(item);
|
||||
if (attribute == null) {
|
||||
Element subElement = getTestCase().getDocument().createElement(declaredField.getName());
|
||||
return subElement;
|
||||
}
|
||||
if (attribute.getClass().isArray()) {
|
||||
// Arrays z.B. so ausgeben
|
||||
// <workStationDataArray size="4">
|
||||
// <WorkStationData bookDate="07.11.2006 20:42:13" createDate="07.11.2006 20:42:13" cycleTime="0.0".../>
|
||||
|
||||
// Name der Arrayklasse, z.B. WorkStationData[]
|
||||
String arrayElementClassName = attribute.getClass().getSimpleName();
|
||||
// vom Klassennamendie eckigen Klammern entfernen
|
||||
arrayElementClassName = arrayElementClassName.substring(0, arrayElementClassName.length() - 2);
|
||||
LogHandler.log(LOGGER, TRACE, "add field '" + declaredField.getName() + "' as array of '" + arrayElementClassName + "'");
|
||||
Element subElement = getTestCase().getDocument().createElement(declaredField.getName());
|
||||
// besondere Behandlung von byte[]...
|
||||
if (arrayElementClassName.equals(byte.class.getSimpleName())) {
|
||||
addAttribute(subElement, "size", "" + ((byte[]) attribute).length);
|
||||
} else {
|
||||
Object[] arrayObjects = (Object[]) attribute;
|
||||
addAttribute(subElement, "size", "" + arrayObjects.length);
|
||||
// Arrays bis zu einer Tiefe von 20 ausgeben
|
||||
final int MAX_ARRAY_SIZE = 20;
|
||||
for (int i = 0; i < arrayObjects.length; i++) {
|
||||
Object object = arrayObjects[i];
|
||||
if (i < MAX_ARRAY_SIZE) {
|
||||
try {
|
||||
subElement.appendChild(getStructuredElement(object));
|
||||
} catch (Throwable e) {
|
||||
LogHandler.log(LOGGER, ERROR, "evaluating array '" + declaredField.getName() + "' failed!", e);
|
||||
}
|
||||
} else if (i == MAX_ARRAY_SIZE) {
|
||||
Element endOfArrayElement = getTestCase().getDocument().createElement(arrayElementClassName);
|
||||
addAttribute(endOfArrayElement, "skipMoreItems", "true");
|
||||
subElement.appendChild(endOfArrayElement);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
element.appendChild(subElement);
|
||||
}
|
||||
continue;
|
||||
} else if (!isSimpleType(attribute.getClass())) {
|
||||
// weiterer strukturierter Datentyp
|
||||
LogHandler.log(LOGGER, TRACE, "add structured data type : " + declaredField.getName());
|
||||
element.appendChild(getStructuredElement(attribute));
|
||||
continue;
|
||||
}
|
||||
LogHandler.log(LOGGER, TRACE, "add attribute: " + declaredField.getName() + "=" + attribute.toString());
|
||||
addAttribute(element, declaredField.getName(), attribute.toString());
|
||||
} catch (Throwable e) {
|
||||
LogHandler.log(LOGGER, ERROR, "evaluating array '" + declaredField.getName() + "' failed!", e);
|
||||
}
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
private Object getParameterValue(Class<?> clazz, String parameterName, String value) {
|
||||
|
||||
// wird in einem Parameter ein Verweis auf eine andere Variable genommen?
|
||||
if (VariableEngine.isVariable(value)) {
|
||||
// dann den Wert dieser Variablen aufloesen
|
||||
try {
|
||||
value = getTestCase().getVariableEngine().get(value).toString();
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(LOGGER, ERROR, "no value found for variable " + value);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (value.getClass() == clazz) {
|
||||
return value;
|
||||
}
|
||||
|
||||
try {
|
||||
if (clazz == Integer.class || clazz == int.class) {
|
||||
return Integer.parseInt(value);
|
||||
} else if (clazz == Long.class || clazz == long.class) {
|
||||
return Long.parseLong(value);
|
||||
} else if (clazz == Boolean.class || clazz == boolean.class) {
|
||||
return Boolean.parseBoolean(value);
|
||||
} else if (clazz == Double.class || clazz == double.class) {
|
||||
return Double.parseDouble(value);
|
||||
} else if (clazz == Float.class || clazz == float.class) {
|
||||
return Float.parseFloat(value);
|
||||
}
|
||||
} catch (NumberFormatException nfe) {
|
||||
throw new NullPointerException(getErrorHeader() + "'" + value + "' is not a valid value for parameter '" + parameterName
|
||||
+ "' of type '" + clazz.getSimpleName() + "'");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setParameterNames(String[] parameters) {
|
||||
parameterNames = parameters;
|
||||
}
|
||||
|
||||
public String[] getParameterNames() {
|
||||
return parameterNames;
|
||||
}
|
||||
|
||||
public void setParameterTypes(Class<?>[] pParamTypes) {
|
||||
this.paramTypes = pParamTypes;
|
||||
}
|
||||
|
||||
public void addStructuredParameter(String parameterName, Node x) {
|
||||
structuredParameters.put(parameterName, x);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endFail() {
|
||||
super.endFail();
|
||||
getTestCase().setLastApiCallRuntime(getTestCase().getLastRuntime());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endPass() {
|
||||
super.endPass();
|
||||
getTestCase().setLastApiCallRuntime(getTestCase().getLastRuntime());
|
||||
}
|
||||
|
||||
public void setMethod(Method m) {
|
||||
this.method = m;
|
||||
}
|
||||
|
||||
public Method getMethod() {
|
||||
return method;
|
||||
}
|
||||
|
||||
public String getFunctionName() {
|
||||
return functionName;
|
||||
}
|
||||
|
||||
// liefert die Klasse zu einem Parameter mit dem entsprechendem Namen
|
||||
// falls es keinen Parameter mit diesem Namen gibt liefert die Funktion null
|
||||
public Class<?> getClassForParameter(String parameterName) {
|
||||
for (int i = 0; i < parameterNames.length; i++) {
|
||||
if (parameterNames[i].equals(parameterName)) {
|
||||
return paramTypes[i];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Class<?>[] getParameterTypes() {
|
||||
return paramTypes;
|
||||
}
|
||||
|
||||
private void safeSetField(Field field, Object object, Object value) {
|
||||
// feld wert setzen
|
||||
try {
|
||||
LogHandler.info("set value " + value.toString() + " for field " + field.getName());
|
||||
if (field.getType() == Integer.class || field.getType() == int.class) {
|
||||
field.set(object, Integer.parseInt(value.toString()));
|
||||
} else if (field.getType() == Long.class || field.getType() == long.class) {
|
||||
field.set(object, Long.parseLong(value.toString()));
|
||||
} else if (field.getType() == Double.class || field.getType() == double.class) {
|
||||
field.set(object, Double.parseDouble(value.toString()));
|
||||
} else if (field.getType() == Float.class || field.getType() == float.class) {
|
||||
field.set(object, Float.parseFloat(value.toString()));
|
||||
} else if (field.getType() == Boolean.class || field.getType() == boolean.class) {
|
||||
field.set(object, Boolean.parseBoolean(value.toString()));
|
||||
} else {
|
||||
field.set(object, value.toString());
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
LogHandler.log(LOGGER, ERROR, "setting field value failed", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* simple typen sind die, die direkt mit toString ausgegeben werden können
|
||||
*
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
private boolean isSimpleType(Class<?> clazz) {
|
||||
return clazz == Integer.class || clazz == int.class || clazz == Long.class || clazz == long.class || clazz == Boolean.class
|
||||
|| clazz == boolean.class || clazz == Double.class || clazz == double.class || clazz == Float.class || clazz == float.class
|
||||
|| clazz == String.class;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.text.MessageFormat;
|
||||
|
||||
import javax.script.Invocable;
|
||||
import javax.script.ScriptContext;
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptEngineManager;
|
||||
import javax.script.ScriptException;
|
||||
|
||||
import com.itac.mes.datainterface.datasource.BasicDataSource;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlAssertJs extends XmlConstruct {
|
||||
|
||||
public static final String LOGGER = XmlAssertJs.class.getSimpleName();
|
||||
|
||||
public static final String SCRIPT_EXAMPLE = " <AssertJs id=\"assertionId\" test=\"$setupName\">\r\n" +
|
||||
" function assert(varName, testValue) {\r\n" +
|
||||
" \r\n" +
|
||||
" print (\"var Name :\" + varName);\r\n" +
|
||||
" print (\"test value :\" + testValue);\r\n" +
|
||||
" \r\n" +
|
||||
" return testValue == \"000111\";\r\n" +
|
||||
" }\r\n" +
|
||||
" </AssertJs>\r\n";
|
||||
|
||||
public XmlAssertJs(String id) {
|
||||
super(id);
|
||||
iName = "assertJS";
|
||||
}
|
||||
|
||||
// mit der Auswertung der Test-Variable wird der Wert in dieses Obejct geschrieben
|
||||
private Object testValue = null;
|
||||
private String scriptText;
|
||||
private String test;
|
||||
|
||||
private BasicDataSource instance;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
if (getId().isEmpty()) {
|
||||
return "AssertJs";
|
||||
}
|
||||
return "AssertJs id(" + getId() + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
super.execute(services);
|
||||
// variable ermitteln
|
||||
Object testValue = getTestCase().getVariableEngine().get(test);
|
||||
// if (testValue == null) {
|
||||
// addAttribute(test, "errorDescription", "variable " + test + " does not exist");
|
||||
// LogHandler.log(LOGGER, ERROR, "Variable '" + test + "' does not exist");
|
||||
// return false;
|
||||
// }
|
||||
ScriptEngineManager engineManager = new ScriptEngineManager();
|
||||
ScriptEngine engine = engineManager.getEngineByName("nashorn");
|
||||
ScriptContext context = engine.getContext();
|
||||
StringWriter logWriter = new StringWriter();
|
||||
context.setErrorWriter(logWriter);
|
||||
context.setWriter(logWriter);
|
||||
|
||||
try {
|
||||
// cast the script engine to an invocable instance
|
||||
Invocable invocable = (Invocable) engine;
|
||||
engine.eval(scriptText);
|
||||
engine.put("instance", instance);
|
||||
engine.put("test", testValue);
|
||||
engine.put("testVariable", test);
|
||||
Object assertResult = invocable.invokeFunction("assert", test, testValue);
|
||||
|
||||
LogHandler.log(getClass().getSimpleName(), INFO, logWriter.toString());
|
||||
|
||||
if (assertResult == null) {
|
||||
throw new ScriptException("Script executed, but function 'assert' did not return a value");
|
||||
}
|
||||
if (!(assertResult instanceof Boolean)) {
|
||||
throw new ScriptException(MessageFormat.format(
|
||||
"Script executed, but function 'assert' did not return a boolean value, but {0} of type {1} instead.",
|
||||
assertResult.toString(), assertResult.getClass()));
|
||||
}
|
||||
|
||||
LogHandler.log(LOGGER, INFO, "AssertJs\n\treturned: " + ((Boolean) assertResult).booleanValue());
|
||||
|
||||
if (((Boolean) assertResult).booleanValue()) {
|
||||
endPass();
|
||||
return;
|
||||
}
|
||||
|
||||
} catch (NoSuchMethodException e) {
|
||||
LogHandler.log(LOGGER, ERROR, "Script not executed; missing function 'assert'\n xmlConstruct should look like following:\n" +
|
||||
SCRIPT_EXAMPLE, e);
|
||||
} catch (ScriptException e) {
|
||||
LogHandler.log(LOGGER, ERROR, e.getMessage() + "\n" + SCRIPT_EXAMPLE, e);
|
||||
}
|
||||
// dump on Failure
|
||||
endFail();
|
||||
getTestCase().getVariableEngine().dump(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param textContent
|
||||
*/
|
||||
public void setScriptText(String textContent) {
|
||||
this.scriptText = textContent;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param sTest
|
||||
*/
|
||||
public void setTest(String sTest) {
|
||||
this.test = sTest;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param instance
|
||||
*/
|
||||
public void setInstance(BasicDataSource instance) {
|
||||
this.instance = instance;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
import static com.itac.util.logging.LogLevel.TRACE;
|
||||
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlAssertion extends XmlConstruct {
|
||||
|
||||
public static final String LOGGER = XmlAssertion.class.getSimpleName();
|
||||
|
||||
public XmlAssertion(String id) {
|
||||
super(id);
|
||||
iName = "assert";
|
||||
}
|
||||
|
||||
private String test = "";
|
||||
private String expected = "";
|
||||
private XmlCondition condition;
|
||||
|
||||
// mit der Auswertung der Test-Variable wird der Wert in dieses Obejct geschrieben
|
||||
private Object testValue = null;
|
||||
|
||||
public void setTest(String test) {
|
||||
this.test = test;
|
||||
}
|
||||
|
||||
public void setExpected(String expected) {
|
||||
this.expected = expected;
|
||||
}
|
||||
|
||||
public String getTest() {
|
||||
return test;
|
||||
}
|
||||
|
||||
public String getExpected() {
|
||||
return expected;
|
||||
}
|
||||
|
||||
public void setCondition(XmlCondition condition) {
|
||||
this.condition = condition;
|
||||
}
|
||||
|
||||
public XmlCondition getCondition() {
|
||||
return condition;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
if (getId().equals("")) {
|
||||
return "Assertion " + test + " " + condition.getSymbol() + " " + expected;
|
||||
}
|
||||
if (expected != null && expected.isEmpty()) {
|
||||
return "Assertion id(" + getId() + ")" + test + " " + condition.getSymbol() + " ''";
|
||||
}
|
||||
return "Assertion id(" + getId() + ")" + test + " " + condition.getSymbol() + " " + expected;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
super.execute(services);
|
||||
// einen neuen Unterknoten anfuegen (testvalues)
|
||||
condition.setDocument(getTestCase().getDocument());
|
||||
|
||||
Element testNode = getTestCase().getDocument().createElement("testinfo");
|
||||
boolean assertResult = executeAssert(testNode);
|
||||
callElement.appendChild(condition.getConditionNode());
|
||||
if (assertResult) {
|
||||
endPass();
|
||||
} else {
|
||||
|
||||
LogHandler.log(LOGGER, INFO, "AssertionDetails" + //
|
||||
"\n\ttest :" + test + " = " + testValue + //
|
||||
"\n\texpected:" + expected + ": ");
|
||||
|
||||
// dump on Failure
|
||||
getTestCase().getVariableEngine().dump(true);
|
||||
|
||||
callElement.appendChild(testNode);
|
||||
addAttribute(testNode, "test", test);
|
||||
if (testValue != null) {
|
||||
addAttribute(testNode, "testvalue", testValue.toString());
|
||||
} else {
|
||||
addAttribute(testNode, "testvalue", "null");
|
||||
}
|
||||
addAttribute(testNode, "expected", expected);
|
||||
endFail();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param testNode
|
||||
* @return
|
||||
*/
|
||||
protected boolean executeAssert(Element testNode) {
|
||||
try {
|
||||
// Variable oder sonderfunktion???
|
||||
if (test.equals("$RUNTIME")) {
|
||||
long testValue = getTestCase().getLastRuntime();
|
||||
this.testValue = testValue;
|
||||
// expected muss ein long sein, das stellt der Parser schon sicher...
|
||||
long expected = Long.parseLong(getExpected());
|
||||
return condition.compare(testValue, expected);
|
||||
}
|
||||
|
||||
if (VariableEngine.isVariable(expected)) {
|
||||
if (expected.equals("$EMPTY")) {
|
||||
// do not change value
|
||||
} else {
|
||||
Object expectedVar = getTestCase().getVariableEngine().get(expected);
|
||||
if (expectedVar == null) {
|
||||
if (testNode != null) {
|
||||
addAttribute(testNode, "errorDescription", "variable '" + expected + "' from attribute 'expected' does not exists");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
expected = expectedVar.toString();
|
||||
}
|
||||
}
|
||||
|
||||
// variable ermitteln
|
||||
Object var = getTestCase().getVariableEngine().get(test);
|
||||
if (var == null) {
|
||||
if (condition == XmlCondition.NOTEXISTS) {
|
||||
// sonderfall: Variable darf nicht existieren als Bedingung
|
||||
LogHandler.log(LOGGER, INFO, "Variable '" + test + "' does not exist");
|
||||
return true;
|
||||
}
|
||||
if (testNode != null) {
|
||||
addAttribute(testNode, "errorDescription", "variable " + test + " does not exist");
|
||||
}
|
||||
LogHandler.log(LOGGER, ERROR, "Variable '" + test + "' does not exist");
|
||||
return false;
|
||||
}
|
||||
LogHandler.log(LOGGER, TRACE, "Variable '" + test + "', value: " + var.toString());
|
||||
if (condition == XmlCondition.EXISTS) {
|
||||
// Sonderfall: Variable existiert, keine Wert-Prüfung
|
||||
return true;
|
||||
} else if (condition == XmlCondition.NOTEXISTS) {
|
||||
// sonderfall: Variable darf nicht existieren als Bedingung
|
||||
LogHandler.log(LOGGER, ERROR, "Variable '" + test + "' exists!");
|
||||
if (testNode != null) {
|
||||
addAttribute(testNode, "errorDescription", "variable " + test + " exists");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
LogHandler.log(LOGGER, INFO, "testvalue=" + var.toString());
|
||||
testValue = var.toString();
|
||||
if (var instanceof String) {
|
||||
return condition.compare((String) var, expected);
|
||||
} else if (var instanceof String) {
|
||||
return condition.compare((String) var, expected);
|
||||
} else if (var instanceof Long) {
|
||||
return condition.compare((Long) var, expected);
|
||||
} else if (var instanceof Integer) {
|
||||
return condition.compare((Integer) var, expected);
|
||||
} else if (var instanceof Double) {
|
||||
return condition.compare((Double) var, expected);
|
||||
} else if (var instanceof Float) {
|
||||
return condition.compare((Float) var, expected);
|
||||
} else if (var instanceof Boolean) {
|
||||
return condition.compare((Boolean) var, expected);
|
||||
} else if (var instanceof Object) {
|
||||
return condition.compare((String) var.toString(), expected);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(LOGGER, ERROR, "Assertion incorrect:", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
import static com.itac.util.logging.LogLevel.TRACE;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.w3c.dom.Attr;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public enum XmlCondition {
|
||||
LESS("less", "<"), //
|
||||
GREATER("greater", ">"), //
|
||||
EQUAL("equal", "=="), //
|
||||
LESSEQUAL("lessEqual", "<="), //
|
||||
GREATEREQUAL("greaterEqual", ">="), //
|
||||
NOTEQUAL("notEqual", "!="), //
|
||||
ISREGEXP("isRegExp", "~"), //
|
||||
EXISTS("exists", "exists"), //
|
||||
NOTEXISTS("notExists", "notexists"), //
|
||||
IN("in", "in");
|
||||
|
||||
public static final String LOGGER = XmlCondition.class.getSimpleName();
|
||||
|
||||
private String text;
|
||||
private String symbol;
|
||||
private Element conditionNode;
|
||||
private Document document;
|
||||
|
||||
private XmlCondition(String text, String symbol) {
|
||||
this.text = text;
|
||||
this.symbol = symbol;
|
||||
}
|
||||
|
||||
public static XmlCondition get(String text) {
|
||||
for (XmlCondition condition : XmlCondition.values()) {
|
||||
if (condition.text.equals(text)) {
|
||||
return condition;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public static String getAllConditions() {
|
||||
StringBuffer result = new StringBuffer();
|
||||
for (XmlCondition condition : XmlCondition.values()) {
|
||||
if (result.length() > 0) {
|
||||
result.append(",");
|
||||
}
|
||||
result.append(condition.text);
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public String getSymbol() {
|
||||
return symbol;
|
||||
}
|
||||
|
||||
public boolean compare(long testValue, long expected) {
|
||||
setTextValues(String.valueOf(testValue), String.valueOf(expected));
|
||||
switch (this) {
|
||||
case LESS:
|
||||
return testValue < expected;
|
||||
case GREATER:
|
||||
return testValue > expected;
|
||||
case EQUAL:
|
||||
return testValue == expected;
|
||||
case LESSEQUAL:
|
||||
return testValue <= expected;
|
||||
case GREATEREQUAL:
|
||||
return testValue >= expected;
|
||||
case NOTEQUAL:
|
||||
return testValue != expected;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean compare(String testValue, String expected) {
|
||||
LogHandler.log(LOGGER, TRACE, "compare (" + testValue + ", " + expected + ")");
|
||||
|
||||
if (testValue.equalsIgnoreCase("$EMPTY")){
|
||||
testValue = "";
|
||||
}
|
||||
if (expected.equalsIgnoreCase("$EMPTY")){
|
||||
expected = "";
|
||||
}
|
||||
|
||||
expected = checkControlChar(expected);
|
||||
setTextValues(String.valueOf(testValue), expected);
|
||||
switch (this) {
|
||||
// case 0: return testValue.compareTo(expected);
|
||||
// case 1: return testValue > expected;
|
||||
case EQUAL:
|
||||
return testValue.equals(expected);
|
||||
case LESSEQUAL:
|
||||
case GREATEREQUAL:
|
||||
try {
|
||||
int iValue = Integer.parseInt(testValue);
|
||||
return compare(iValue, expected);
|
||||
} catch (NumberFormatException e) {
|
||||
try {
|
||||
double iValue = Double.parseDouble(testValue);
|
||||
return compare(iValue, expected);
|
||||
} catch (NumberFormatException e2) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
case NOTEQUAL:
|
||||
return !testValue.equals(expected);
|
||||
case ISREGEXP:
|
||||
Pattern p = Pattern.compile(expected, Pattern.MULTILINE + Pattern.DOTALL);
|
||||
Matcher matcher = p.matcher(testValue);
|
||||
return matcher.matches();
|
||||
case IN:
|
||||
// RightOperand muss eine durch Semikolon getrennte Werteliste sein
|
||||
String[] rightOperands = expected.split("\\;");
|
||||
Set<String> rightOperandSet = new HashSet<String>();
|
||||
for (String value : rightOperands) {
|
||||
rightOperandSet.add(value);
|
||||
}
|
||||
return rightOperandSet.contains(testValue);
|
||||
default:
|
||||
LogHandler.log(LOGGER, ERROR, "unsupported operator " + this.symbol + " for datatype String");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String checkControlChar(String expected) {
|
||||
StringBuffer out = new StringBuffer();
|
||||
for (int n = 0; n < expected.length(); n++) {
|
||||
if (expected.charAt(n) == '\\' && n + 1 < expected.length()) {
|
||||
switch (expected.charAt(n + 1)) {
|
||||
case 'n':
|
||||
out.append('\n');
|
||||
n++;
|
||||
break;
|
||||
|
||||
case 't':
|
||||
out.append('\t');
|
||||
n++;
|
||||
break;
|
||||
|
||||
default:
|
||||
out.append(expected.charAt(n));
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
out.append(expected.charAt(n));
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
public boolean compare(int testValue, String expected) {
|
||||
setTextValues(String.valueOf(testValue), expected);
|
||||
int iExpected = Integer.parseInt(expected);
|
||||
switch (this) {
|
||||
case LESS:
|
||||
return testValue < iExpected;
|
||||
case GREATER:
|
||||
return testValue > iExpected;
|
||||
case EQUAL:
|
||||
return testValue == iExpected;
|
||||
case LESSEQUAL:
|
||||
return testValue <= iExpected;
|
||||
case GREATEREQUAL:
|
||||
return testValue >= iExpected;
|
||||
case NOTEQUAL:
|
||||
return testValue != iExpected;
|
||||
default:
|
||||
LogHandler.log(LOGGER, ERROR, "unsupported operator " + this.symbol + " for datatype int");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean compare(long testValue, String expected) {
|
||||
setTextValues(String.valueOf(testValue), expected);
|
||||
long lExpected = Long.parseLong(expected);
|
||||
switch (this) {
|
||||
case LESS:
|
||||
return testValue < lExpected;
|
||||
case GREATER:
|
||||
return testValue > lExpected;
|
||||
case EQUAL:
|
||||
return testValue == lExpected;
|
||||
case LESSEQUAL:
|
||||
return testValue <= lExpected;
|
||||
case GREATEREQUAL:
|
||||
return testValue >= lExpected;
|
||||
case NOTEQUAL:
|
||||
return testValue != lExpected;
|
||||
default:
|
||||
LogHandler.log(LOGGER, ERROR, "unsupported operator " + this.symbol + " for datatype long");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean compare(double testValue, String expected) {
|
||||
setTextValues(String.valueOf(testValue), expected);
|
||||
double dExpected = Double.parseDouble(expected);
|
||||
switch (this) {
|
||||
case LESS:
|
||||
return testValue < dExpected;
|
||||
case GREATER:
|
||||
return testValue > dExpected;
|
||||
case EQUAL:
|
||||
return testValue == dExpected;
|
||||
case LESSEQUAL:
|
||||
return testValue <= dExpected;
|
||||
case GREATEREQUAL:
|
||||
return testValue >= dExpected;
|
||||
case NOTEQUAL:
|
||||
return testValue != dExpected;
|
||||
default:
|
||||
LogHandler.log(LOGGER, ERROR, "unsupported operator " + this.symbol + " for datatype double");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean compare(float testValue, String expected) {
|
||||
setTextValues(String.valueOf(testValue), expected);
|
||||
double fExpected = Float.parseFloat(expected);
|
||||
switch (this) {
|
||||
case LESS:
|
||||
return testValue < fExpected;
|
||||
case GREATER:
|
||||
return testValue > fExpected;
|
||||
case EQUAL:
|
||||
return testValue == fExpected;
|
||||
case LESSEQUAL:
|
||||
return testValue <= fExpected;
|
||||
case GREATEREQUAL:
|
||||
return testValue >= fExpected;
|
||||
case NOTEQUAL:
|
||||
return testValue != fExpected;
|
||||
default:
|
||||
LogHandler.log(LOGGER, ERROR, "unsupported operator " + this.symbol + " for datatype float");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean compare(Boolean testValue, String expected) {
|
||||
setTextValues(String.valueOf(testValue), expected);
|
||||
boolean bExpected = Boolean.parseBoolean(expected);
|
||||
switch (this) {
|
||||
case EQUAL:
|
||||
return testValue == bExpected;
|
||||
case NOTEQUAL:
|
||||
return testValue != bExpected;
|
||||
default:
|
||||
LogHandler.log(LOGGER, ERROR, "unsupported operator " + this.symbol + " for datatype boolean");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void setTextValues(String value, String expected) {
|
||||
if (document == null) {
|
||||
return;
|
||||
}
|
||||
Attr attr = document.createAttribute("value");
|
||||
attr.setNodeValue(value);
|
||||
conditionNode.setAttributeNode(attr);
|
||||
|
||||
attr = document.createAttribute("expected");
|
||||
attr.setNodeValue(expected);
|
||||
conditionNode.setAttributeNode(attr);
|
||||
}
|
||||
|
||||
public void setDocument(Document document) {
|
||||
this.document = document;
|
||||
conditionNode = document.createElement("condition");
|
||||
Attr attr = document.createAttribute("operator");
|
||||
attr.setNodeValue(getText());
|
||||
conditionNode.setAttributeNode(attr);
|
||||
}
|
||||
|
||||
public Element getConditionNode() {
|
||||
return conditionNode;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.TRACE;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.w3c.dom.Attr;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestCase;
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestCaseState;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public abstract class XmlConstruct {
|
||||
|
||||
public static final String ID = "id";
|
||||
private transient List<XmlConstruct> childs = new ArrayList<XmlConstruct>();
|
||||
// Der Testcase dem dieses Construct angehoert
|
||||
private transient XmlTestCase testCase;
|
||||
// fuer dieses Construct benoetigte Ausfuehrungszeiten
|
||||
protected long startTime = 0L;
|
||||
protected long stopTime = 0L;
|
||||
// unique Id ueber alle testschritte in diesem TestCase
|
||||
private String sId = "";
|
||||
/**
|
||||
* callElement ist das Element im DOM-Baum, das zur Zeit ausgefuehrt wird. Zu diesem Element koennen weitere Knoten und Attribute
|
||||
* hinzugefuegt weredn
|
||||
*/
|
||||
protected transient Element callElement;
|
||||
protected String iName = "";
|
||||
private transient Element stats;
|
||||
|
||||
public void addChild(XmlConstruct xmlSubConstruct) {
|
||||
childs.add(xmlSubConstruct);
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return sId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Xmlconstruct kann nur mit einer gueltigen id erzeugt werden. gueltig ist eine Id, wenn sie entweder "" ist oder ueber alle
|
||||
* constructe zu einem TestCase eindeutig
|
||||
*
|
||||
* @param id
|
||||
*/
|
||||
public XmlConstruct(String id) {
|
||||
super();
|
||||
this.sId = id;
|
||||
this.iName = "call";
|
||||
}
|
||||
|
||||
public void setTestCase(XmlTestCase testCase) {
|
||||
this.testCase = testCase;
|
||||
}
|
||||
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException{
|
||||
LogHandler.log(getClass().getSimpleName(), TRACE, "executing id " + getId());
|
||||
checkStart();
|
||||
}
|
||||
|
||||
public XmlTestCase getTestCase() {
|
||||
return testCase;
|
||||
}
|
||||
|
||||
public void endPass() {
|
||||
stopTime = System.currentTimeMillis();
|
||||
getTestCase().setPass();
|
||||
getTestCase().setLastRuntime(getTestMillies());
|
||||
LogHandler.info(this.toString() + " run in " + getTestMillies() + " millies");
|
||||
addAttribute(stats, "executionTime", String.valueOf(getTestMillies()));
|
||||
addAttribute(stats, "state", XmlTestCaseState.PASS.toString());
|
||||
addAttribute(stats, "ended", new Date().toString());
|
||||
}
|
||||
|
||||
public void endFail() {
|
||||
stopTime = System.currentTimeMillis();
|
||||
getTestCase().setFail();
|
||||
getTestCase().setLastRuntime(getTestMillies());
|
||||
LogHandler.info(this.toString() + " run in " + getTestMillies() + " millies");
|
||||
|
||||
addAttribute(stats, "executionTime", String.valueOf(getTestMillies()));
|
||||
addAttribute(stats, "state", XmlTestCaseState.FAIL.toString());
|
||||
addAttribute(stats, "ended", new Date().toString());
|
||||
}
|
||||
|
||||
public void checkStart() throws TestcaseException {
|
||||
if (getTestCase().getState() != XmlTestCaseState.PASS && getTestCase().getState() != XmlTestCaseState.STARTED) {
|
||||
throw new TestcaseException("testcase {0} is in invalid state {1}", getId(), getTestCase().getState()) ;
|
||||
}
|
||||
startTime = System.currentTimeMillis();
|
||||
LogHandler.info("starte " + toString());
|
||||
|
||||
callElement = getTestCase().getDocument().createElement(iName);
|
||||
stats = getTestCase().getDocument().createElement("stats");
|
||||
callElement.appendChild(stats);
|
||||
|
||||
getTestCase().getTestCaseNode().appendChild(callElement);
|
||||
addAttribute(callElement, ID, sId.toString());
|
||||
addAttribute(stats, "started", new Date().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* berechnet die Laufzeit eines einzelnen Constructs nach der Ausfuehrung; wurde ein Testschritt nicht ausgefuehrt, weil ein
|
||||
* voriger Testschritt fehlerhaft beendet wurde ist die Zeit 0
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public long getTestMillies() {
|
||||
if (startTime == 0L && stopTime == 0L) {
|
||||
return 0L;
|
||||
}
|
||||
|
||||
return stopTime - startTime;
|
||||
}
|
||||
|
||||
public List<XmlConstruct> getChilds() {
|
||||
return childs;
|
||||
}
|
||||
|
||||
/**
|
||||
* zu einem Schluessel den Variablennamen erzeugen. Ist eine ID vorhanden wird diese mit einem Punkt davor gesetzt
|
||||
*
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
protected String getVariableName(String key) {
|
||||
if (getId().isEmpty()) {
|
||||
return key;
|
||||
}
|
||||
return getId() + "." + key;
|
||||
}
|
||||
|
||||
/**
|
||||
* erzeugen eines neuen Attributes und anhaengen des Attributs an das Element
|
||||
*
|
||||
* @param superElement
|
||||
* @param attributeKey
|
||||
* @param attributeValue
|
||||
*/
|
||||
protected void addAttribute(Element superElement, String attributeKey, String attributeValue) {
|
||||
addAttribute(getTestCase().getDocument(), superElement, attributeKey, attributeValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* erzeugen eines neuen Attributes und anhaengen des Attributs an das Element
|
||||
*
|
||||
* @param superElement
|
||||
* @param attributeKey
|
||||
* @param attributeValue
|
||||
*/
|
||||
protected void addAttribute(Document document, Element superElement, String attributeKey, String attributeValue) {
|
||||
Attr attr = document.createAttribute(attributeKey);
|
||||
attr.setNodeValue(attributeValue);
|
||||
superElement.setAttributeNode(attr);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import com.itac.mes.datainterface.gui.IMachineSimulation;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.mes.datainterface.simulation.DatabaseSimulation;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
import com.itac.util.logging.LogLevel;
|
||||
|
||||
public class XmlDatabase extends XmlMachineConstruct {
|
||||
|
||||
// private DatabaseSimulation databaseSimulation;
|
||||
private String sql;
|
||||
|
||||
final static private int SELECT = 0;
|
||||
final static private int UPDATE = 1;
|
||||
final static private int COMMIT = 2;
|
||||
final static private int INSERT = 3;
|
||||
final static private int DELETE = 4;
|
||||
private int operation = 0;
|
||||
|
||||
public XmlDatabase(String id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
// pruefen, od diese Funktion ueberhaupt ausgefuehrt werden darf
|
||||
super.execute(services);
|
||||
try {
|
||||
// String sqlFin = null;
|
||||
// if (sql != null) {
|
||||
// sqlFin = replaceVariables(sql);
|
||||
// }
|
||||
// switch (Operation) {
|
||||
// case SELECT:
|
||||
// databaseSimulation.executeAction(sqlFin, this);
|
||||
// break;
|
||||
// case UPDATE:
|
||||
// databaseSimulation.executeUpdate(sqlFin, this);
|
||||
// break;
|
||||
// case INSERT:
|
||||
// databaseSimulation.executeInsert(sqlFin, this);
|
||||
// break;
|
||||
// case DELETE:
|
||||
// databaseSimulation.executeDelete(sqlFin, this);
|
||||
// break;
|
||||
// case COMMIT:
|
||||
// databaseSimulation.commit(this);
|
||||
// break;
|
||||
// }
|
||||
// wenn keine Exception oder sonstige Fehler aufgetreten sind ist diese funktion erfolgreich ausgeführt worden.
|
||||
endPass();
|
||||
} catch (Throwable th) {
|
||||
LogHandler.log("XmlDatabase", LogLevel.ERROR, th.getMessage());
|
||||
endFail();
|
||||
}
|
||||
}
|
||||
|
||||
public void setDatabaseSimulation(DatabaseSimulation databaseSimulation) {
|
||||
// this.databaseSimulation = databaseSimulation;
|
||||
}
|
||||
|
||||
public void setSelect(String sql) {
|
||||
operation = SELECT;
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
public void setInsert(String sql) {
|
||||
operation = INSERT;
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
public void setUpdate(String sql) {
|
||||
operation = UPDATE;
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
public void setDelete(String sql) {
|
||||
operation = DELETE;
|
||||
this.sql = sql;
|
||||
System.err.println("" + operation + this.sql);
|
||||
}
|
||||
|
||||
public void commit() {
|
||||
operation = COMMIT;
|
||||
}
|
||||
|
||||
// private String replaceVariables(String select) throws Exception {
|
||||
// StringBuilder stb = new StringBuilder(select);
|
||||
// boolean replaced = false;
|
||||
// int start = 0;
|
||||
// do {
|
||||
// start = stb.indexOf("{$", start);
|
||||
// int end = 0;
|
||||
// if (start > 0) {
|
||||
// end = stb.indexOf("}", start);
|
||||
// if (end == -1) {
|
||||
// throw new Exception("missing char '}' after variable");
|
||||
// }
|
||||
// }
|
||||
// replaced = false;
|
||||
// if (start >= 0 && end > 0) {
|
||||
//
|
||||
// String variableName = stb.substring(start + 1, end);
|
||||
// Object varValue = getTestCase().getVariableEngine().get(variableName);
|
||||
// // ersetzen
|
||||
// if (varValue == null) {
|
||||
// throw new Exception("missing Variable '" + variableName + "'");
|
||||
// }
|
||||
// stb.replace(start, end + 1, varValue.toString());
|
||||
// replaced = true;
|
||||
// start = 0;
|
||||
// }
|
||||
// } while (replaced);
|
||||
//
|
||||
// return stb.toString();
|
||||
// }
|
||||
|
||||
/**
|
||||
* @param machine
|
||||
*/
|
||||
@Override
|
||||
public void setSimulation(IMachineSimulation machineSimulation) {
|
||||
if (machineSimulation instanceof DatabaseSimulation) {
|
||||
// this.databaseSimulation = (DatabaseSimulation) machineSimulation;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
|
||||
public class XmlDump extends XmlConstruct {
|
||||
private boolean withStructure;
|
||||
|
||||
public XmlDump(String id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) {
|
||||
getTestCase().getVariableEngine().dump(withStructure);
|
||||
}
|
||||
|
||||
public void setStructuredOutput(boolean withStructure) {
|
||||
this.withStructure = withStructure;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestCaseState;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
|
||||
public class XmlFor extends XmlConstruct {
|
||||
|
||||
public XmlFor(String id) {
|
||||
super(id);
|
||||
iName = "for";
|
||||
}
|
||||
|
||||
private String variable;
|
||||
private int start = Integer.MIN_VALUE;
|
||||
private int end = Integer.MIN_VALUE;
|
||||
|
||||
public void setVariable(String variable) {
|
||||
this.variable = variable;
|
||||
}
|
||||
|
||||
public void setStart(String start) {
|
||||
this.start = Integer.parseInt(start);
|
||||
}
|
||||
|
||||
public void setEnd(String end) {
|
||||
this.end = Integer.parseInt(end);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "for id(" + getId() + ")" + variable + ": " + start + " to " + end;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
super.execute(services);
|
||||
// die einzige Vorbedingung ist, dass die Grenzen richtig sind
|
||||
if (end == Integer.MIN_VALUE && start == Integer.MIN_VALUE) {
|
||||
endFail();
|
||||
return;
|
||||
}
|
||||
|
||||
if (start > end) {
|
||||
endPass();
|
||||
return;
|
||||
}
|
||||
// auswerten, untergeordnete Faelle laufen lassen
|
||||
for (int i = start; i <= end; i++) {
|
||||
getTestCase().getVariableEngine().put(getVariableName(variable), i);
|
||||
List<XmlConstruct> subConstructs = getChilds();
|
||||
if (!subConstructs.isEmpty()) {
|
||||
for (XmlConstruct xmlConstruct : subConstructs) {
|
||||
if (getTestCase().getState() != XmlTestCaseState.FAIL) {
|
||||
xmlConstruct.execute(services);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
endPass();// oder endFail
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.DEBUG;
|
||||
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlFunctionCall extends XmlConstruct {
|
||||
|
||||
public static final String FUNCTION = "function";
|
||||
public static final String LOGGER = XmlFunctionCall.class.getSimpleName();
|
||||
|
||||
private String functionName;
|
||||
|
||||
public XmlFunctionCall(String id) {
|
||||
super(id);
|
||||
iName = "functionCall";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return FUNCTION + " id(" + getId() + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
super.execute(services);
|
||||
|
||||
|
||||
LogHandler.log(LOGGER, DEBUG, toString() + " calling subroutine '" + functionName + "'");
|
||||
// aus der Testsuite die Routine ermitteln.
|
||||
// diese Routine dann ausführen
|
||||
XmlConstruct xmlConstruct = getTestCase().getSuite().getFunction(functionName);
|
||||
if (xmlConstruct == null) {
|
||||
throw new TestcaseException(toString() + ":subroutine " + functionName + " not found in testSuite "
|
||||
+ getTestCase().getSuite().getId());
|
||||
}
|
||||
xmlConstruct.setTestCase(getTestCase());
|
||||
xmlConstruct.execute(services);
|
||||
endPass();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param functionName
|
||||
* Die funktion mit diesem Namen ist aufzurufen
|
||||
*/
|
||||
public void setFunctionName(String functionName) {
|
||||
this.functionName = functionName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.DEBUG;
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestCaseState;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlFunctionDefinition extends XmlConstruct {
|
||||
|
||||
public static final String LOGGER = XmlFunctionDefinition.class.getSimpleName();
|
||||
|
||||
private ArrayList<XmlConstruct> xmlConstructs = new ArrayList<XmlConstruct>();
|
||||
private HashSet<String> idSet = new HashSet<String>();
|
||||
|
||||
public XmlFunctionDefinition(String id) {
|
||||
super(id);
|
||||
iName = "subroutineExecution";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "id(" + getId() + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
LogHandler.log(LOGGER, DEBUG, "executing subroutine '" + getId() + "'");
|
||||
// aus der Testsuite die Routine ermitteln.
|
||||
// diese Routine dann ausführen
|
||||
for (XmlConstruct xmlConstruct : xmlConstructs) {
|
||||
if (getTestCase().getState() != XmlTestCaseState.FAIL) {
|
||||
try {
|
||||
xmlConstruct.setTestCase(getTestCase());
|
||||
xmlConstruct.execute(services);
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(LOGGER, ERROR, e.getMessage());
|
||||
xmlConstruct.endFail();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void add(XmlConstruct xmlConstruct) throws Exception {
|
||||
testId(xmlConstruct);
|
||||
idSet.add(xmlConstruct.getId());
|
||||
xmlConstructs.add(xmlConstruct);
|
||||
}
|
||||
|
||||
private void testId(XmlConstruct xmlConstruct) throws Exception {
|
||||
if (!xmlConstruct.getId().equals("") && idSet.contains(xmlConstruct.getId())) {
|
||||
throw new Exception("construct with id '" + xmlConstruct.getId() + "' is already used in function id '" + getId() + "'");
|
||||
}
|
||||
if (xmlConstruct.getChilds() != null) {
|
||||
for (XmlConstruct child : xmlConstruct.getChilds()) {
|
||||
testId(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ArrayList<XmlConstruct> getXmlConstructs() {
|
||||
return xmlConstructs;
|
||||
}
|
||||
|
||||
public HashSet<String> getIdSet() {
|
||||
return idSet;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.w3c.dom.Comment;
|
||||
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestCaseState;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
|
||||
public class XmlIf extends XmlConstruct {
|
||||
|
||||
public XmlIf(String id) {
|
||||
super(id);
|
||||
iName = "if";
|
||||
}
|
||||
|
||||
private String leftOperand;
|
||||
private String rightOperand;
|
||||
private XmlCondition condition;
|
||||
|
||||
public void setLeftOperand(String leftOperand) {
|
||||
this.leftOperand = leftOperand;
|
||||
}
|
||||
|
||||
public void setCondition(XmlCondition condition) {
|
||||
this.condition = condition;
|
||||
}
|
||||
|
||||
public void setRightOperand(String rightOperand) {
|
||||
this.rightOperand = rightOperand;
|
||||
}
|
||||
|
||||
public String getLeftOperand() {
|
||||
return leftOperand;
|
||||
}
|
||||
|
||||
public String getRightOperand() {
|
||||
return rightOperand;
|
||||
}
|
||||
|
||||
public XmlCondition getCondition() {
|
||||
return condition;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "if id(" + getId() + ")(" + leftOperand + " " + condition.getText() + " " + rightOperand + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
super.execute(services);
|
||||
|
||||
// auswerten, untergeordnete Faelle laufen lassen
|
||||
Object sLeft = getTestCase().getVariableEngine().get(leftOperand);
|
||||
if (sLeft == null) {
|
||||
sLeft = leftOperand.toString();
|
||||
}
|
||||
Object sRight = getTestCase().getVariableEngine().get(rightOperand);
|
||||
if (sRight == null) {
|
||||
sRight = rightOperand.toString();
|
||||
}
|
||||
|
||||
if (condition.compare(sLeft.toString(), sRight.toString())) {
|
||||
Comment commentNode = getTestCase().getDocument().createComment(
|
||||
"if id(" + getId() + "): " + leftOperand + condition.getSymbol() + rightOperand + " = true, execute block");
|
||||
getTestCase().getTestCaseNode().appendChild(commentNode);
|
||||
|
||||
List<XmlConstruct> subConstructs = getChilds();
|
||||
if (!subConstructs.isEmpty()) {
|
||||
for (XmlConstruct xmlConstruct : subConstructs) {
|
||||
if (getTestCase().getState() != XmlTestCaseState.FAIL) {
|
||||
xmlConstruct.execute(services);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Comment commentNode = getTestCase().getDocument().createComment(
|
||||
"if id(" + getId() + "): " + leftOperand + condition.getSymbol() + rightOperand + " = false, do not execute block");
|
||||
getTestCase().getTestCaseNode().appendChild(commentNode);
|
||||
}
|
||||
endPass();// oder endFail
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import com.itac.mes.datainterface.datasource.BasicDataSource;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
|
||||
public class XmlInstance extends XmlConstruct {
|
||||
|
||||
public XmlInstance(String id) {
|
||||
super(id);
|
||||
iName = "instance";
|
||||
}
|
||||
|
||||
private BasicDataSource instance;
|
||||
private String action;
|
||||
|
||||
public void setInstance(BasicDataSource dataSource) {
|
||||
instance = dataSource;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
super.execute(services);
|
||||
// Wenn es eine Instanz gibt und diese gefunden wurde, dann versuchen die Methode an dieser instanz per reflection
|
||||
// aufzurufen
|
||||
// Fehler werden geloggt, es geht trotzdem weiter
|
||||
try {
|
||||
Method m = instance.getClass().getMethod(action);
|
||||
if (m == null) {
|
||||
throw new Exception("missing operation for instance ...");
|
||||
}
|
||||
m.invoke(instance);
|
||||
} catch (Exception e) {
|
||||
endFail();
|
||||
}
|
||||
|
||||
endPass();// oder endFail
|
||||
}
|
||||
|
||||
public void setAction(String sAction) {
|
||||
this.action = sAction;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
|
||||
import java.io.StringWriter;
|
||||
|
||||
import javax.script.ScriptContext;
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptEngineManager;
|
||||
import javax.script.ScriptException;
|
||||
|
||||
import com.itac.mes.datainterface.datasource.BasicDataSource;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlJavascript extends XmlConstruct {
|
||||
|
||||
public XmlJavascript(String id) {
|
||||
super(id);
|
||||
iName = "javascript";
|
||||
}
|
||||
|
||||
private BasicDataSource instance;
|
||||
private String action;
|
||||
private String script;
|
||||
|
||||
public void setInstance(BasicDataSource dataSource) {
|
||||
instance = dataSource;
|
||||
}
|
||||
|
||||
public void setAction(String sAction) {
|
||||
this.action = sAction;
|
||||
}
|
||||
|
||||
public String getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setting the script to be executes as text
|
||||
*
|
||||
* @param script
|
||||
*/
|
||||
public void setScript(String script) {
|
||||
this.script = script;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
super.execute(services);
|
||||
try {
|
||||
executeJavascript();
|
||||
} catch (ScriptException se) {
|
||||
endFail();
|
||||
} catch (Exception e) {
|
||||
endFail();
|
||||
throw e;
|
||||
}
|
||||
endPass();
|
||||
}
|
||||
|
||||
private void executeJavascript() throws ScriptException {
|
||||
LogHandler.log(getClass().getSimpleName(), INFO, "start executing script");
|
||||
// run command as JavaScript
|
||||
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
|
||||
ScriptContext context = engine.getContext();
|
||||
StringWriter logWriter = new StringWriter();
|
||||
context.setErrorWriter(logWriter);
|
||||
context.setWriter(logWriter);
|
||||
// stores an object under the key `myKey` in the (engine scoped) context
|
||||
context.setAttribute("instance", instance, ScriptContext.ENGINE_SCOPE);
|
||||
engine.put("instance", instance);
|
||||
engine.put("configuration", instance.getConfiguration());
|
||||
engine.put("variables", this.getTestCase().getVariableEngine());
|
||||
|
||||
Object result = engine.eval(script);
|
||||
LogHandler.log(getClass().getSimpleName(), INFO, logWriter.toString());
|
||||
if (result == null)
|
||||
LogHandler.log(getClass().getSimpleName(), INFO, "Script finished with " + result);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
import static com.itac.util.logging.LogLevel.TRACE;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import javax.xml.bind.Unmarshaller;
|
||||
|
||||
import org.w3c.dom.DOMException;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.xml.UnsupportedTypeException;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.mes.datainterface.simulation.DefaultMachineSimulation;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
abstract public class XmlJaxbMachineConstruct extends XmlMachineConstruct {
|
||||
public static final String ACTION_SEND = "send";
|
||||
public static final String METHOD = "method";
|
||||
private JAXBContext jaxbContext;
|
||||
private Unmarshaller unmarshaller;
|
||||
|
||||
protected Node node;
|
||||
protected String sMethod = "";
|
||||
|
||||
public XmlJaxbMachineConstruct(String id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
protected void setMethods(Method[] methods) {
|
||||
List<Class<?>> classList = new ArrayList<Class<?>>();
|
||||
for (Method mMethod : methods) {
|
||||
Class<?>[] paramTypesForMethod = mMethod.getParameterTypes();
|
||||
if (paramTypesForMethod != null) {
|
||||
for (Class<?> clazz : paramTypesForMethod) {
|
||||
classList.add(clazz);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Class<?>[] classArray = new Class[classList.size()];
|
||||
classList.toArray(classArray);
|
||||
|
||||
try {
|
||||
jaxbContext = JAXBContext.newInstance(classArray);
|
||||
unmarshaller = jaxbContext.createUnmarshaller();
|
||||
} catch (JAXBException e) {
|
||||
LogHandler.log(getClass().getSimpleName(), ERROR, "creating the cogiscan unmarshaller failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
*/
|
||||
protected Unmarshaller getUnmarshaller() {
|
||||
return unmarshaller;
|
||||
}
|
||||
|
||||
public void setSubnode(Node node) throws IllegalArgumentException, DOMException, UnsupportedTypeException, InstantiationException,
|
||||
IllegalAccessException, ClassNotFoundException {
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
/**
|
||||
* optional setzen eines Methodennamens, der remote aufgerufen werden soll. das wird dann benötigt, wenn es keine Daten gibt,
|
||||
* anhand dessen Typs (Signatur) die Methode ermittelt werden kann.
|
||||
*
|
||||
* @param sMethod
|
||||
* name of the method to be called
|
||||
*/
|
||||
public void setMethod(String sMethod) {
|
||||
this.sMethod = sMethod;
|
||||
}
|
||||
|
||||
/**
|
||||
* im XML-Knoten all Variablen in Attributen durch Werte ersetzen
|
||||
*
|
||||
* @param node2
|
||||
*/
|
||||
protected void replaceVariableFields(Node node) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
// Attribute
|
||||
if (node.getAttributes() != null) {
|
||||
// alle Attribute umsetzen
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
for (int i = 0; i < attributes.getLength(); i++) {
|
||||
if (attributes.item(i).getNodeValue().startsWith("$")
|
||||
&& getTestCase().getVariableEngine().containsVariable(attributes.item(i).getNodeValue())) {
|
||||
String newValue = getTestCase().getVariableEngine().get(attributes.item(i).getNodeValue()).toString();
|
||||
attributes.item(i).setNodeValue(newValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (node.getNodeType() == Node.TEXT_NODE) {
|
||||
if (getTestCase().getVariableEngine().containsVariable(node.getNodeValue())) {
|
||||
String newValue = getTestCase().getVariableEngine().get(node.getNodeValue()).toString();
|
||||
node.setNodeValue(newValue);
|
||||
}
|
||||
}
|
||||
if (node.getChildNodes() != null) {
|
||||
for (int j = 0; j < node.getChildNodes().getLength(); j++) {
|
||||
replaceVariableFields(node.getChildNodes().item(j));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
super.execute(services);
|
||||
|
||||
// Wenn Clients aktiv Funktionen am commonSmt aufrufen werden die Daten in die aktuelle Variablenliste eingetragen
|
||||
// die Variablen
|
||||
String id = "$" + getId() + '.';
|
||||
|
||||
try {
|
||||
if (getMachineSimulation().hasAction(action)) {
|
||||
getMachineSimulation().executeAction(action, timeout * 1000L);
|
||||
return;
|
||||
}
|
||||
if (action.equals(ACTION_SEND)) {
|
||||
Object requestObject = null;
|
||||
// in diesem Knoten alle Variablen ersetzen, z.B. Datum, stationsnamen, liniennamen etc...
|
||||
if (node != null) {
|
||||
replaceVariableFields(node);// guenstig, da hier alles Texte sind...
|
||||
|
||||
// aus diesem Knoten ein Object machen (z.B. StationEventComposite, etc
|
||||
// den Knoten incl aller subknoten als Text ...
|
||||
|
||||
// aus dem Knotennamen den Klassenname ermitteln, Klasse ermitteln und Unmarshaller erzeugen
|
||||
String className = node.getNodeName();
|
||||
String classPathString = getPackageClassPath() + "." + className;
|
||||
|
||||
Class<?> clazz = Class.forName(classPathString);
|
||||
requestObject = getUnmarshaller().unmarshal(node, clazz).getValue();
|
||||
}
|
||||
// für jede Objektklasse ist definiert, was mit ihr geschehen soll.
|
||||
// ist timeout gesetzt, wird auch auf eine Antwort gewartet (max Zeit)
|
||||
try {
|
||||
Object result = send(id, sMethod, requestObject, timeout);
|
||||
if (result != null) {
|
||||
// zu den Variablen hinzufuegen
|
||||
getTestCase().getVariableEngine().put(id + "return", result);
|
||||
} else {
|
||||
LogHandler.log(getClass().getSimpleName(), TRACE, "no result object from send");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(getClass().getSimpleName(), TRACE, e.getMessage());
|
||||
}
|
||||
|
||||
} else if (action.equals(ACTION_CHANGE_CONFIGURATION)) {
|
||||
changeSimulationConfiguration(getMachineSimulation());
|
||||
}
|
||||
|
||||
getTestCase().getVariableEngine().put(id + "result", "0");
|
||||
endPass();
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(getClass().getSimpleName(), ERROR, "Error at action: " + action, e);
|
||||
getTestCase().getVariableEngine().put(id + "result", "-1");
|
||||
endFail();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
*/
|
||||
abstract protected String getPackageClassPath();
|
||||
|
||||
/**
|
||||
* @return
|
||||
*/
|
||||
abstract protected DefaultMachineSimulation getMachineSimulation();
|
||||
|
||||
abstract protected Object send(String id, String sMethod, Object requestObject, int timeout);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import com.itac.mes.datainterface.gui.IMachineSimulation;
|
||||
import com.itac.mes.datainterface.simulation.DefaultMachineSimulation;
|
||||
|
||||
abstract public class XmlMachineConstruct extends XmlConstruct {
|
||||
public static final String ACTION_CHANGE_CONFIGURATION = "changeConfiguration";
|
||||
|
||||
protected String action;
|
||||
|
||||
// die folgenden vier Werte sind für das ändern einer Konfiguration notwendig...
|
||||
private String parameterName;
|
||||
private String parameterValue;
|
||||
private String parameterLine;
|
||||
private String parameterMachine;
|
||||
|
||||
protected int timeout;
|
||||
|
||||
public XmlMachineConstruct(String id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param machine
|
||||
*/
|
||||
abstract public void setSimulation(IMachineSimulation machine);
|
||||
|
||||
/**
|
||||
* Per Script ändern eines konfig-Wertes...
|
||||
*
|
||||
* @param name
|
||||
* @param value
|
||||
*/
|
||||
public void setParamChangeValues(String name, String value, String parameterLine, String parameterMachine) {
|
||||
this.parameterName = name;
|
||||
this.parameterValue = value;
|
||||
this.parameterLine = parameterLine;
|
||||
this.parameterMachine = parameterMachine;
|
||||
}
|
||||
|
||||
protected void changeSimulationConfiguration(DefaultMachineSimulation machineSimulation) throws Exception {
|
||||
if (action.equals(ACTION_CHANGE_CONFIGURATION)) {
|
||||
if (parameterName == null || parameterValue == null) {
|
||||
// nichts machen
|
||||
} else {
|
||||
// Konfigurationswert aendern
|
||||
String sParameterLine = parameterLine;
|
||||
try {
|
||||
sParameterLine = getTestCase().getVariableEngine().get(parameterLine).toString();
|
||||
} catch (Exception e) {
|
||||
}
|
||||
|
||||
String sParameterMachine = parameterMachine;
|
||||
try {
|
||||
sParameterMachine = getTestCase().getVariableEngine().get(parameterMachine).toString();
|
||||
} catch (Exception e) {
|
||||
}
|
||||
|
||||
if (!machineSimulation.changeConfiguration(parameterName, parameterValue, sParameterLine, sParameterMachine)) {
|
||||
throw new Exception("unable to change parameter '" + parameterName + "', value not set to '" + parameterValue + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* setzen eines timeouts für die Aktion; der Wert ist in Sekunden einzugeben
|
||||
*
|
||||
* @param timeout
|
||||
*/
|
||||
public void setTimeout(int timeout) {
|
||||
this.timeout = timeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param timeout in seconds
|
||||
*/
|
||||
public int getTimeout() {
|
||||
return timeout;
|
||||
}
|
||||
|
||||
public void setAction(String action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
public String getAction() {
|
||||
return action;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
* Copyright (c) 2014 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied, printed, edited
|
||||
* or otherwise distributed, be stored in a retrieval system, or be translated into another language without the written permission
|
||||
* of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
|
||||
import com.itac.mes.datainterface.datasource.database.DbConnectionManager;
|
||||
import com.itac.mes.datainterface.gui.IMachineSimulation;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.mes.intface.basiculi.services.DbTransactionInterface;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlSql extends XmlMachineConstruct {
|
||||
|
||||
public static final String LOGGER = XmlSql.class.getSimpleName();
|
||||
/** the basic SQL command from the source file */
|
||||
private String sql;
|
||||
private String connectionString;
|
||||
private String user;
|
||||
private String password;
|
||||
private DbTransactionInterface currentTransaction;
|
||||
private DbConnectionManager dbConnection;
|
||||
|
||||
public XmlSql(String id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
// pruefen, od diese Funktion ueberhaupt ausgefuehrt werden darf
|
||||
super.execute(services);
|
||||
try {
|
||||
// replace all variables in the source by current values
|
||||
String sqlFin = replaceVariables(sql);
|
||||
|
||||
String connectString = getTestCase().getVariableEngine().get(connectionString).toString();
|
||||
String provider = "";
|
||||
String driver = "";
|
||||
String schema = "bde";
|
||||
// automatically use the correct driver and Provider...
|
||||
if (connectString.startsWith("jdbc:oracle:thin:")) {
|
||||
driver = "oracle.jdbc.driver.OracleDriver";
|
||||
provider = "Oracle";
|
||||
} else {
|
||||
driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
|
||||
provider = "MsSql";
|
||||
}
|
||||
|
||||
try {
|
||||
// create a valid connection and transaction
|
||||
dbConnection = new DbConnectionManager(connectString, driver, schema, provider, user, password, "defaultPool");
|
||||
|
||||
executeStatements(sqlFin);
|
||||
} catch (Throwable e) {
|
||||
LogHandler.log(LOGGER, ERROR, "Database not connected! Check log file", e);
|
||||
}
|
||||
|
||||
// wenn keine Exception oder sonstige Fehler aufgetreten sind ist diese funktion erfolgreich ausgeführt worden.
|
||||
endPass();
|
||||
} catch (Throwable th) {
|
||||
LogHandler.log(LOGGER, ERROR, "execution of xmlsql failed", th);
|
||||
endFail();
|
||||
}
|
||||
}
|
||||
|
||||
private void executeStatements(String sqlFin) {
|
||||
// alle einzelnen Commands sind durch ; getrennt
|
||||
// nacheinander ausfuehren
|
||||
|
||||
String[] lines = sqlFin.split("\\;");
|
||||
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
lines[i] = lines[i].replaceAll("\n", "");
|
||||
if (lines[i].trim().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
LogHandler.log(LOGGER, INFO, "execution of sql: " + lines[i]);
|
||||
if (lines[i].toUpperCase().startsWith("UPDATE")) {
|
||||
getCurrentTransaction().update(lines[i]);
|
||||
} else {
|
||||
getCurrentTransaction().executeStatement(lines[i]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public DbTransactionInterface getCurrentTransaction() {
|
||||
if (currentTransaction == null) {
|
||||
try {
|
||||
currentTransaction = dbConnection.getDbTransaction();
|
||||
} catch (Throwable e) {
|
||||
LogHandler.log(LOGGER, ERROR, "getCurrentTransaction failed", e);
|
||||
}
|
||||
}
|
||||
return currentTransaction;
|
||||
}
|
||||
|
||||
private String replaceVariables(String select) throws Exception {
|
||||
StringBuilder stb = new StringBuilder(select);
|
||||
boolean replaced = false;
|
||||
int start = 0;
|
||||
do {
|
||||
start = stb.indexOf("{$", start);
|
||||
int end = 0;
|
||||
if (start > 0) {
|
||||
end = stb.indexOf("}", start);
|
||||
if (end == -1) {
|
||||
throw new Exception("missing char '}' after variable");
|
||||
}
|
||||
}
|
||||
replaced = false;
|
||||
if (start >= 0 && end > 0) {
|
||||
|
||||
String variableName = stb.substring(start + 1, end);
|
||||
Object varValue = getTestCase().getVariableEngine().get(variableName);
|
||||
// ersetzen
|
||||
if (varValue == null) {
|
||||
throw new Exception("missing Variable '" + variableName + "'");
|
||||
}
|
||||
stb.replace(start, end + 1, varValue.toString());
|
||||
replaced = true;
|
||||
start = 0;
|
||||
}
|
||||
} while (replaced);
|
||||
|
||||
return stb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param machine
|
||||
*/
|
||||
@Override
|
||||
public void setSimulation(IMachineSimulation machineSimulation) {
|
||||
// es wird keine Simulation zur Ausfuehrung benoetigt
|
||||
}
|
||||
|
||||
public void setConnectionString(String nodeValue) {
|
||||
this.connectionString = nodeValue;
|
||||
}
|
||||
|
||||
public void setUser(String nodeValue) {
|
||||
this.user = nodeValue;
|
||||
}
|
||||
|
||||
public void setPassword(String nodeValue) {
|
||||
this.password = nodeValue;
|
||||
}
|
||||
|
||||
public void setSelect(String sql) throws Exception {
|
||||
if (sql == null) {
|
||||
throw new Exception("not allowed to set null as sql-statement");
|
||||
}
|
||||
this.sql = sql;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.DEBUG;
|
||||
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlString extends XmlConstruct {
|
||||
|
||||
private String varName;
|
||||
private String varValue;
|
||||
private XmlStringOperation operation;
|
||||
|
||||
public XmlString(String id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Variable id(" + getId() + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
super.execute(services);
|
||||
LogHandler.log("XmlVariable", DEBUG, "modifying variable by script");
|
||||
if (!getTestCase().getVariableEngine().containsVariable(varName)) {
|
||||
// Variable nicht gefunden...
|
||||
throw new TestcaseException("Variable " + varName + " not found in TestCase " + getTestCase().getId());
|
||||
}
|
||||
String currentValue = getTestCase().getVariableEngine().get(varName).toString();
|
||||
switch (operation) {
|
||||
case APPEND:
|
||||
if (VariableEngine.isVariable(varValue)) {
|
||||
currentValue = currentValue + getTestCase().getVariableEngine().get(varValue).toString();
|
||||
} else {
|
||||
currentValue += varValue;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
getTestCase().getVariableEngine().put(varName, currentValue);
|
||||
}
|
||||
|
||||
public void set(String variable, String value, XmlStringOperation operation) {
|
||||
this.varName = variable;
|
||||
this.varValue = value;
|
||||
this.operation = operation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (c) 2010 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
/**
|
||||
* @author frankp created 2011
|
||||
*/
|
||||
public enum XmlStringOperation {
|
||||
|
||||
APPEND("append");
|
||||
|
||||
private XmlStringOperation(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
private String text;
|
||||
|
||||
public static XmlStringOperation getOperation(String text) {
|
||||
for (XmlStringOperation opCode : XmlStringOperation.values()) {
|
||||
if (opCode.text.equals(text)) {
|
||||
return opCode;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String getAllOperations() {
|
||||
StringBuffer result = new StringBuffer();
|
||||
for (XmlStringOperation opCode : XmlStringOperation.values()) {
|
||||
if (result.length() > 0) {
|
||||
result.append(",");
|
||||
}
|
||||
result.append(opCode.text);
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import com.itac.mes.api.domain.EWApiServices;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.mes.imsapi.domain.IMSApiService;
|
||||
import com.itac.util.annotation.ItacMethodDescriptor;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlTemplate extends XmlConstruct {
|
||||
|
||||
public XmlTemplate(String id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) {
|
||||
StringBuffer stb = new StringBuffer();
|
||||
Method[] apiMethodArray = EWApiServices.class.getMethods();
|
||||
stb.append("EW Api \n");
|
||||
for (Method method : apiMethodArray) {
|
||||
printMethod(method);
|
||||
}
|
||||
stb.append("IMS Api \n");
|
||||
apiMethodArray = IMSApiService.class.getMethods();
|
||||
for (Method method : apiMethodArray) {
|
||||
printMethod(method);
|
||||
}
|
||||
}
|
||||
|
||||
private void printMethod(Method method) {
|
||||
StringBuilder stb = new StringBuilder();
|
||||
stb.append("<").append(method.getName());
|
||||
stb.append(" id=\"\"");
|
||||
// Die Parameternamen werden jetzt ueber Annotations ausgelesen
|
||||
// @ItacMethodDescriptor(argNames={"sessValData"})
|
||||
ItacMethodDescriptor methodDescriptor = method.getAnnotation(ItacMethodDescriptor.class);
|
||||
if (methodDescriptor == null) {
|
||||
LogHandler.warn(
|
||||
"method " + method.getName() + " is not annotated with \"@ItacMethodDescriptor\", method has no parameters ...\n");
|
||||
} else {
|
||||
// alle Parameter als Attribute
|
||||
for (String paramName : methodDescriptor.argNames()) {
|
||||
stb.append(" ").append(paramName).append("=\"\"");
|
||||
}
|
||||
}
|
||||
stb.append("/>\n");
|
||||
LogHandler.info(stb.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright (c) 2014 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied, printed, edited
|
||||
* or otherwise distributed, be stored in a retrieval system, or be translated into another language without the written permission
|
||||
* of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import com.itac.mes.datainterface.gui.IMachineSimulation;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
|
||||
public class XmlTestCaseDetail extends XmlMachineConstruct {
|
||||
|
||||
private String text;
|
||||
|
||||
public XmlTestCaseDetail(String id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) throws TestcaseException {
|
||||
// es gibt keine Ausführung !!!
|
||||
super.execute(services);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param machine
|
||||
*/
|
||||
@Override
|
||||
public void setSimulation(IMachineSimulation machineSimulation) {
|
||||
// es wird keine Simulation zur Ausfuehrung benoetigt
|
||||
}
|
||||
|
||||
public void setDetailText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public String getDetailText() {
|
||||
if (text == null) {
|
||||
return "";
|
||||
}
|
||||
return text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
import com.itac.util.logging.LogLevel;
|
||||
|
||||
public class XmlVariable extends XmlConstruct {
|
||||
|
||||
private String varName;
|
||||
private String varValue;
|
||||
|
||||
public XmlVariable(String id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Variable id(" + getId() + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) {
|
||||
LogHandler.log("XmlVariable", LogLevel.DEBUG, "adding variable by script");
|
||||
getTestCase().getVariableEngine().put(varName, varValue);
|
||||
}
|
||||
|
||||
public void set(String variable, String value) {
|
||||
this.varName = variable;
|
||||
this.varValue = value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import com.itac.mes.datainterface.data.Duration;
|
||||
import com.itac.mes.datainterface.service.DataInterfaceServices;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlWait extends XmlConstruct {
|
||||
|
||||
private Duration duration = new Duration(0);
|
||||
|
||||
public XmlWait(String id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceServices services) {
|
||||
try {
|
||||
Thread.sleep(duration.getMillies());
|
||||
|
||||
} catch (Exception e) {
|
||||
LogHandler.error("wait not performed properly");
|
||||
}
|
||||
}
|
||||
|
||||
public String getTime() {
|
||||
return duration.toString();
|
||||
}
|
||||
|
||||
public void setTime(String time) {
|
||||
duration = new Duration(time);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package com.itac.mes.datainterface.filehandler;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.DEBUG;
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
import static com.itac.util.logging.LogLevel.WARN;
|
||||
|
||||
import java.io.File;
|
||||
import java.text.MessageFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import javax.xml.transform.OutputKeys;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
|
||||
import com.itac.mes.config.domain.Parameter;
|
||||
import com.itac.mes.config.domain.ParameterEnumerationProperties;
|
||||
import com.itac.mes.datainterface.ConfigurationException;
|
||||
import com.itac.mes.datainterface.annotations.AInstantiationType;
|
||||
import com.itac.mes.datainterface.annotations.AParamValue;
|
||||
import com.itac.mes.datainterface.annotations.AParameter;
|
||||
import com.itac.mes.datainterface.annotations.AParameterProperties;
|
||||
import com.itac.mes.datainterface.annotations.InstantiationType;
|
||||
import com.itac.mes.datainterface.data.FileUnit;
|
||||
import com.itac.mes.datainterface.data.ProcessResult;
|
||||
import com.itac.mes.datainterface.data.UploadXmlTestPlanUnit;
|
||||
import com.itac.mes.datainterface.factories.AConfigurableHandler;
|
||||
import com.itac.mes.datainterface.process.IProcessor.Code;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
@AInstantiationType(name = "xmlapi", type = InstantiationType.FILEHANDLER, inheritParameter = false)
|
||||
public class XmlApiFileHandler extends DefaultFileHandler {
|
||||
|
||||
private static final String LOGGER = XmlApiFileHandler.class.getSimpleName();
|
||||
// define the keys as they are used in the configuration
|
||||
private static final String FILEHANDLER_XMLAPI = "filehandler.xmlapi";
|
||||
private static final String ERROR_PATTERN = FILEHANDLER_XMLAPI + ".errorPattern";
|
||||
private static final String BACKUP_PATTERN = FILEHANDLER_XMLAPI + ".backupPattern";
|
||||
private static final String UNPROCESSED_PATTERN = FILEHANDLER_XMLAPI + ".unprocessedPattern";
|
||||
private static final String BACKUP_LEVEL = FILEHANDLER_XMLAPI + ".backupLevel";
|
||||
private static final String BACKUP_DIR = FILEHANDLER_XMLAPI + ".backupDir";
|
||||
private static final String ERROR_DIR = FILEHANDLER_XMLAPI + ".errorDir";
|
||||
private static final String WORK_DIR = FILEHANDLER_XMLAPI + ".workDir";
|
||||
private static final String UNPROCESSED_DIR = FILEHANDLER_XMLAPI + ".unprocessedDir";
|
||||
private static final String WORK_DIR_CLEAN = FILEHANDLER_XMLAPI + ".workDirClean";
|
||||
private static final String OUTPUT_PATTERN = FILEHANDLER_XMLAPI + ".outputPattern";
|
||||
private static final String OUTPUT_DIR = FILEHANDLER_XMLAPI + ".outputDir";
|
||||
private static final String PASS_TEXT = FILEHANDLER_XMLAPI + ".pass";
|
||||
private static final String FAIL_TEXT = FILEHANDLER_XMLAPI + ".fail";
|
||||
|
||||
@AParameter(name = FILEHANDLER_XMLAPI, description = "XmlApi file handler",
|
||||
visibility = "FileHandler=com.itac.mes.datainterface.filehandler.XmlApiFileHandler")
|
||||
private Parameter paramFileHandler;
|
||||
@AParameter(name = ERROR_PATTERN, parent = FILEHANDLER_XMLAPI, description = "error pattern", type = String.class)
|
||||
private Parameter paramErrorPattern;
|
||||
@AParameter(name = BACKUP_PATTERN, parent = FILEHANDLER_XMLAPI, description = "backup pattern", type = String.class)
|
||||
private Parameter paramBackupPattern;
|
||||
@AParameter(name = OUTPUT_PATTERN, parent = FILEHANDLER_XMLAPI, description = "output pattern", type = String.class)
|
||||
private Parameter paramOutputPattern;
|
||||
@AParameter(name = UNPROCESSED_PATTERN, parent = FILEHANDLER_XMLAPI, description = "unprocessed pattern", type = String.class)
|
||||
private Parameter paramUnprocessedPattern;
|
||||
@AParameter(name = BACKUP_LEVEL, parent = FILEHANDLER_XMLAPI, description = "backup level", type = Enum.class,
|
||||
metaType = Integer.class)
|
||||
private Parameter paramBackupLevel;
|
||||
@AParameter(name = BACKUP_DIR, parent = FILEHANDLER_XMLAPI, description = "backup directory", type = String.class)
|
||||
private Parameter paramBackupDir;
|
||||
@AParameter(name = ERROR_DIR, parent = FILEHANDLER_XMLAPI, description = "error directory", type = String.class)
|
||||
private Parameter paramErrorDir;
|
||||
@AParameter(name = OUTPUT_DIR, parent = FILEHANDLER_XMLAPI, description = "output directory", type = String.class)
|
||||
private Parameter paramOutputDir;
|
||||
@AParameter(name = WORK_DIR, parent = FILEHANDLER_XMLAPI, description = "working directory", type = String.class)
|
||||
private Parameter paramWorkDir;
|
||||
@AParameter(name = UNPROCESSED_DIR, parent = FILEHANDLER_XMLAPI, description = "unprocessed directory", type = String.class)
|
||||
private Parameter paramUnprocessedDir;
|
||||
@AParameter(name = WORK_DIR_CLEAN, parent = FILEHANDLER_XMLAPI, description = "cleanup workup directory", type = Boolean.class)
|
||||
private Parameter paramCleanWorkDir;
|
||||
@AParameter(name = PASS_TEXT, parent = FILEHANDLER_XMLAPI, description = "text for Pass tests for output-pattern",
|
||||
type = String.class)
|
||||
private Parameter paramPass;
|
||||
@AParameter(name = FAIL_TEXT, parent = FILEHANDLER_XMLAPI, description = "text for Fail tests for output-pattern",
|
||||
type = String.class)
|
||||
private Parameter paramFail;
|
||||
|
||||
private File outputDirectory;
|
||||
private String outputPattern;
|
||||
@AParamValue(value = PASS_TEXT)
|
||||
private String sPass;
|
||||
@AParamValue(value = FAIL_TEXT)
|
||||
private String sFail;
|
||||
|
||||
public XmlApiFileHandler() {
|
||||
super();
|
||||
}
|
||||
|
||||
@AParamValue(value = BACKUP_DIR)
|
||||
public void setBackupDirectory(String value) throws ConfigurationException {
|
||||
super.setBackupDirectory(value);
|
||||
}
|
||||
|
||||
@AParamValue(value = WORK_DIR)
|
||||
public void setWorkDirectory(String value) throws ConfigurationException {
|
||||
super.setWorkDirectory(value);
|
||||
}
|
||||
|
||||
@AParamValue(value = ERROR_DIR)
|
||||
public void setErrorDirectory(String value) throws ConfigurationException {
|
||||
super.setErrorDirectory(value);
|
||||
}
|
||||
|
||||
@AParamValue(value = UNPROCESSED_DIR)
|
||||
public void setUnprocessedDirectory(String value) throws ConfigurationException {
|
||||
super.setUnprocessedDirectory(value);
|
||||
}
|
||||
|
||||
@AParamValue(value = OUTPUT_DIR)
|
||||
public void setOutputDirectory(String value) throws ConfigurationException {
|
||||
File directory = new File(value);
|
||||
getConfiguration().checkDirectory(directory);
|
||||
outputDirectory = directory;
|
||||
}
|
||||
|
||||
@AParamValue(value = OUTPUT_PATTERN)
|
||||
public void setOutputPattern(String value) throws ConfigurationException {
|
||||
outputPattern = value;
|
||||
}
|
||||
|
||||
@AParamValue(value = BACKUP_PATTERN)
|
||||
public void setBackupPattern(String value) throws ConfigurationException {
|
||||
super.setBackupPattern(value);
|
||||
}
|
||||
|
||||
@AParamValue(value = BACKUP_LEVEL)
|
||||
public void setBackupLevel(Integer value) throws ConfigurationException {
|
||||
super.setBackupLevel(value);
|
||||
}
|
||||
|
||||
@AParamValue(value = ERROR_PATTERN)
|
||||
public void setErrorPattern(String value) throws ConfigurationException {
|
||||
super.setErrorPattern(value);
|
||||
}
|
||||
|
||||
@AParamValue(value = UNPROCESSED_PATTERN)
|
||||
public void setUnprocessedPattern(String value) throws ConfigurationException {
|
||||
super.setUnprocessedPattern(value);
|
||||
}
|
||||
|
||||
@AParamValue(value = WORK_DIR_CLEAN)
|
||||
protected void setCleanup(boolean value) {
|
||||
super.setCleanup(value);
|
||||
}
|
||||
|
||||
@AParameterProperties(name = BACKUP_LEVEL)
|
||||
public static ParameterEnumerationProperties<Integer> getProperties() {
|
||||
ParameterEnumerationProperties<Integer> props = new ParameterEnumerationProperties<Integer>(Integer.class);
|
||||
props.add(BACKUP_NONE, "none");
|
||||
props.add(BACKUP_ERROR, "error");
|
||||
props.add(BACKUP_ALL, "all");
|
||||
return props;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int endFile(FileUnit file) {
|
||||
// je nach dem in wie weit das File bisher verarbeitet wurde wird das File jetzt kpl ins error-Verzeichnis gemoved
|
||||
// oder ins OK-Verzeichnis geschoben
|
||||
// oder zerlegt und teils ins error und teils ins backup geschoben.
|
||||
// mit gesonderter Einstellung kann der Backup-Vorgang auch unterbunden werden.
|
||||
LogHandler.log(LOGGER, DEBUG, "end file");
|
||||
int code = AConfigurableHandler.OK;
|
||||
|
||||
// File erzeugen
|
||||
if (file.uploadUnitList != null && file.uploadUnitList.size() != 0) {
|
||||
for (int i = 0; i < file.uploadUnitList.size(); i++) {
|
||||
|
||||
UploadXmlTestPlanUnit xmlUploadUnit = (UploadXmlTestPlanUnit) file.uploadUnitList.get(i);
|
||||
String passFail = sPass;
|
||||
if (!xmlUploadUnit.getTotalResult()) {
|
||||
passFail = sFail;
|
||||
}
|
||||
String newFileName = MessageFormat.format(outputPattern,
|
||||
new Object[] { FileTools.getBaseName(file.file), FileTools.getExtension(file.file), new Date(), passFail });
|
||||
File outFile = new File(outputDirectory.getPath() + File.separator + newFileName);
|
||||
// This method writes a DOM document to a file
|
||||
try {
|
||||
// Prepare the DOM document for writing
|
||||
DOMSource source = new DOMSource(xmlUploadUnit.getDocument());
|
||||
|
||||
// Prepare the output file
|
||||
StreamResult result = new StreamResult(outFile);
|
||||
|
||||
// Write the DOM document to the file
|
||||
Transformer xformer = TransformerFactory.newInstance().newTransformer();
|
||||
xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
|
||||
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
xformer.transform(source, result);
|
||||
} catch (Exception e) {
|
||||
writeMessage(ERROR, "failed to write result file!");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (file.processResultList == null) {
|
||||
// File wurde in keinster Weise bearbeitet
|
||||
LogHandler.log(LOGGER, WARN, "file was not processed or no ProcessResult was set!");
|
||||
|
||||
if (backupLevel != DefaultFileHandler.BACKUP_NONE) {
|
||||
code = FileTools.renameFile(file, errorPattern);
|
||||
if (code == AConfigurableHandler.OK) {
|
||||
try {
|
||||
FileTools.moveFile(file.file, errorDirectory, overrideExistingfiles);
|
||||
writeMessage(ERROR, true, ": file moved into error directory");
|
||||
} catch (FileException exception) {
|
||||
LogHandler.log(LOGGER, ERROR, "Failed to move file: " + exception.getMessage());
|
||||
eventHandler.raise(DefaultFileHandler.COND_FILE_NOT_MOVED, eventSourceInfo);
|
||||
code = IFileHandler.FILE_MOVE_ERROR;
|
||||
writeMessage(DEBUG, true, ": failed to move file");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
LogHandler.log(LOGGER, INFO, "Delete processed File ");
|
||||
if (!file.file.delete()) {
|
||||
LogHandler.log(LOGGER, ERROR, "Deleting file failed");
|
||||
writeMessage(DEBUG, ": file NOT deleted");
|
||||
eventHandler.raise(DefaultFileHandler.COND_FILE_NOT_REMOVED, eventSourceInfo);
|
||||
} else {
|
||||
writeMessage(DEBUG, ": file deleted");
|
||||
}
|
||||
}
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
// file was processed, but no process information was set
|
||||
// this is treated as the default for all ok
|
||||
if (file.processResultList.size() == 0) {
|
||||
LogHandler.log(LOGGER, DEBUG, "file was processed but no detailled process information available!");
|
||||
code = doOkFile(file);
|
||||
return code;
|
||||
}
|
||||
writeMessage(DEBUG, "" + file.processResultList.size() + " units processed");
|
||||
for (int i = 0; i < file.processResultList.size(); i++) {
|
||||
writeMessage(DEBUG, "unit " + (i + 1) + ": " + file.processResultList.get(i).getDetailText());
|
||||
}
|
||||
|
||||
ProcessResult processResult = file.processResultList.get(0);
|
||||
try {
|
||||
if (processResult.getResultCode() == Code.OK) {
|
||||
code = doOkFile(file);
|
||||
} else if (processResult.getResultCode() == Code.SKIPPED_OR_UNPROCESSED) {
|
||||
code = FileTools.renameFile(file, unprocessedPattern);
|
||||
if (code == AConfigurableHandler.OK) {
|
||||
FileTools.moveFile(file.file, unprocessedDirectory, overrideExistingfiles);
|
||||
}
|
||||
} else {
|
||||
writeMessage(DEBUG, "end File");
|
||||
code = doErrorFile(file);
|
||||
}
|
||||
} catch (FileException exception) {
|
||||
LogHandler.log(LOGGER, ERROR, "Failed to move file: " + exception.getMessage());
|
||||
code = IFileHandler.FILE_MOVE_ERROR;
|
||||
eventHandler.raise(DefaultFileHandler.COND_FILE_NOT_MOVED, eventSourceInfo);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.itac.mes.datainterface.parser;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlMachineConstruct;
|
||||
import com.itac.mes.datainterface.gui.IMachineSimulation;
|
||||
|
||||
public abstract class MachinePluginParser extends PluginParser {
|
||||
|
||||
protected static final String SIMULATION = "simulation";
|
||||
protected static final String ACTION = "action";
|
||||
protected static final String TIMEOUT = "timeout";
|
||||
|
||||
protected static final String MACHINE = "machine";
|
||||
protected static final String LINE = "line";
|
||||
protected static final String VALUE = "value";
|
||||
protected static final String PARAMETER = "parameter";
|
||||
|
||||
public MachinePluginParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
protected String getIdConstructHeader(String id, String construct) {
|
||||
return "id: " + id + ": construct '" + construct + "'";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param machine
|
||||
* @param name
|
||||
* @param simulation
|
||||
* @param id
|
||||
* @param expectedSimulationClass
|
||||
* @throws Exception
|
||||
*/
|
||||
protected void checkMachineSimulation(IMachineSimulation machine, String name, String simulation, String id,
|
||||
Class<?> expectedSimulationClass) throws Exception {
|
||||
if (machine == null) {
|
||||
throw new Exception(getIdConstructHeader(id, name) + " wrong; the requested simulation '" + simulation + "' is not known!\n"
|
||||
+ "Available simulations are " + getToolBox().getSimulationInstanceNames());
|
||||
}
|
||||
|
||||
if (machine.getClass() != expectedSimulationClass) {
|
||||
throw new Exception(getIdConstructHeader(id, name) + " wrong; the simulation type is '" + machine.getSimulationType()
|
||||
+ "' and not " + expectedSimulationClass + "!\n");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param name
|
||||
* @param action
|
||||
* @param action2
|
||||
* @param allowedActions
|
||||
* @param xmlConstructActions
|
||||
* @throws Exception
|
||||
*/
|
||||
protected void checkActions(String name, String action, String id, Set<String> allowedActions, String[] xmlConstructActions)
|
||||
throws Exception {
|
||||
Set<String> constructActionSet = new HashSet<String>();
|
||||
for (String key : xmlConstructActions) {
|
||||
constructActionSet.add(key);
|
||||
}
|
||||
if (!allowedActions.contains(action) && !constructActionSet.contains(action)) {
|
||||
// aus dem Set der allowed Actions Text bauen
|
||||
StringBuffer machineActions = new StringBuffer();
|
||||
for (String key : allowedActions) {
|
||||
if (machineActions.length() > 0) {
|
||||
machineActions.append(",");
|
||||
}
|
||||
machineActions.append(key);
|
||||
}
|
||||
|
||||
StringBuffer constructActions = new StringBuffer();
|
||||
for (String key : constructActionSet) {
|
||||
if (constructActions.length() > 0) {
|
||||
constructActions.append(",");
|
||||
}
|
||||
constructActions.append(key);
|
||||
}
|
||||
|
||||
throw new Exception(getIdConstructHeader(id, name) + " wrong:\nattribute action has wrong value (" + action
|
||||
+ "), possible values for machine are " + machineActions.toString() + "\npossible actions for xmlConstruct are "
|
||||
+ constructActions);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param oibXmlConstruct
|
||||
* @param attributes
|
||||
* @throws Exception
|
||||
*/
|
||||
protected void parseChangeConfiguration(XmlMachineConstruct xmlMachineConstruct, NamedNodeMap attributes) throws Exception {
|
||||
checkAttributesNotEmpty(attributes, new String[] { PARAMETER, VALUE, MACHINE }, getName());
|
||||
checkAttributes(attributes, new String[] { LINE }, getName());
|
||||
String sParameter = getAttributeValue(attributes, PARAMETER);
|
||||
String sParameterBValue = getAttributeValue(attributes, VALUE);
|
||||
String sParameterLine = getAttributeValue(attributes, LINE);
|
||||
String sParameterMachine = getAttributeValue(attributes, MACHINE);
|
||||
xmlMachineConstruct.setParamChangeValues(sParameter, sParameterBValue, sParameterLine, sParameterMachine);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.itac.mes.datainterface.parser;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
|
||||
public abstract class PluginParser extends IPluginParser {
|
||||
|
||||
protected static final String ATTR_ID = "id";
|
||||
|
||||
public PluginParser(String simulationType, Toolbox toolbox) {
|
||||
super(simulationType, toolbox);
|
||||
}
|
||||
|
||||
public abstract XmlConstruct parse(Node node) throws Exception;
|
||||
|
||||
@Override
|
||||
public abstract boolean includeSubNodes();
|
||||
|
||||
/**
|
||||
* prueft, dass die Attribute aus attribNames alle vorhanden und nicht leer sind
|
||||
*
|
||||
* @param attributes
|
||||
* @param id
|
||||
* @throws Exception
|
||||
* wenn eines der zu prüfenden Attribute nicht vorhanden oder leer ist
|
||||
*/
|
||||
public void checkAttributesNotEmpty(NamedNodeMap attributes, String[] attributeNames, String elementName) throws Exception {
|
||||
if (attributes == null) {
|
||||
String allAttributeNames = "";
|
||||
for (String attrName : attributeNames) {
|
||||
allAttributeNames = allAttributeNames + "'" + attrName + "',";
|
||||
}
|
||||
throw new Exception("missing attributes " + allAttributeNames + " for element '" + elementName + "'");
|
||||
}
|
||||
|
||||
for (String attrName : attributeNames) {
|
||||
if (attributes.getNamedItem(attrName) == null) {
|
||||
throw new Exception("missing attribute '" + attrName + "' for element '" + elementName + "'");
|
||||
}
|
||||
String value = attributes.getNamedItem(attrName).getNodeValue();
|
||||
if (value == null || value.equals("")) {
|
||||
throw new Exception("attribute '" + attrName + "' for element '" + elementName + "' is null or empty");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* prüft, dass die Attribute aus attribNames alle vorhanden sind, leere Attribute sind jedoch zulässig
|
||||
*
|
||||
* @param attributes
|
||||
* @param id
|
||||
* @throws Exception
|
||||
* , wenn ein Attribut nicht vorhanden ist
|
||||
*/
|
||||
public void checkAttributes(NamedNodeMap attributes, String[] attributeNames, String elementName) throws Exception {
|
||||
if (attributes == null) {
|
||||
String allAttributeNames = "";
|
||||
for (String attrName : attributeNames) {
|
||||
allAttributeNames = allAttributeNames + "'" + attrName + "',";
|
||||
}
|
||||
throw new Exception("missing attributes " + allAttributeNames + " for element '" + elementName + "'");
|
||||
}
|
||||
|
||||
for (String attrName : attributeNames) {
|
||||
if (attributes.getNamedItem(attrName) == null) {
|
||||
throw new Exception("missing attribute '" + attrName + "' for element '" + elementName + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param attributes
|
||||
* alle Attribute eines Knotens
|
||||
* @param attributeName
|
||||
* der Name des Attributes, für das der Wert zu ermitteln ist
|
||||
* @return wenn das Attribut nicht vorhanden ist liefert diese Funkiton einen Leerstring
|
||||
*/
|
||||
protected String getAttributeValue(NamedNodeMap attributes, String attributeName) {
|
||||
if (attributes.getNamedItem(attributeName) != null) {
|
||||
return attributes.getNamedItem(attributeName).getNodeValue();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
/*
|
||||
* Copyright (c) 2010 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied, printed, edited
|
||||
* or otherwise distributed, be stored in a retrieval system, or be translated into another language without the written permission
|
||||
* of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.parser;
|
||||
|
||||
import static com.itac.mes.datainterface.ParameterUpdateTool.DEFAULT_DIM_PATH;
|
||||
import static com.itac.util.logging.LogLevel.DEBUG;
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
import static com.itac.util.logging.LogLevel.TRACE;
|
||||
import static com.itac.util.logging.LogLevel.WARN;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import com.itac.mes.config.domain.Parameter;
|
||||
import com.itac.mes.datainterface.annotations.AAutoHandler;
|
||||
import com.itac.mes.datainterface.annotations.AInit;
|
||||
import com.itac.mes.datainterface.annotations.AInstantiationType;
|
||||
import com.itac.mes.datainterface.annotations.AParamValue;
|
||||
import com.itac.mes.datainterface.annotations.AParameter;
|
||||
import com.itac.mes.datainterface.annotations.InstantiationType;
|
||||
import com.itac.mes.datainterface.data.BasicUploadUnit;
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.UploadXmlTestPlanUnit;
|
||||
import com.itac.mes.datainterface.data.xmlapi.VariableEngine;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlFunctionCall;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlFunctionDefinition;
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestCase;
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestSuite;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.AssertionJsParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.AssertionParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.DumpParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.ForParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.FunctionCallParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.FunctionParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.IfParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.InstanceParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.JavascriptParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.SqlXmlParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.StringParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.TestCaseDetailParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.VariableParser;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.WaitParser;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
import com.itac.util.logging.evaluation.ObjectEvaluator;
|
||||
|
||||
@AInstantiationType(type = InstantiationType.PARSER, name = "xmlapi")
|
||||
public class XmlApiParser extends BasicXMLParser {
|
||||
|
||||
private static final String XMLAPI_PARSER = "parser.xmlapi";
|
||||
private static final String XMLAPI_XSLT = "parser.xmlapi.xslt";
|
||||
|
||||
@AParameter(name = XMLAPI_PARSER, description = "XML API Parser", dimPath = DEFAULT_DIM_PATH,
|
||||
visibility = "Parser=com.itac.mes.datainterface.parser.XmlApiParser")
|
||||
private Parameter paramRoot;
|
||||
@AParameter(name = XMLAPI_XSLT, parent = XMLAPI_PARSER, description = "XSLT File for XML API Parser", type = String.class)
|
||||
private Parameter paramXslt;
|
||||
@AAutoHandler(InstantiationType.TOOL)
|
||||
private Toolbox toolbox;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final String TESTCASE = "TestCase";
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final String TESTSUITE = "TestSuite";
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final String TESTPLAN = "TestPlan";
|
||||
|
||||
private static final String LOGGER = XmlApiParser.class.getSimpleName();
|
||||
|
||||
private FunctionParser functionParser;
|
||||
|
||||
private String xsltFile;
|
||||
private ObjectEvaluator objectEvaluator = new ObjectEvaluator();
|
||||
|
||||
public XmlApiParser() {
|
||||
super();
|
||||
getSupportedRootElements().add(TESTPLAN);
|
||||
}
|
||||
|
||||
@AInit
|
||||
public void atInit() {
|
||||
functionParser = new FunctionParser("", toolbox);
|
||||
toolbox.addPluginParser(new AssertionParser("Assertion", toolbox));
|
||||
toolbox.addPluginParser(new ForParser("for", toolbox));
|
||||
toolbox.addPluginParser(new IfParser("if", toolbox));
|
||||
toolbox.addPluginParser(new DumpParser("dump", toolbox));
|
||||
toolbox.addPluginParser(new WaitParser("wait", toolbox));
|
||||
toolbox.addPluginParser(new VariableParser(VariableParser.VARIABLE, toolbox));
|
||||
toolbox.addPluginParser(new StringParser("string", toolbox));
|
||||
toolbox.addPluginParser(new FunctionCallParser("call", toolbox));
|
||||
toolbox.addPluginParser(new InstanceParser("instance", toolbox));
|
||||
toolbox.addPluginParser(new JavascriptParser("javascript", toolbox));
|
||||
toolbox.addPluginParser(new SqlXmlParser("sql", toolbox));
|
||||
toolbox.addPluginParser(new TestCaseDetailParser("details", toolbox));
|
||||
toolbox.addPluginParser(new AssertionJsParser("AssertJs", toolbox));
|
||||
}
|
||||
|
||||
@AParamValue(value = XMLAPI_XSLT)
|
||||
|
||||
public void setXsltFile(String xsltFile) {
|
||||
this.xsltFile = xsltFile;
|
||||
LogHandler.log(XmlApiParser.class.getSimpleName(), DEBUG, "use '" + xsltFile + "' as xslt file in output files");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Code parseDocument(Document document, String fileName, List<BasicUploadUnit> uploadUnitList, StringBuffer resultText) {
|
||||
Code code = Code.NOT_PARSED;
|
||||
long startTime = System.currentTimeMillis();
|
||||
Node node = document.getDocumentElement();
|
||||
if (node.getNodeName().equals(TESTPLAN)) {
|
||||
code = parseTestPlan(node, uploadUnitList, resultText);
|
||||
} else {
|
||||
LogHandler.log(LOGGER, ERROR, "missing root document 'TestPlan'\n");
|
||||
resultText.append("missing root document 'TestPlan'\n");
|
||||
code = Code.PARSE_ERROR;
|
||||
}
|
||||
long endTime = System.currentTimeMillis();
|
||||
LogHandler.log(LOGGER, INFO, "document '" + fileName + "' parsed in " + (endTime - startTime) + "ms");
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
private Code parseTestPlan(Node testPlanNode, List<BasicUploadUnit> uploadUnitList, StringBuffer resultText) {
|
||||
Code code = Code.OK;
|
||||
NamedNodeMap attributes = testPlanNode.getAttributes();
|
||||
// Attribute pruefen, id muss vorhanden und nicht leer und eindeutig sein
|
||||
try {
|
||||
checkAttributesNotEmpty(attributes, new String[] { XmlConstruct.ID }, TESTPLAN);
|
||||
} catch (Exception e) {
|
||||
code = Code.PARSE_ERROR;
|
||||
resultText.append(e.getMessage());
|
||||
}
|
||||
String desc = getAttributeValue(attributes, UploadXmlTestPlanUnit.DESC);
|
||||
|
||||
UploadXmlTestPlanUnit xmlTestPlan = new UploadXmlTestPlanUnit();
|
||||
xmlTestPlan.setXsltFile(xsltFile);
|
||||
if (code == Code.OK) {
|
||||
xmlTestPlan.setId(attributes.getNamedItem(XmlConstruct.ID).getNodeValue());
|
||||
xmlTestPlan.setDesc(desc);
|
||||
boolean testSuiteFound = false;
|
||||
NodeList nodes = testPlanNode.getChildNodes();
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
Node node = nodes.item(i);
|
||||
if (node.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
if (node.getNodeName().equals(TESTSUITE)) {
|
||||
testSuiteFound = true;
|
||||
code = parseTestSuite(node, xmlTestPlan, resultText);
|
||||
} else {
|
||||
LogHandler.log(LOGGER, WARN, node.getNodeName() + " is not expected here. Expected is '" + TESTSUITE + "'");
|
||||
}
|
||||
}
|
||||
if (!testSuiteFound) {
|
||||
resultText.append("missing element 'TestSuite'\n");
|
||||
code = Code.PARSE_ERROR;
|
||||
}
|
||||
}
|
||||
if (code == Code.OK) {
|
||||
uploadUnitList.add(xmlTestPlan);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* prueft, dass die Attribute aus attribNames alle vorhanden und nicht leer sind
|
||||
*
|
||||
* @param attributes
|
||||
* @param id
|
||||
* @throws Exception
|
||||
* wenn eines der zu prüfenden Attribute nicht vorhanden oder leer ist
|
||||
*/
|
||||
public void checkAttributesNotEmpty(NamedNodeMap attributes, String[] attributeNames, String elementName) throws Exception {
|
||||
if (attributes == null) {
|
||||
String allAttributeNames = "";
|
||||
for (String attrName : attributeNames) {
|
||||
allAttributeNames = allAttributeNames + "'" + attrName + "',";
|
||||
}
|
||||
throw new Exception("missing attributes " + allAttributeNames + " for element '" + elementName + "'");
|
||||
}
|
||||
|
||||
for (String attrName : attributeNames) {
|
||||
if (attributes.getNamedItem(attrName) == null) {
|
||||
throw new Exception("missing attribute '" + attrName + "' for element '" + elementName + "'");
|
||||
}
|
||||
String value = attributes.getNamedItem(attrName).getNodeValue();
|
||||
if (value == null || value.equals("")) {
|
||||
throw new Exception("attribute '" + attrName + "' for element '" + elementName + "' is null or empty");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Code parseTestSuite(Node testSuiteNode, UploadXmlTestPlanUnit xmlTestPlan, StringBuffer resultText) {
|
||||
Code code = Code.OK;
|
||||
NamedNodeMap attributes = testSuiteNode.getAttributes();
|
||||
// Attribute pruefen
|
||||
try {
|
||||
checkAttributesNotEmpty(attributes, new String[] { XmlConstruct.ID }, TESTSUITE);
|
||||
|
||||
XmlTestSuite xmlTestSuite = new XmlTestSuite(xmlTestPlan);
|
||||
xmlTestSuite.setId(getAttributeValue(attributes, XmlConstruct.ID));
|
||||
xmlTestSuite.setDesc(getAttributeValue(attributes, UploadXmlTestPlanUnit.DESC));
|
||||
NodeList nodes = testSuiteNode.getChildNodes();
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
Node node = nodes.item(i);
|
||||
if (node.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
if (node.getNodeName().equals(TESTCASE)) {
|
||||
parseTestCase(node, xmlTestSuite);
|
||||
} else if (node.getNodeName().equals(VariableParser.VARIABLE)) {
|
||||
parseTestVariable(node, xmlTestSuite);
|
||||
} else if (node.getNodeName().equals(XmlFunctionCall.FUNCTION)) {
|
||||
parseSubroutine(node, xmlTestSuite);
|
||||
} else {
|
||||
LogHandler.log(LOGGER, WARN, node.getNodeName() + " is not expected here. Expected are '" + TESTCASE + ","
|
||||
+ VariableParser.VARIABLE + "," + XmlFunctionCall.FUNCTION + "'");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(LOGGER, ERROR, "", e);
|
||||
resultText.append(e.getMessage()).append('\n');
|
||||
code = Code.PARSE_ERROR;
|
||||
}
|
||||
}
|
||||
xmlTestPlan.add(xmlTestSuite);
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(LOGGER, ERROR, "parse Exception", e);
|
||||
resultText.append(e.getMessage());
|
||||
code = Code.PARSE_ERROR;
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
private void parseTestVariable(Node node, XmlTestSuite xmlTestSuite) throws Exception {
|
||||
// Attribute pruefen
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributesNotEmpty(attributes, new String[] { VariableParser.NAME, VariableParser.VALUE }, VariableParser.VARIABLE);
|
||||
|
||||
String variable = getAttributeValue(attributes, VariableParser.NAME);
|
||||
String value = getAttributeValue(attributes, VariableParser.VALUE);
|
||||
|
||||
if (!VariableEngine.isVariable(variable)) {
|
||||
throw new Exception("attribute 'name' for element 'variable' does not start with '$'\n");
|
||||
}
|
||||
if (VariableEngine.isVariable(value)) {
|
||||
// hier koennen nur statische Variablen abgefragt werden
|
||||
VariableEngine ve = new VariableEngine();
|
||||
value = ve.get(value).toString();
|
||||
}
|
||||
variable = variable.substring(1);
|
||||
xmlTestSuite.getStaticVariables().put(variable, value);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/** a few parsers do not require an id<br>
|
||||
* 1: sql<br>
|
||||
* 2: instance<br>
|
||||
*
|
||||
* @param testCaseNode
|
||||
* @param xmlTestSuite
|
||||
* @throws Exception
|
||||
*/
|
||||
private void parseTestCase(Node testCaseNode, XmlTestSuite xmlTestSuite) throws Exception {
|
||||
NamedNodeMap attributes = testCaseNode.getAttributes();
|
||||
// Attribute pruefen
|
||||
XmlTestCase xmlTestCase = new XmlTestCase(xmlTestSuite);
|
||||
checkAttributesNotEmpty(attributes, new String[] { XmlConstruct.ID }, TESTCASE);
|
||||
String desc = getAttributeValue(attributes, UploadXmlTestPlanUnit.DESC);
|
||||
|
||||
// parsen von funktionen, schleifen, Anweisungen, Zusicherungen
|
||||
xmlTestCase.setId(attributes.getNamedItem(XmlConstruct.ID).getNodeValue());
|
||||
LogHandler.log(LOGGER, TRACE, "start parsing testCase " + xmlTestCase.getId());
|
||||
xmlTestCase.setDesc(desc);
|
||||
NodeList nodes = testCaseNode.getChildNodes();
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
Node node = nodes.item(i);
|
||||
if (node.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
XmlConstruct xmlConstruct = getConstruct(xmlTestCase, node);
|
||||
xmlTestCase.add(xmlConstruct);
|
||||
}
|
||||
xmlTestSuite.add(xmlTestCase);
|
||||
}
|
||||
|
||||
private void parseSubroutine(Node testCaseNode, XmlTestSuite xmlTestSuite) throws Exception {
|
||||
NamedNodeMap attributes = testCaseNode.getAttributes();
|
||||
// Attribute pruefen
|
||||
checkAttributesNotEmpty(attributes, new String[] { XmlConstruct.ID }, XmlFunctionCall.FUNCTION);
|
||||
|
||||
// parsen von funktionen, schleifen, Anweisungen, Zusicherungen
|
||||
String sId = getAttributeValue(attributes, XmlConstruct.ID);
|
||||
XmlFunctionDefinition xmlSubroutine = new XmlFunctionDefinition(sId);
|
||||
LogHandler.log(LOGGER, TRACE, "start parsing function " + sId);
|
||||
|
||||
NodeList nodes = testCaseNode.getChildNodes();
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
Node node = nodes.item(i);
|
||||
if (node.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
XmlConstruct xmlConstruct = getConstruct(null, node);
|
||||
xmlSubroutine.add(xmlConstruct);
|
||||
}
|
||||
xmlTestSuite.addRoutine(sId, xmlSubroutine);
|
||||
}
|
||||
|
||||
private XmlConstruct getConstruct(XmlTestCase testCase, Node node) throws Exception {
|
||||
XmlConstruct xmlConstruct = null;
|
||||
|
||||
String nodeName = node.getNodeName();
|
||||
|
||||
PluginParser pluginParser = (PluginParser) toolbox.getPluginParser(nodeName);
|
||||
|
||||
if (pluginParser != null) {
|
||||
xmlConstruct = pluginParser.parse(node);
|
||||
|
||||
if (!pluginParser.includeSubNodes()) {
|
||||
NodeList nodes = node.getChildNodes();
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
Node subNode = nodes.item(i);
|
||||
if (subNode.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
XmlConstruct xmlSubConstruct = getConstruct(testCase, subNode);
|
||||
if (xmlConstruct == null) {
|
||||
throw new Exception("parse construct failed.....");
|
||||
}
|
||||
xmlConstruct.addChild(xmlSubConstruct);
|
||||
}
|
||||
}
|
||||
} else if (node.getNodeType() == Node.ELEMENT_NODE) {
|
||||
// simple API call...
|
||||
xmlConstruct = functionParser.parse(node);
|
||||
}
|
||||
if (xmlConstruct != null) {
|
||||
xmlConstruct.setTestCase(testCase);
|
||||
|
||||
// Object auswerten
|
||||
StringBuffer evaluateResult = new StringBuffer();
|
||||
try {
|
||||
objectEvaluator.evaluateObject(xmlConstruct.getClass().getSimpleName(), xmlConstruct, evaluateResult);
|
||||
LogHandler.log(LOGGER, TRACE, evaluateResult.toString());
|
||||
} catch (Throwable e) {
|
||||
LogHandler.log(LOGGER, ERROR, "evaluating field failed", e);
|
||||
}
|
||||
}
|
||||
return xmlConstruct;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
/*
|
||||
* Copyright (c) 2010 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied, printed, edited
|
||||
* or otherwise distributed, be stored in a retrieval system, or be translated into another language without the written permission
|
||||
* of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.parser.data;
|
||||
|
||||
import static com.itac.mes.datainterface.parser.data.XmlTestCaseState.FAIL;
|
||||
import static com.itac.mes.datainterface.parser.data.XmlTestCaseState.INIT;
|
||||
import static com.itac.mes.datainterface.parser.data.XmlTestCaseState.PASS;
|
||||
import static com.itac.mes.datainterface.parser.data.XmlTestCaseState.STARTED;
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.w3c.dom.Attr;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import com.itac.mes.datainterface.data.xmlapi.VariableEngine;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlTestCaseDetail;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlTestCase {
|
||||
|
||||
private static final String LOGGER = XmlTestCase.class.getSimpleName();
|
||||
private String id;
|
||||
private List<XmlConstruct> xmlConstructs = new ArrayList<XmlConstruct>();
|
||||
private XmlTestSuite suite;
|
||||
private XmlTestCaseState state = INIT;
|
||||
private long startTime;
|
||||
private long stopTime;
|
||||
private long executedSteps;
|
||||
private long lastRuntime;
|
||||
private VariableEngine variableEngine = new VariableEngine();
|
||||
private HashSet<String> idSet = new HashSet<String>();
|
||||
private Element testCaseNode;
|
||||
private Element stats;
|
||||
/**
|
||||
* Anzahl der ausgefuehrten API-Calls im testCase
|
||||
*/
|
||||
private int apiCalls;
|
||||
private long apiCallTime;
|
||||
private long minApiCall;
|
||||
private long maxApiCall;
|
||||
private String description;
|
||||
private String detailText;
|
||||
|
||||
public XmlTestCase(XmlTestSuite suite) {
|
||||
super();
|
||||
this.suite = suite;
|
||||
variableEngine.putAll(suite.getStaticVariables());
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
idSet.add(id);
|
||||
}
|
||||
|
||||
public void add(XmlConstruct xmlConstruct) throws Exception {
|
||||
if (xmlConstruct instanceof XmlTestCaseDetail) {
|
||||
this.setDetailText(((XmlTestCaseDetail) xmlConstruct).getDetailText());
|
||||
return;
|
||||
}
|
||||
testId(xmlConstruct);
|
||||
idSet.add(xmlConstruct.getId());
|
||||
xmlConstructs.add(xmlConstruct);
|
||||
}
|
||||
|
||||
private void setDetailText(String detailText) {
|
||||
this.detailText = detailText;
|
||||
}
|
||||
|
||||
private void testId(XmlConstruct xmlConstruct) throws Exception {
|
||||
if (!xmlConstruct.getId().equals("") && idSet.contains(xmlConstruct.getId())) {
|
||||
throw new Exception("construct with id '" + xmlConstruct.getId() + "' is already used in TestCase id '" + id + "'");
|
||||
}
|
||||
if (xmlConstruct.getChilds() != null) {
|
||||
for (XmlConstruct child : xmlConstruct.getChilds()) {
|
||||
testId(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
if (state == XmlTestCaseState.INIT) {
|
||||
return "TestCase id=" + id + ", " + xmlConstructs.size() + " top Level teststeps";
|
||||
}
|
||||
return "TestCase id=" + id + ", " + xmlConstructs.size() + " top Level teststeps, " + executedSteps + " steps executed";
|
||||
}
|
||||
|
||||
public List<XmlConstruct> getXmlConstructs() {
|
||||
return xmlConstructs;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void start() {
|
||||
if (state == INIT) {
|
||||
state = STARTED;
|
||||
startTime = System.currentTimeMillis();
|
||||
LogHandler.log(LOGGER, INFO, "start " + toString());
|
||||
|
||||
testCaseNode = getDocument().createElement("testCase");
|
||||
suite.getTestSuiteNode().appendChild(testCaseNode);
|
||||
|
||||
stats = getDocument().createElement("stats");
|
||||
testCaseNode.appendChild(stats);
|
||||
|
||||
addAttribute(testCaseNode, "id", getId());
|
||||
addAttribute(testCaseNode, "desc", getDesc());
|
||||
addAttribute(stats, "started", new Date().toString());
|
||||
|
||||
return;
|
||||
}
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
private String getDesc() {
|
||||
return description;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public void stop() {
|
||||
stopTime = System.currentTimeMillis();
|
||||
if (state != PASS && state != FAIL) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
LogHandler.log(LOGGER, INFO, toString() + " finished successful in " + getTestCaseMillies() + " millies");
|
||||
|
||||
addAttribute(stats, "executionTime", String.valueOf(getTestCaseMillies()));
|
||||
addAttribute(stats, "state", getState().toString());
|
||||
addAttribute(stats, "ended", new Date().toString());
|
||||
|
||||
addAttribute(stats, "apiCalls", String.valueOf(apiCalls));
|
||||
if (apiCalls > 0) {
|
||||
addAttribute(stats, "minCallTime", String.valueOf(minApiCall));
|
||||
addAttribute(stats, "maxCallTime", String.valueOf(maxApiCall));
|
||||
addAttribute(stats, "avgCallTime", String.valueOf(Math.round(apiCallTime / apiCalls)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Aenderung der Zustandsmaschine von STARTED auf PASS
|
||||
*/
|
||||
public void setPass() {
|
||||
if (state == INIT) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
executedSteps++;
|
||||
if (state == FAIL) {
|
||||
return;
|
||||
}
|
||||
state = PASS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aenderung der Zustandsmaschine von STARTED oder PASS
|
||||
*/
|
||||
public void setFail() {
|
||||
if (state == INIT) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
if (state != FAIL) {
|
||||
executedSteps++;
|
||||
}
|
||||
state = FAIL;
|
||||
LogHandler.log(LOGGER, INFO, toString() + " failed after " + getTestCaseMillies() + " millies");
|
||||
}
|
||||
|
||||
/**
|
||||
* Aenderung der Zustandsmaschine von STARTED oder PASS
|
||||
*/
|
||||
public void setException() {
|
||||
if (state == INIT) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
if (state != FAIL) {
|
||||
executedSteps++;
|
||||
}
|
||||
state = XmlTestCaseState.EXCEPTION;
|
||||
LogHandler.log(LOGGER, INFO, toString() + " failed with exception after " + getTestCaseMillies() + " millies");
|
||||
}
|
||||
|
||||
public XmlTestCaseState getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public XmlTestSuite getSuite() {
|
||||
return suite;
|
||||
}
|
||||
|
||||
/**
|
||||
* berechnet die Laufzeit eines einzelnen Constructs nach der Ausfuehrung; wurde ein Testschritt nicht ausgefuehrt, weil ein
|
||||
* voriger Testschritt fehlerhaft beendet wurde ist die Zeit 0
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public long getTestCaseMillies() {
|
||||
if (startTime == 0L && stopTime == 0L) {
|
||||
return 0L;
|
||||
}
|
||||
return stopTime - startTime;
|
||||
}
|
||||
|
||||
public void setLastRuntime(long testMillies) {
|
||||
lastRuntime = testMillies;
|
||||
}
|
||||
|
||||
public void setLastApiCallRuntime(long testMillies) {
|
||||
apiCalls++;
|
||||
apiCallTime += testMillies;
|
||||
if (minApiCall == 0 || testMillies < minApiCall) {
|
||||
minApiCall = testMillies;
|
||||
}
|
||||
|
||||
if (maxApiCall == 0 || testMillies > maxApiCall) {
|
||||
maxApiCall = testMillies;
|
||||
}
|
||||
}
|
||||
|
||||
public long getLastRuntime() {
|
||||
return lastRuntime;
|
||||
}
|
||||
|
||||
public Set<String> getIdSet() {
|
||||
return idSet;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public VariableEngine getVariableEngine() {
|
||||
return variableEngine;
|
||||
}
|
||||
|
||||
public Document getDocument() {
|
||||
return suite.getDocument();
|
||||
}
|
||||
|
||||
public Element getTestCaseNode() {
|
||||
return testCaseNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* erzeugen eines neuen Attributes und anhaengen des Attributs an das Element
|
||||
*
|
||||
* @param superElement
|
||||
* @param attributeKey
|
||||
* @param attributeValue
|
||||
*/
|
||||
private void addAttribute(Element superElement, String attributeKey, String attributeValue) {
|
||||
Attr attr = getDocument().createAttribute(attributeKey);
|
||||
attr.setNodeValue(attributeValue);
|
||||
superElement.setAttributeNode(attr);
|
||||
}
|
||||
|
||||
public void setDesc(String desc) {
|
||||
description = desc;
|
||||
}
|
||||
|
||||
public String getDetailText() {
|
||||
if (detailText == null) {
|
||||
return "";
|
||||
}
|
||||
return detailText;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.itac.mes.datainterface.parser.data;
|
||||
|
||||
/**
|
||||
* Hier sind alle Zustaende des XmlTestCase hinterlegt, die die Statusmaschine eines TestCase annehemen kann. Die
|
||||
* Zustandsuebergaenge selbst wird ducrch die Ausfuehrung der einzelnen Testschritte vorgeommen.
|
||||
*
|
||||
* @author frankp <br>
|
||||
*/
|
||||
public enum XmlTestCaseState {
|
||||
INIT, STARTED,
|
||||
PASS, // Verarbeitung des Testschritts OK
|
||||
FAIL, // Verarbeitung des Testschritts nicht OK
|
||||
EXCEPTION // wenn die Verarbeitung nicht weiter ausgeführt werden kann, z.B. LookupException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package com.itac.mes.datainterface.parser.data;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
import static com.itac.util.logging.LogLevel.TRACE;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Hashtable;
|
||||
|
||||
import org.w3c.dom.Attr;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.UploadXmlTestPlanUnit;
|
||||
import com.itac.mes.datainterface.data.xmlapi.TestcaseException;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlTestSuite {
|
||||
|
||||
private static final String LOGGER = XmlTestSuite.class.getSimpleName();
|
||||
|
||||
private String id;
|
||||
private ArrayList<XmlTestCase> xmlTestCases = new ArrayList<XmlTestCase>();
|
||||
protected long startTime = 0L;
|
||||
protected long stopTime = 0L;
|
||||
|
||||
protected HashSet<String> idSet = new HashSet<String>();
|
||||
private UploadXmlTestPlanUnit testPlan;
|
||||
private Element testSuiteNode;
|
||||
private Element stats;
|
||||
private String description = "";
|
||||
private Hashtable<String, String> staticVariables = new Hashtable<String, String>();
|
||||
private Hashtable<String, XmlConstruct> subroutines = new Hashtable<String, XmlConstruct>();
|
||||
|
||||
public XmlTestSuite(UploadXmlTestPlanUnit xmlTestPlan) {
|
||||
super();
|
||||
testPlan = xmlTestPlan;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void add(XmlTestCase xmlTestCase) throws Exception {
|
||||
if (!xmlTestCase.getId().equals("") && idSet.contains(xmlTestCase.getId())) {
|
||||
throw new Exception("testcase already contains id(" + xmlTestCase.getId() + ")");
|
||||
}
|
||||
idSet.add(xmlTestCase.getId());
|
||||
xmlTestCases.add(xmlTestCase);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "TestSuite id=" + id + ", " + xmlTestCases.size() + " testcases";
|
||||
}
|
||||
|
||||
public ArrayList<XmlTestCase> getTestCases() {
|
||||
return xmlTestCases;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
startTime = System.currentTimeMillis();
|
||||
LogHandler.log(LOGGER, INFO, "starte testSuite " + toString());
|
||||
|
||||
Node rootNode = getDocument().getDocumentElement();
|
||||
testSuiteNode = getDocument().createElement("testSuite");
|
||||
|
||||
stats = getDocument().createElement("stats");
|
||||
testSuiteNode.appendChild(stats);
|
||||
|
||||
addAttribute(stats, "started", new Date().toString());
|
||||
addAttribute(testSuiteNode, "id", getId());
|
||||
addAttribute(testSuiteNode, "desc", getDesc());
|
||||
rootNode.appendChild(testSuiteNode);
|
||||
}
|
||||
|
||||
private String getDesc() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
stopTime = System.currentTimeMillis();
|
||||
LogHandler.log(LOGGER, INFO, this.toString() + " run in " + getSuiteMillies() + " millies");
|
||||
|
||||
addAttribute(stats, "ended", new Date().toString());
|
||||
addAttribute(stats, "executionTime", String.valueOf(getSuiteMillies()));
|
||||
addAttribute(stats, "suiteResult", getState().toString());
|
||||
|
||||
int casesPassed = 0;
|
||||
int casesFailed = 0;
|
||||
|
||||
for (XmlTestCase testCase : xmlTestCases) {
|
||||
if (testCase.getState() == XmlTestCaseState.PASS) {
|
||||
casesPassed++;
|
||||
} else {
|
||||
casesFailed++;
|
||||
}
|
||||
}
|
||||
addAttribute(stats, "testCases", String.valueOf(casesPassed + casesFailed));
|
||||
addAttribute(stats, "testCasePassed", String.valueOf(casesPassed));
|
||||
addAttribute(stats, "testCaseFailed", String.valueOf(casesFailed));
|
||||
}
|
||||
|
||||
/**
|
||||
* berechnet die Laufzeit eines einzelnen Constructs nach der Ausfuehrung; wurde ein Testscritt nicht ausgefuehrt,
|
||||
* weil ein voriger Testschritt fehlerhaft beendet wurde ist die Zeit 0
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public long getSuiteMillies() {
|
||||
if (startTime == 0L && stopTime == 0L) {
|
||||
return 0L;
|
||||
}
|
||||
return stopTime - startTime;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Document getDocument() {
|
||||
return testPlan.getDocument();
|
||||
}
|
||||
|
||||
public UploadXmlTestPlanUnit getTestPlan() {
|
||||
return testPlan;
|
||||
}
|
||||
|
||||
public Element getTestSuiteNode() {
|
||||
return testSuiteNode;
|
||||
}
|
||||
|
||||
public XmlTestCaseState getState() {
|
||||
|
||||
XmlTestCaseState state = XmlTestCaseState.PASS;
|
||||
|
||||
for (XmlTestCase testCase : xmlTestCases) {
|
||||
if (testCase.getState() != XmlTestCaseState.PASS) {
|
||||
state = XmlTestCaseState.FAIL;
|
||||
}
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* erzeugen eines neuen Attributes und anhaengen des Attributs an das Element
|
||||
*
|
||||
* @param superElement
|
||||
* @param attributeKey
|
||||
* @param attributeValue
|
||||
*/
|
||||
private void addAttribute(Element superElement, String attributeKey, String attributeValue) {
|
||||
Attr attr = getDocument().createAttribute(attributeKey);
|
||||
attr.setNodeValue(attributeValue);
|
||||
superElement.setAttributeNode(attr);
|
||||
}
|
||||
|
||||
public void setDesc(String desc) {
|
||||
description = desc;
|
||||
}
|
||||
|
||||
public Hashtable<String, String> getStaticVariables() {
|
||||
return staticVariables;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param xmlTestCase
|
||||
*/
|
||||
public void addRoutine(String functionName, XmlConstruct xmlSubroutine) {
|
||||
if (!subroutines.containsKey(functionName)) {
|
||||
LogHandler.log(LOGGER, TRACE, "add function '" + functionName + "' to TestSuite '" + getId() + "'");
|
||||
} else {
|
||||
LogHandler.log(LOGGER, TRACE, "replace function '" + functionName + "' for TestSuite '" + getId() + "'");
|
||||
}
|
||||
subroutines.put(functionName, xmlSubroutine);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param functionName
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public XmlConstruct getFunction(String functionName) throws TestcaseException {
|
||||
if (!subroutines.containsKey(functionName)) {
|
||||
throw new TestcaseException("TestSuite '" + getId() + "' does not contain function '" + functionName + "'");
|
||||
}
|
||||
return subroutines.get(functionName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlAssertJs;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.datasource.BasicDataSource;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class AssertionJsParser extends PluginParser {
|
||||
|
||||
public static final String ASSERT = "assertJs";
|
||||
private static final String TEST = "test";
|
||||
private static final String INSTANCE = "instance";
|
||||
|
||||
public AssertionJsParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlAssertJs parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
|
||||
checkAttributesNotEmpty(attributes, new String[] { TEST }, getName());
|
||||
String id = getAttributeValue(attributes, XmlConstruct.ID);
|
||||
if (attributes.getNamedItem(XmlConstruct.ID) != null) {
|
||||
checkAttributesNotEmpty(attributes, new String[] { XmlConstruct.ID }, getName());
|
||||
}
|
||||
String sTest = getAttributeValue(attributes, TEST);
|
||||
|
||||
if (attributes.getNamedItem(INSTANCE) != null) {
|
||||
checkAttributesNotEmpty(attributes, new String[] { INSTANCE }, getName());
|
||||
}
|
||||
|
||||
// optional attribute "instance"
|
||||
String instanceName = getAttributeValue(attributes, INSTANCE);
|
||||
XmlAssertJs xmlAssertJs = new XmlAssertJs(id);
|
||||
// Im Text steht das JS Script
|
||||
xmlAssertJs.setTest(sTest);
|
||||
xmlAssertJs.setScriptText(node.getTextContent());
|
||||
if (instanceName != null) {
|
||||
BasicDataSource instance = getToolBox().getWorkerInstance(instanceName);
|
||||
if (instance == null) {
|
||||
throw new Exception("unknown instance '" + instanceName + "', available instances are: "
|
||||
+ getToolBox().getWorkerInstanceNames().toString());
|
||||
}
|
||||
|
||||
xmlAssertJs.setInstance(instance);
|
||||
}
|
||||
|
||||
return xmlAssertJs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.VariableEngine;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlAssertion;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlCondition;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class AssertionParser extends PluginParser {
|
||||
|
||||
public static final String ASSERT = "assert";
|
||||
public static final String CONDITION = "condition";
|
||||
private static final String EXPECTED = "expected";
|
||||
private static final String TEST = "test";
|
||||
|
||||
public AssertionParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlAssertion parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributesNotEmpty(attributes, new String[] { CONDITION, TEST }, getName());
|
||||
String id = getAttributeValue(attributes, XmlConstruct.ID);
|
||||
if (attributes.getNamedItem(XmlConstruct.ID) != null) {
|
||||
checkAttributesNotEmpty(attributes, new String[] { XmlConstruct.ID }, getName());
|
||||
}
|
||||
|
||||
XmlCondition condition = XmlCondition.EQUAL;
|
||||
String sCondition = getAttributeValue(attributes, CONDITION);
|
||||
if (!sCondition.equals("")) {
|
||||
condition = XmlCondition.get(sCondition);
|
||||
if (condition == null) {
|
||||
throw new Exception("Assertion construct wrong:\n 'condition' (" + sCondition
|
||||
+ ") is an invalid value; allowed conditions are '" + XmlCondition.getAllConditions() + "'\n");
|
||||
}
|
||||
}
|
||||
String sTest = getAttributeValue(attributes, TEST);
|
||||
if (condition != XmlCondition.EXISTS && condition != XmlCondition.NOTEXISTS) {
|
||||
checkAttributes(attributes, new String[] { EXPECTED }, getName());
|
||||
} else {
|
||||
// attribute 'test' is not a variable for element 'assert'
|
||||
if (!VariableEngine.isVariable(sTest)) {
|
||||
throw new Exception("attribute '" + TEST + "' is not a variable for element '" + getName() + "'");
|
||||
}
|
||||
}
|
||||
XmlAssertion xmlAssertion = new XmlAssertion(id);
|
||||
xmlAssertion.setTest(sTest);
|
||||
xmlAssertion.setExpected(getAttributeValue(attributes, EXPECTED));
|
||||
xmlAssertion.setCondition(condition);
|
||||
if (xmlAssertion.getTest().equals("$RUNTIME")) {
|
||||
try {
|
||||
Long.parseLong(xmlAssertion.getExpected());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new Exception("integer values allowed only for expected when test-variable is $RUNTIME");
|
||||
}
|
||||
}
|
||||
return xmlAssertion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlDatabase;
|
||||
import com.itac.mes.datainterface.gui.IMachineSimulation;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class DatabaseXmlParser extends PluginParser {
|
||||
|
||||
public DatabaseXmlParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlConstruct parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributes(attributes, new String[] { XmlConstruct.ID }, "");
|
||||
|
||||
if (attributes.getNamedItem("simulation") == null) {
|
||||
throw new Exception("database construct wrong; missing attribute 'simulation'\n");
|
||||
}
|
||||
|
||||
String id = getAttributeValue(attributes, XmlConstruct.ID);
|
||||
|
||||
// Referenz auf die DatabaseSimulation ermitteln; also auf die komponente, die SQL zu der entsprechenden Connection
|
||||
// ausfuehren kann
|
||||
String simulation = "";
|
||||
if (attributes.getNamedItem("simulation") != null) {
|
||||
simulation = attributes.getNamedItem("simulation").getNodeValue();
|
||||
}
|
||||
IMachineSimulation machine = getToolBox().getSimulation(simulation);
|
||||
if (machine == null) {
|
||||
throw new Exception("database construct wrong; the requested simulation '" + simulation + "' is not known!\n");
|
||||
}
|
||||
|
||||
// das ausfuehrbare Statement vorbereiten
|
||||
XmlDatabase xmlDatabase = new XmlDatabase(id);
|
||||
xmlDatabase.setSimulation(machine);
|
||||
|
||||
// die Anweisungen holen
|
||||
// select, insert, delete oder update , commit
|
||||
if (attributes.getNamedItem("select") != null) {
|
||||
xmlDatabase.setSelect(attributes.getNamedItem("select").getNodeValue());
|
||||
} else if (attributes.getNamedItem("insert") != null) {
|
||||
xmlDatabase.setInsert(attributes.getNamedItem("insert").getNodeValue());
|
||||
} else if (attributes.getNamedItem("update") != null) {
|
||||
xmlDatabase.setUpdate(attributes.getNamedItem("update").getNodeValue());
|
||||
} else if (attributes.getNamedItem("delete") != null) {
|
||||
xmlDatabase.setDelete(attributes.getNamedItem("delete").getNodeValue());
|
||||
} else if (attributes.getNamedItem("commit") != null) {
|
||||
xmlDatabase.commit();
|
||||
}
|
||||
|
||||
return xmlDatabase;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlDump;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class DumpParser extends PluginParser {
|
||||
|
||||
|
||||
public DumpParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlConstruct parse(Node node) {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
String id = getAttributeValue(attributes, XmlConstruct.ID);
|
||||
|
||||
String sStructure = getAttributeValue(attributes, "structure");
|
||||
boolean withStructure = Boolean.parseBoolean(sStructure);
|
||||
|
||||
XmlDump xmlDump = new XmlDump(id);
|
||||
xmlDump.setStructuredOutput(withStructure);
|
||||
return xmlDump;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlFor;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class ForParser extends PluginParser {
|
||||
|
||||
private static final String END = "end";
|
||||
private static final String START = "start";
|
||||
|
||||
public ForParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlFor parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributesNotEmpty(attributes, new String[] { VariableParser.VARIABLE, START, END }, "for");
|
||||
String id = getAttributeValue(attributes, XmlConstruct.ID);
|
||||
|
||||
XmlFor xmlFor = new XmlFor(id);
|
||||
xmlFor.setVariable(getAttributeValue(attributes, VariableParser.VARIABLE));
|
||||
try {
|
||||
xmlFor.setStart(getAttributeValue(attributes, START));
|
||||
} catch (NumberFormatException nfe) {
|
||||
throw new Exception("start value is not numeric\n");
|
||||
}
|
||||
try {
|
||||
xmlFor.setEnd(getAttributeValue(attributes, END));
|
||||
} catch (NumberFormatException nfe) {
|
||||
throw new Exception("end value is not numeric\n");
|
||||
}
|
||||
return xmlFor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlFunctionCall;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class FunctionCallParser extends PluginParser {
|
||||
|
||||
public FunctionCallParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlConstruct parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributesNotEmpty(attributes, new String[] { XmlConstruct.ID, XmlFunctionCall.FUNCTION }, "call");
|
||||
// Assert: es gibt die Attribute ID und Function, und die sind nicht leer...
|
||||
|
||||
XmlFunctionCall xmlCall = new XmlFunctionCall(attributes.getNamedItem(XmlConstruct.ID).getNodeValue());
|
||||
xmlCall.setFunctionName(attributes.getNamedItem(XmlFunctionCall.FUNCTION).getNodeValue());
|
||||
|
||||
return xmlCall;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
/*
|
||||
* Copyright (c) 2015 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
import static com.itac.util.logging.LogLevel.TRACE;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashSet;
|
||||
import java.util.Hashtable;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import com.itac.mes.api.domain.EWApiServices;
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlApiFunction;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
import com.itac.mes.imsapi.domain.IMSApiService;
|
||||
import com.itac.mes.imsapi.domain.container.IMSApiSessionContextStruct;
|
||||
import com.itac.util.annotation.ItacMethodDescriptor;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class FunctionParser extends PluginParser {
|
||||
public static final String LOGGER = FunctionParser.class.getSimpleName();
|
||||
|
||||
private final Hashtable<String, Method> apiMethods = new Hashtable<String, Method>();
|
||||
private final Hashtable<String, Method> imsApiMethods = new Hashtable<String, Method>();
|
||||
// aus welchem Service soll die Funktion aufgerufen werden EWAPi oder IMSAPI
|
||||
// der Wert des Attributes "target" bestimmt das;
|
||||
private int apiFunctionMode = EWAPI_FIRST;
|
||||
public static final int EWAPI_FIRST = 0;
|
||||
public static final int EWAPI_ONLY = 1;
|
||||
public static final int IMSAPI_ONLY = 2;
|
||||
|
||||
public FunctionParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
Method[] apiMethodArray = EWApiServices.class.getMethods();
|
||||
for (Method method : apiMethodArray) {
|
||||
apiMethods.put(method.getName(), method);
|
||||
}
|
||||
|
||||
Method[] imsApiMethodArray = IMSApiService.class.getMethods();
|
||||
for (Method method : imsApiMethodArray) {
|
||||
imsApiMethods.put(method.getName(), method);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlApiFunction parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
|
||||
checkAttributesNotEmpty(attributes, new String[] { XmlConstruct.ID, XmlApiFunction.TARGET }, node.getNodeName());
|
||||
String id = attributes.getNamedItem(XmlConstruct.ID).getNodeValue();
|
||||
|
||||
String target = getAttributeValue(attributes, XmlApiFunction.TARGET);
|
||||
if (target.equalsIgnoreCase(XmlApiFunction.IMSAPI)) {
|
||||
apiFunctionMode = IMSAPI_ONLY;
|
||||
} else if (target.equalsIgnoreCase(XmlApiFunction.EWAPI)) {
|
||||
apiFunctionMode = EWAPI_ONLY;
|
||||
}
|
||||
|
||||
XmlApiFunction xmlApiFunction = new XmlApiFunction(id);
|
||||
String methodName = node.getNodeName();
|
||||
LogHandler.log(LOGGER, TRACE, "parse function id(" + id + "): method " + methodName);
|
||||
|
||||
// pruefen, dass diese Methode auch wirklich existiert
|
||||
int apiMode = XmlApiFunction.EWAPI_FUNCTION;
|
||||
Method m = null;
|
||||
if (apiFunctionMode == EWAPI_ONLY || apiFunctionMode == EWAPI_FIRST) {
|
||||
m = apiMethods.get(methodName);
|
||||
if (m == null) {
|
||||
if (apiFunctionMode == EWAPI_FIRST) {
|
||||
m = imsApiMethods.get(methodName);
|
||||
apiMode = XmlApiFunction.IMSAPI_FUNCTION;
|
||||
}
|
||||
}
|
||||
xmlApiFunction.setFunctionName(methodName);
|
||||
} else if (apiFunctionMode == IMSAPI_ONLY) {
|
||||
m = imsApiMethods.get(methodName);
|
||||
apiMode = XmlApiFunction.IMSAPI_FUNCTION;
|
||||
xmlApiFunction.setFunctionName(methodName);
|
||||
}
|
||||
xmlApiFunction.apiSource = apiMode;
|
||||
if (m == null) {
|
||||
throw new Exception("function id(" + id + "): method " + methodName + " not found in API; check spelling, camelCase...\n");
|
||||
}
|
||||
xmlApiFunction.setMethod(m);
|
||||
|
||||
if (apiMode == XmlApiFunction.IMSAPI_FUNCTION) {
|
||||
return parseImsApiFunction(xmlApiFunction, node);
|
||||
} else {
|
||||
return parseEwApiFunction(xmlApiFunction, node);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* IMS-Api Funktionen testen
|
||||
*
|
||||
* @param xmlApiFunction
|
||||
* @param node
|
||||
* @param resultText
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public XmlApiFunction parseImsApiFunction(XmlApiFunction xmlApiFunction, Node node) throws Exception {
|
||||
LogHandler.log(LOGGER, TRACE, "parameter zur Methode " + xmlApiFunction.getMethod().getName());
|
||||
// Die Parameternamen werden ueber Annotations gelesen
|
||||
ItacMethodDescriptor methodDescriptor = xmlApiFunction.getMethod().getAnnotation(ItacMethodDescriptor.class);
|
||||
if (methodDescriptor == null) {
|
||||
throw new Exception("method " + xmlApiFunction.getFunctionName()
|
||||
+ " is not annotated with \"@ItacMethodDescriptor\", method has no parameters...\n");
|
||||
}
|
||||
|
||||
StringBuffer thisFunction = new StringBuffer();
|
||||
|
||||
Class<?>[] paramTypes = xmlApiFunction.getMethod().getParameterTypes();
|
||||
String[] argNames = methodDescriptor.argNames();
|
||||
xmlApiFunction.setParameterNames(argNames);
|
||||
xmlApiFunction.setParameterTypes(paramTypes);
|
||||
|
||||
// alle Parameter sind required
|
||||
HashSet<String> requiredParams = new HashSet<String>();
|
||||
for (int i = 0; i < argNames.length; i++) {
|
||||
LogHandler.log(LOGGER, TRACE, "required parameter " + i + ": " + argNames[i] + ", type :" + paramTypes[i].getSimpleName());
|
||||
requiredParams.add(argNames[i]);
|
||||
}
|
||||
// bei imsApiFunctions immer den SessionContext automatisch betrachten
|
||||
requiredParams.remove("sessionContext");
|
||||
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
IMSApiSessionContextStruct imssession = new IMSApiSessionContextStruct();
|
||||
|
||||
xmlApiFunction.add(new XmlParameter("sessionContext", imssession.toString()));
|
||||
|
||||
if (attributes != null) {
|
||||
// es gibt attribute, diese jetzt checken und hinzufuegen
|
||||
for (int i = 0; i < attributes.getLength(); i++) {
|
||||
XmlParameter xmlParameter = new XmlParameter(attributes.item(i).getNodeName(), attributes.item(i).getNodeValue());
|
||||
LogHandler.log(LOGGER, TRACE, "parsed Parameter " + xmlParameter.toString());
|
||||
xmlApiFunction.add(xmlParameter);
|
||||
requiredParams.remove(attributes.item(i).getNodeName());
|
||||
}
|
||||
}
|
||||
|
||||
// Unterknoten auswerten, und die einzelnen Knoten zu den Parametern hinzufügen
|
||||
// jetzt gibt es zwei Moeglichkeiten:
|
||||
// 1. Parameter anhand des Parameternamens ermitteln
|
||||
// 2. Parameter anhand der Typen ermitteln
|
||||
|
||||
NodeList subElements = node.getChildNodes();
|
||||
for (int i = 0; i < subElements.getLength(); i++) {
|
||||
Node subNode = subElements.item(i);
|
||||
if (subNode.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
LogHandler.log(LOGGER, TRACE, "node : " + subNode.getNodeName());
|
||||
|
||||
//
|
||||
if (requiredParams.contains(subNode.getNodeName())) {
|
||||
// unterhalb dieses Knotens liegen jetzt die Strukturen
|
||||
if (parseNamedElements(subNode, xmlApiFunction, thisFunction)) {
|
||||
requiredParams.remove(subNode.getNodeName());
|
||||
}
|
||||
} else {
|
||||
thisFunction.append(subNode.getNodeName()).append(" is not part of the required params!");
|
||||
// das kann jetzt noch ein Typ sein
|
||||
}
|
||||
}
|
||||
|
||||
if (requiredParams.size() > 0) {
|
||||
for (String reqParam : requiredParams) {
|
||||
thisFunction.append("missing parameter " + reqParam + " for function " + xmlApiFunction.getMethod() + "\n");
|
||||
}
|
||||
throw new Exception(thisFunction.toString());
|
||||
}
|
||||
return xmlApiFunction;
|
||||
}
|
||||
|
||||
// ein einzelnes benamtes Element lesen;
|
||||
// es koennen verschiedene Datentypen auftauchen, primaer für strukturierte Typen und Arrays
|
||||
// strukur des Nodes:
|
||||
// <paramName>
|
||||
// <ElementType value=""/>
|
||||
// </paramName>
|
||||
private boolean parseNamedElements(Node node, XmlApiFunction xmlApiFunction, StringBuffer resultText) {
|
||||
LogHandler.log(LOGGER, TRACE, "parseNamedElement " + node.getNodeName());
|
||||
boolean result = true;
|
||||
NodeList nodelist = node.getChildNodes();
|
||||
try {
|
||||
Class<?> componentClass = xmlApiFunction.getClassForParameter(node.getNodeName());
|
||||
Class<?> clazz = xmlApiFunction.getClassForParameter(node.getNodeName());
|
||||
if (clazz.isArray()) {
|
||||
// Bei einem Array interessiert die Klasse der einzelnen Komponenten
|
||||
componentClass = clazz.getComponentType();
|
||||
LogHandler.log(LOGGER, TRACE, "start parseNamedElements with component class " + componentClass.toString());
|
||||
// arrayInstanz erstellen, die entsprechende Groesse feststellen, nur Elementknoten benutzen
|
||||
int arraySize = 0;
|
||||
for (int i = 0; i < nodelist.getLength(); i++) {
|
||||
Node subNode = nodelist.item(i);
|
||||
if (subNode.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
arraySize++;
|
||||
}
|
||||
LogHandler.log(LOGGER, TRACE, "arraysize = " + arraySize);
|
||||
// Jeder Elementknoten ist ein einzelnes Array-Element
|
||||
for (int i = 0; i < nodelist.getLength(); i++) {
|
||||
Node subNode = nodelist.item(i);
|
||||
if (subNode.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
NamedNodeMap attributes = subNode.getAttributes();
|
||||
// Besonderbehandlung bei StringArray, jedes Element erwartet ein Attribut value
|
||||
if (componentClass == String.class) {
|
||||
if (attributes == null || attributes.getLength() == 0) {
|
||||
// alternativ über den nodeValue...
|
||||
String text = subNode.getTextContent();
|
||||
if (text != null) {
|
||||
LogHandler.log(LOGGER, TRACE, "direct text content");
|
||||
} else {
|
||||
throw new Exception("no attributes found");
|
||||
}
|
||||
} else if (attributes.getNamedItem("value") == null) {
|
||||
throw new Exception("no attribut 'value' found, attribute is required for type String[]");
|
||||
}
|
||||
// Es gibt ein Attribut value, in dem der Wert für dieses String-Array-Element steht,
|
||||
// oder der Wert ist direkt als Text enthalten
|
||||
} else {
|
||||
// Instanz erzeugen (ein einzelnes array-Element
|
||||
Constructor<?> constructor = componentClass.getConstructor();
|
||||
constructor.newInstance();
|
||||
// Felder anhand von Attributen pruefen,
|
||||
// 1. pruefen dass es keine Attribute gibt, zu denen es keine Felder gibt
|
||||
// 2. pruefen, dass alle Felder der Instanz gefuellt werden koennen
|
||||
boolean valid = checkInstanceComplete(node.getNodeName(), componentClass, attributes, resultText);
|
||||
if (!valid) {
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
LogHandler.log(LOGGER, INFO, "set element for array");
|
||||
}
|
||||
// den Knoten hinzufügen; damit kann beim ausführen alles gemacht werden...
|
||||
xmlApiFunction.addStructuredParameter(node.getNodeName(), node);
|
||||
LogHandler.log(LOGGER, INFO, "finish array");
|
||||
} else {
|
||||
// Kein Array, aber struktrierte daten
|
||||
for (int i = 0; i < nodelist.getLength(); i++) {
|
||||
Node subNode = nodelist.item(i);
|
||||
if (subNode.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
NamedNodeMap attributes = subNode.getAttributes();
|
||||
// Instanz erzeugen
|
||||
Constructor<?> constructor = componentClass.getConstructor();
|
||||
constructor.newInstance();
|
||||
// Felder anhand von Attributen pruefen,
|
||||
// 1. pruefen dass es keine Attribute gibt, zu denen es keine Felder gibt
|
||||
// 2. pruefen, dass alle Felder der Instanz gefuellt werden koennen
|
||||
if (checkInstanceComplete(node.getNodeName(), componentClass, attributes, resultText)) {
|
||||
xmlApiFunction.addStructuredParameter(node.getNodeName(), node);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
LogHandler.log(LOGGER, ERROR, null, ex);
|
||||
resultText.append(ex.getMessage());
|
||||
result = false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* enthält die angegebene attributeMap ein Attribut für jedes Feld der angegebenen Klasse
|
||||
*
|
||||
* @param parameterName
|
||||
* @param clazz
|
||||
* @param attributes
|
||||
* @param resultText
|
||||
* @return
|
||||
*/
|
||||
private boolean checkInstanceComplete(String parameterName, Class<?> clazz, NamedNodeMap attributes, StringBuffer resultText) {
|
||||
// Vollständigkeit des Arrays prüfen
|
||||
// ueber alle Felder iteriern und die nicht gesetzten Felder ausgeben
|
||||
Field[] fields = clazz.getDeclaredFields();
|
||||
HashSet<String> fieldNames = new HashSet<String>();
|
||||
|
||||
for (Field field : fields) {
|
||||
if (field.getName().startsWith("$jacoco")) {
|
||||
continue;
|
||||
}
|
||||
fieldNames.add(field.getName());
|
||||
|
||||
}
|
||||
for (int i = 0; i < attributes.getLength(); i++) {
|
||||
if (!fieldNames.contains(attributes.item(i).getNodeName())) {
|
||||
resultText.append("class ").append(clazz.getName()).append(" does not contain field ")
|
||||
.append(attributes.item(i).getNodeName()).append("\n");
|
||||
|
||||
continue;
|
||||
|
||||
}
|
||||
fieldNames.remove(attributes.item(i).getNodeName());
|
||||
|
||||
}
|
||||
boolean result = true;
|
||||
|
||||
for (String fieldName : fieldNames) {
|
||||
// die verbleibenden Felder sind nicht im XML.Source enthalten
|
||||
resultText.append("field ").append(fieldName).append(" not set for parameter ").append(parameterName).append("\n");
|
||||
result = false;
|
||||
|
||||
}
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
private XmlApiFunction parseEwApiFunction(XmlApiFunction xmlApiFunction, Node node) throws Exception {
|
||||
|
||||
// Die Parameternamen werden jetzt ueber Annotations ausgelesen
|
||||
// @ItacMethodDescriptor(argNames={"sessValData"})
|
||||
ItacMethodDescriptor methodDescriptor = xmlApiFunction.getMethod().getAnnotation(ItacMethodDescriptor.class);
|
||||
|
||||
if (methodDescriptor == null) {
|
||||
// Sonderfall getCalendarData
|
||||
if (!xmlApiFunction.getMethod().getName().equals("getCalendarData")) {
|
||||
throw new Exception("method " + xmlApiFunction.getMethod().getName()
|
||||
+ " is not annotated with \"@ItacMethodDescriptor\", method has no parameters...\n");
|
||||
} else {
|
||||
LogHandler.log(LOGGER, INFO, "special case method " + xmlApiFunction.getMethod().getName() + " has no parameters");
|
||||
}
|
||||
}
|
||||
|
||||
LogHandler.log(LOGGER, TRACE, "get parameters for method " + xmlApiFunction.getMethod().getName());
|
||||
Class<?>[] paramTypes = xmlApiFunction.getMethod().getParameterTypes();
|
||||
String[] argNames = new String[0];
|
||||
if (methodDescriptor != null) {
|
||||
argNames = methodDescriptor.argNames();
|
||||
}
|
||||
|
||||
xmlApiFunction.setParameterNames(argNames);
|
||||
|
||||
xmlApiFunction.setParameterTypes(paramTypes);
|
||||
for (int i = 0; i < argNames.length; i++) {
|
||||
LogHandler.log(LOGGER, TRACE, " Parameter " + i + ": " + argNames[i] + ", type :" + paramTypes[i].getName());
|
||||
}
|
||||
// parameter zur Methode checkSnrStateBySnrRef
|
||||
// Parameter 0: stationNr, type :java.lang.String
|
||||
// Parameter 1: processLayer, type :int
|
||||
// Parameter 2: serialNumber, type :java.lang.String
|
||||
// Parameter 3: numberOfRecords, type :org.omg.CORBA.IntHolder
|
||||
// Parameter 4: testDataArray, type :com.itac.easyworks.api.idl.StateDataArrayHolder // out
|
||||
// Parameter 5: errorString, type :org.omg.CORBA.StringHolder // out
|
||||
// Attribute pruefen
|
||||
// alle Parameter werden als einfache Attribute uebergeben
|
||||
HashSet<String> requiredParams = new HashSet<String>();
|
||||
for (int i = 0; i < argNames.length; i++) {
|
||||
if (paramTypes[i].getName().contains("org.omg.CORBA") || paramTypes[i].getName().contains("Holder") // ||
|
||||
// paramTypes[i].getName().contains("com.itac.easyworks.api.idl.")
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
LogHandler.log(LOGGER, TRACE, "required Parameter = " + argNames[i]);
|
||||
requiredParams.add(argNames[i]);
|
||||
}
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
if (attributes != null) {
|
||||
// es gibt attribute, diese jetzt checken und hinzufuegen
|
||||
for (int i = 0; i < attributes.getLength(); i++) {
|
||||
XmlParameter xmlParameter = new XmlParameter(attributes.item(i).getNodeName(), attributes.item(i).getNodeValue());
|
||||
LogHandler.log(LOGGER, TRACE, "parsed Parameter " + xmlParameter.toString());
|
||||
xmlApiFunction.add(xmlParameter);
|
||||
requiredParams.remove(attributes.item(i).getNodeName());
|
||||
}
|
||||
}
|
||||
boolean parseResult = true;
|
||||
StringBuffer resultText = new StringBuffer();
|
||||
NodeList subElements = node.getChildNodes();
|
||||
for (int i = 0; i < subElements.getLength(); i++) {
|
||||
|
||||
Node subNode = subElements.item(i);
|
||||
if (subNode.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
LogHandler.log(LOGGER, TRACE, "node : " + subNode.getNodeName());
|
||||
|
||||
//
|
||||
if (requiredParams.contains(subNode.getNodeName())) {
|
||||
// unterhalb dieses Knotens liegen jetzt die Strukturen
|
||||
if (parseNamedElements(subNode, xmlApiFunction, resultText)) {
|
||||
requiredParams.remove(subNode.getNodeName());
|
||||
}
|
||||
} else {
|
||||
resultText.append(subNode.getNodeName()).append(" is not part of the required params!\n");
|
||||
// das kann jetzt noch ein Typ sein
|
||||
parseResult = false;
|
||||
}
|
||||
}
|
||||
if (requiredParams.size() > 0) {
|
||||
for (String reqParam : requiredParams) {
|
||||
resultText.append("missing parameter " + reqParam + " for function " + xmlApiFunction.getMethod().getName() + "\n");
|
||||
parseResult = false;
|
||||
}
|
||||
}
|
||||
if (!parseResult) {
|
||||
throw new Exception(resultText.toString());
|
||||
}
|
||||
return xmlApiFunction;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlCondition;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlIf;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class IfParser extends PluginParser {
|
||||
|
||||
private static final String RIGHT_OPERAND = "rightOperand";
|
||||
private static final String LEFT_OPERAND = "leftOperand";
|
||||
|
||||
public IfParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlIf parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributesNotEmpty(attributes, new String[] { AssertionParser.CONDITION, LEFT_OPERAND, RIGHT_OPERAND }, "if");
|
||||
|
||||
String sCondition = getAttributeValue(attributes, AssertionParser.CONDITION);
|
||||
XmlCondition condition = XmlCondition.get(sCondition);
|
||||
if (condition == null) {
|
||||
throw new Exception("Assertion construct wrong:\n 'condition' (" + sCondition
|
||||
+ ") is an invalid value; allowed conditions are '" + XmlCondition.getAllConditions() + "'\n");
|
||||
}
|
||||
|
||||
XmlIf xmlIf = new XmlIf(getAttributeValue(attributes, XmlConstruct.ID));
|
||||
xmlIf.setLeftOperand(getAttributeValue(attributes, LEFT_OPERAND));
|
||||
xmlIf.setCondition(condition);
|
||||
xmlIf.setRightOperand(getAttributeValue(attributes, RIGHT_OPERAND));
|
||||
return xmlIf;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlInstance;
|
||||
import com.itac.mes.datainterface.datasource.BasicDataSource;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
import com.itac.util.logging.LogLevel;
|
||||
|
||||
public class InstanceParser extends PluginParser {
|
||||
|
||||
protected static final String NAME = "name";
|
||||
protected static final String ACTION = "action";
|
||||
|
||||
public InstanceParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
protected String getIdConstructHeader(String id, String construct) {
|
||||
return "id: " + id + ": construct '" + construct + "'";
|
||||
}
|
||||
|
||||
@Override
|
||||
// <instance id="instance1" name="fujiInstance" action="stop" />
|
||||
public XmlConstruct parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributesNotEmpty(attributes, new String[] { NAME, ACTION }, getName());
|
||||
|
||||
XmlInstance xmlInstance = new XmlInstance(getAttributeValue(attributes, XmlConstruct.ID));
|
||||
String instanceName = getAttributeValue(attributes, NAME);
|
||||
BasicDataSource instance = getToolBox().getWorkerInstance(instanceName);
|
||||
if (instance == null) {
|
||||
throw new Exception("unknown instance '" + instanceName + "', available instances are: "
|
||||
+ getToolBox().getWorkerInstanceNames().toString());
|
||||
}
|
||||
|
||||
String sAction = getAttributeValue(attributes, ACTION);
|
||||
// die Instanz muss diese Methode besitzen
|
||||
|
||||
try {
|
||||
instance.getClass().getMethod(sAction);
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(getClass().getSimpleName(), LogLevel.ERROR, "parsing construct failed", e);
|
||||
throw e;
|
||||
}
|
||||
// setzen der eigenschaften in der XML Unit, die zum ausführen der Operation reicht
|
||||
xmlInstance.setAction(sAction);
|
||||
xmlInstance.setInstance(instance);
|
||||
return xmlInstance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlJavascript;
|
||||
import com.itac.mes.datainterface.datasource.BasicDataSource;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class JavascriptParser extends PluginParser {
|
||||
|
||||
protected static final String INSTANCE = "instance";
|
||||
|
||||
public JavascriptParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
protected String getIdConstructHeader(String id, String construct) {
|
||||
return "id: " + id + ": construct '" + construct + "'";
|
||||
}
|
||||
|
||||
@Override
|
||||
// <instance id="instance1" name="fujiInstance" action="stop" />
|
||||
public XmlConstruct parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributesNotEmpty(attributes, new String[] { INSTANCE }, getName());
|
||||
|
||||
XmlJavascript xmlInstance = new XmlJavascript(getAttributeValue(attributes, XmlConstruct.ID));
|
||||
String instanceName = getAttributeValue(attributes, INSTANCE);
|
||||
BasicDataSource instance = getToolBox().getWorkerInstance(instanceName);
|
||||
if (instance == null) {
|
||||
throw new Exception("unknown instance '" + instanceName + "', available instances are: "
|
||||
+ getToolBox().getWorkerInstanceNames().toString());
|
||||
}
|
||||
|
||||
// die Instanz muss diese Methode besitzen
|
||||
// setzen der eigenschaften in der XML Unit, die zum ausführen der Operation reicht
|
||||
xmlInstance.setInstance(instance);
|
||||
|
||||
String text = node.getTextContent();
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
xmlInstance.setScript(text);
|
||||
|
||||
return xmlInstance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright (c) 2014 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied, printed, edited
|
||||
* or otherwise distributed, be stored in a retrieval system, or be translated into another language without the written permission
|
||||
* of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlSql;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class SqlXmlParser extends PluginParser {
|
||||
|
||||
public SqlXmlParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlConstruct parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributes(attributes, new String[] { XmlConstruct.ID, "connectionString", "user", "password" }, "");
|
||||
|
||||
String id = getAttributeValue(attributes, XmlConstruct.ID);
|
||||
|
||||
// das ausfuehrbare Statement vorbereiten
|
||||
XmlSql xmlDatabase = new XmlSql(id);
|
||||
|
||||
// die Einstellungen holen
|
||||
if (attributes.getNamedItem("connectionString") != null) {
|
||||
xmlDatabase.setConnectionString(attributes.getNamedItem("connectionString").getNodeValue());
|
||||
}
|
||||
if (attributes.getNamedItem("user") != null) {
|
||||
xmlDatabase.setUser(attributes.getNamedItem("user").getNodeValue());
|
||||
}
|
||||
if (attributes.getNamedItem("password") != null) {
|
||||
xmlDatabase.setPassword(attributes.getNamedItem("password").getNodeValue());
|
||||
}
|
||||
// Besonderheit: im Text ist das SQL enthalten
|
||||
String sql = node.getTextContent();
|
||||
xmlDatabase.setSelect(sql);
|
||||
return xmlDatabase;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* To change this template, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.VariableEngine;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlString;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlStringOperation;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author frankp
|
||||
*/
|
||||
public class StringParser extends PluginParser {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final String ELEMENT = "string";
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final String OPERATION = "operation";
|
||||
|
||||
public StringParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlConstruct parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributesNotEmpty(attributes, new String[] { VariableParser.VARIABLE, VariableParser.VALUE, OPERATION }, ELEMENT);
|
||||
|
||||
String variable = getAttributeValue(attributes, VariableParser.VARIABLE);
|
||||
String value = getAttributeValue(attributes, VariableParser.VALUE);
|
||||
if (!VariableEngine.isVariable(variable)) {
|
||||
throw new Exception("attribute 'variable' for element 'string' does not start with '$'\n");
|
||||
}
|
||||
variable = variable.substring(1);
|
||||
String sOperation = getAttributeValue(attributes, OPERATION);
|
||||
XmlStringOperation stringOperation = XmlStringOperation.getOperation(sOperation);
|
||||
if (stringOperation == null) {
|
||||
throw new Exception("attribute 'operation' (" + sOperation + ") for element 'string' is invalid; allowed operations are '"
|
||||
+ XmlStringOperation.getAllOperations() + "'\n");
|
||||
}
|
||||
|
||||
XmlString xmlString = new XmlString(Long.toString(VariableEngine.getSequence()));
|
||||
xmlString.set(variable, value, stringOperation);
|
||||
|
||||
return xmlString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlTemplate;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class TemplateParser extends PluginParser {
|
||||
|
||||
public TemplateParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlConstruct parse(Node node) {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
|
||||
String id = getAttributeValue(attributes, XmlConstruct.ID);
|
||||
|
||||
XmlTemplate xmlTemplate = new XmlTemplate(id);
|
||||
|
||||
return xmlTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (c) 2014 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied, printed, edited
|
||||
* or otherwise distributed, be stored in a retrieval system, or be translated into another language without the written permission
|
||||
* of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlTestCaseDetail;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class TestCaseDetailParser extends PluginParser {
|
||||
|
||||
public TestCaseDetailParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlConstruct parse(Node node) throws Exception {
|
||||
// das ausfuehrbare Statement vorbereiten
|
||||
XmlTestCaseDetail xmlTestCaseDetails = new XmlTestCaseDetail("details");
|
||||
|
||||
// Besonderheit: im Text ist das SQL enthalten
|
||||
String text = node.getTextContent();
|
||||
xmlTestCaseDetails.setDetailText(text);
|
||||
return xmlTestCaseDetails;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.VariableEngine;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlVariable;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class VariableParser extends PluginParser {
|
||||
|
||||
public static final String NAME = "name";
|
||||
public static final String VARIABLE = "variable";
|
||||
public static final String VALUE = "value";
|
||||
|
||||
public VariableParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlConstruct parse(Node node) throws Exception {
|
||||
// Attribute pruefen
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributesNotEmpty(attributes, new String[] { VariableParser.NAME }, VariableParser.VARIABLE);
|
||||
checkAttributes(attributes, new String[] { VariableParser.VALUE }, VariableParser.VARIABLE);
|
||||
|
||||
String variable = getAttributeValue(attributes, VariableParser.NAME);
|
||||
if (variable == null){
|
||||
throw new Exception("attribute 'name' for element 'variable' does not exist\n");
|
||||
}
|
||||
String value = getAttributeValue(attributes, VariableParser.VALUE);
|
||||
|
||||
if (!variable.isEmpty()) {
|
||||
if (!VariableEngine.isVariable(variable)) {
|
||||
throw new Exception("attribute 'name' for element 'variable' does not start with '$'\n");
|
||||
} else {
|
||||
variable = variable.substring(1);
|
||||
}
|
||||
}
|
||||
if (VariableEngine.isVariable(value)) {
|
||||
// hier koennen nur statische Variablen abgefragt werden
|
||||
VariableEngine ve = new VariableEngine();
|
||||
value = ve.get(value).toString();
|
||||
}
|
||||
variable = variable.substring(1);
|
||||
|
||||
XmlVariable xmlVar = new XmlVariable(Long.toString(VariableEngine.getSequence()));
|
||||
xmlVar.set(variable, value);
|
||||
|
||||
return xmlVar;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlWait;
|
||||
import com.itac.mes.datainterface.parser.PluginParser;
|
||||
|
||||
public class WaitParser extends PluginParser {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final String TIME = "time";
|
||||
|
||||
public WaitParser(String name, Toolbox toolbox) {
|
||||
super(name, toolbox);
|
||||
}
|
||||
|
||||
@Override
|
||||
public XmlConstruct parse(Node node) throws Exception {
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
checkAttributesNotEmpty(attributes, new String[] { XmlConstruct.ID, TIME }, "wait");
|
||||
XmlWait xmlWait = new XmlWait(getAttributeValue(attributes, XmlConstruct.ID));
|
||||
xmlWait.setTime(getAttributeValue(attributes, TIME));
|
||||
return xmlWait;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeSubNodes() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
public class XmlParameter {
|
||||
|
||||
private String name;
|
||||
private String value;
|
||||
|
||||
public XmlParameter(String nodeName, String nodeValue) {
|
||||
name = nodeName;
|
||||
value = nodeValue;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return name + ": " + value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright (c) 2013 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied, printed, edited
|
||||
* or otherwise distributed, be stored in a retrieval system, or be translated into another language without the written permission
|
||||
* of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.process;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
import static com.itac.util.logging.LogLevel.WARN;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.itac.artes.ihas.LookupException;
|
||||
import com.itac.mes.datainterface.annotations.AInit;
|
||||
import com.itac.mes.datainterface.annotations.AInstantiationType;
|
||||
import com.itac.mes.datainterface.annotations.Dispatch;
|
||||
import com.itac.mes.datainterface.annotations.InstantiationType;
|
||||
import com.itac.mes.datainterface.data.ProcessResult;
|
||||
import com.itac.mes.datainterface.data.UploadXmlTestPlanUnit;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestCase;
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestCaseState;
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestSuite;
|
||||
|
||||
/**
|
||||
* The SmtProcessor is responsible to send setup structures (contained in UploadUnits) to the server
|
||||
*
|
||||
* @author frankp
|
||||
* <p>
|
||||
* Date: 15.02.2007<br>
|
||||
*
|
||||
*/
|
||||
@AInstantiationType(type = InstantiationType.PROCESSOR, name = "xmlapi")
|
||||
public class XmlApiProcessor extends DefaultProcessor {
|
||||
|
||||
public XmlApiProcessor() {
|
||||
super();
|
||||
}
|
||||
|
||||
@AInit
|
||||
public void initProcessor() {
|
||||
super.initProcessor();
|
||||
}
|
||||
|
||||
@Dispatch(clazz = UploadXmlTestPlanUnit.class)
|
||||
private Code sendXmlApiUnit(UploadXmlTestPlanUnit uploadUnit, ProcessResult result) throws LookupException {
|
||||
uploadUnit.start();
|
||||
Code code = Code.OK;
|
||||
List<XmlTestSuite> suites = uploadUnit.getXmlTestSuites();
|
||||
for (XmlTestSuite suite : suites) {
|
||||
Code subCode = sendSuite(suite, result);
|
||||
if (code == Code.OK) {
|
||||
code = subCode;
|
||||
}
|
||||
}
|
||||
uploadUnit.stop();
|
||||
return code;
|
||||
}
|
||||
|
||||
private Code sendSuite(XmlTestSuite suite, ProcessResult result) throws LookupException {
|
||||
suite.start();
|
||||
List<XmlTestCase> testCases = suite.getTestCases();
|
||||
try {
|
||||
for (XmlTestCase testCase : testCases) {
|
||||
// String currentTestCase = testCase.getId();
|
||||
sendTestCase(testCase, result);
|
||||
}
|
||||
suite.stop();
|
||||
return Code.OK;
|
||||
} catch (Throwable th) {
|
||||
handleException(th, "sendXmlApiTestSuite", result);
|
||||
return Code.NOT_SENT;
|
||||
}
|
||||
}
|
||||
|
||||
private void sendTestCase(XmlTestCase testCase, ProcessResult result) throws Exception {
|
||||
testCase.start();
|
||||
if (!testCase.getDetailText().isEmpty()) {
|
||||
writeMessage(INFO, "TestCase :" + testCase.getId());
|
||||
writeMessage(INFO, testCase.getDetailText());
|
||||
}
|
||||
|
||||
List<XmlConstruct> xmlConstructs = testCase.getXmlConstructs();
|
||||
for (XmlConstruct xmlConstruct : xmlConstructs) {
|
||||
if (testCase.getState() != XmlTestCaseState.FAIL && testCase.getState() != XmlTestCaseState.EXCEPTION) {
|
||||
xmlConstruct.execute(services);
|
||||
}
|
||||
}
|
||||
testCase.stop();
|
||||
if (testCase.getState() == XmlTestCaseState.PASS) {
|
||||
writeMessage(INFO, "TestCase " + testCase.getId() + " Pass in " + testCase.getTestCaseMillies() + "ms");
|
||||
} else if (testCase.getState() == XmlTestCaseState.FAIL) {
|
||||
writeMessage(INFO, "TestCase " + testCase.getId() + " Fail in " + testCase.getTestCaseMillies() + "ms");
|
||||
} else if (testCase.getState() == XmlTestCaseState.EXCEPTION) {
|
||||
writeMessage(WARN, "TestCase " + testCase.getId() + " aborted after " + testCase.getTestCaseMillies() + "ms");
|
||||
result.setDetailCode(-99);
|
||||
result.setDetailText("TestCase " + testCase.getId() + " aborted after " + testCase.getTestCaseMillies() + "ms");
|
||||
result.setResultCode(Code.SERVICE_NOT_AVAILABLE);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package com.itac.mes.datainterface.simulation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Vector;
|
||||
|
||||
import javax.enterprise.deploy.spi.exceptions.ConfigurationException;
|
||||
|
||||
import com.itac.mes.config.domain.Parameter;
|
||||
import com.itac.mes.datainterface.annotations.AInit;
|
||||
import com.itac.mes.datainterface.annotations.AInstantiationType;
|
||||
import com.itac.mes.datainterface.annotations.AParamValue;
|
||||
import com.itac.mes.datainterface.annotations.AParameter;
|
||||
import com.itac.mes.datainterface.annotations.AParameterDefaultValue;
|
||||
import com.itac.mes.datainterface.annotations.InstantiationType;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlDatabase;
|
||||
import com.itac.mes.datainterface.datasource.database.DbConnectionManager;
|
||||
import com.itac.mes.datainterface.gui.DataInterfaceMenuAction;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.DatabaseXmlParser;
|
||||
import com.itac.mes.intface.basiculi.services.DbTransactionInterface;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
import com.itac.util.logging.LogLevel;
|
||||
|
||||
@AInstantiationType(name = "database", type = InstantiationType.MACHINESIMULATION)
|
||||
public class DatabaseSimulation extends DefaultMachineSimulation {
|
||||
public static final String ID_CONNECT = "connect";
|
||||
public static final String ID_DISCONNECT = "disconnect";
|
||||
public static final String ID_TEST_CONNECTION = "testConnection";
|
||||
public static final String ID_EXECUTE = "execute";
|
||||
public static final String ID_CLEAR = "clear";
|
||||
|
||||
private static final String SIMULATION = "simulation.database";
|
||||
private static final String CONNECTION_STRING = SIMULATION + ".connectionString";
|
||||
private static final String DRIVER = SIMULATION + ".jdbcDriver";
|
||||
private static final String SCHEMA = SIMULATION + ".schemaName";
|
||||
private static final String PROVIDER = SIMULATION + ".provider";
|
||||
private static final String USER = SIMULATION + ".user";
|
||||
private static final String PASSWORD = SIMULATION + ".password";
|
||||
|
||||
@AParameter(name = SIMULATION, description = "tracedatabase",
|
||||
visibility = "MachineSimulation=com.itac.mes.datainterface.simulation.DatabaseSimulation")
|
||||
private Parameter paramSource;
|
||||
@AParameter(name = CONNECTION_STRING, description = "connectionString", parent = SIMULATION, type = String.class)
|
||||
private Parameter paramDbConnect;
|
||||
@AParameter(name = DRIVER, description = "jdbcDriver", parent = SIMULATION, type = String.class)
|
||||
private Parameter paramDbDriver;
|
||||
@AParameter(name = SCHEMA, description = "dbSchema", parent = SIMULATION, type = String.class)
|
||||
private Parameter paramDbSchema;
|
||||
@AParameter(name = PROVIDER, description = "provider", parent = SIMULATION, type = String.class)
|
||||
private Parameter paramDbType;
|
||||
@AParameter(name = USER, description = "dbuser", parent = SIMULATION, type = String.class)
|
||||
private Parameter paramDbUser;
|
||||
@AParameter(name = PASSWORD, description = "dbPassWord", parent = SIMULATION, type = String.class)
|
||||
private Parameter paramDbPwd;
|
||||
|
||||
@AParamValue(value = CONNECTION_STRING)
|
||||
@AParameterDefaultValue(name = CONNECTION_STRING)
|
||||
protected String dbConnect = "jdbc:oracle:thin:@HOST:1521:SID";
|
||||
@AParamValue(value = DRIVER)
|
||||
@AParameterDefaultValue(name = DRIVER)
|
||||
protected String dbDriver = "oracle.jdbc.driver.OracleDriver";
|
||||
@AParamValue(value = SCHEMA)
|
||||
@AParameterDefaultValue(name = SCHEMA)
|
||||
protected String dbSchema = "bde";
|
||||
@AParamValue(value = PROVIDER)
|
||||
@AParameterDefaultValue(name = PROVIDER)
|
||||
protected String dbProvider = "Oracle";
|
||||
@AParamValue(value = USER)
|
||||
@AParameterDefaultValue(name = USER)
|
||||
protected String dbUser = "bde";
|
||||
@AParamValue(value = PASSWORD)
|
||||
@AParameterDefaultValue(name = PASSWORD)
|
||||
protected String dbPwd = "bde_pwd";
|
||||
|
||||
private DbConnectionManager dbConnection;
|
||||
private DbTransactionInterface currentTransaction;
|
||||
|
||||
// die einzelnen Menu-Items werden hier deklariert, und spaeter geadded
|
||||
private DataInterfaceMenuAction connectMenuItem = new DataInterfaceMenuAction("connect", "connect", ID_CONNECT);
|
||||
private DataInterfaceMenuAction disconnectMenuItem = new DataInterfaceMenuAction("disconnect", "disconnect", ID_DISCONNECT);
|
||||
private DataInterfaceMenuAction testConnectionMenuItem = new DataInterfaceMenuAction("testConnection", "testConnection",
|
||||
ID_TEST_CONNECTION);
|
||||
private DataInterfaceMenuAction executeMenuItem = new DataInterfaceMenuAction("execute", "execute", ID_EXECUTE);
|
||||
private DataInterfaceMenuAction clearMenuItem = new DataInterfaceMenuAction("clear", "clear", ID_CLEAR);
|
||||
|
||||
public DatabaseSimulation() {
|
||||
super();
|
||||
|
||||
// im Panel eine Action erzeugen mit ActionName und
|
||||
addSimMenuItem(connectMenuItem);
|
||||
addSimMenuItem(disconnectMenuItem);
|
||||
addSimMenuItem(testConnectionMenuItem);
|
||||
addSimMenuItem(executeMenuItem);
|
||||
addSimMenuItem(clearMenuItem);
|
||||
}
|
||||
|
||||
@AInit
|
||||
|
||||
public void atInit() throws ConfigurationException {
|
||||
try {
|
||||
dbConnection = new DbConnectionManager(dbConnect, dbDriver, dbSchema, dbProvider, dbUser, dbPwd, "defaultPool");
|
||||
((IDatabasePane) getWorkerPane()).setConnectionString(dbConnect);
|
||||
} catch (Throwable e) {
|
||||
throw new ConfigurationException("Database not connected! Check log file");
|
||||
}
|
||||
if (getToolbox() != null && getToolbox().getPluginParser(getSimulationType()) == null) {
|
||||
LogHandler.debug("create plugin parser for '" + getSimulationType() + "'");
|
||||
getToolbox().addPluginParser(new DatabaseXmlParser(getSimulationType(), getToolbox()));
|
||||
}
|
||||
}
|
||||
|
||||
public DbTransactionInterface getCurrentTransaction() {
|
||||
if (currentTransaction == null) {
|
||||
try {
|
||||
currentTransaction = dbConnection.getDbTransaction();
|
||||
} catch (Throwable e) {
|
||||
log("\nget Transaction:\n", e);
|
||||
}
|
||||
}
|
||||
return currentTransaction;
|
||||
}
|
||||
|
||||
public void commit(XmlDatabase xmlDatabase) {
|
||||
try {
|
||||
logCommand("commit transaction");
|
||||
DbTransactionInterface dbTransaction = getCurrentTransaction();
|
||||
dbTransaction.executeStatement("commit");
|
||||
currentTransaction = null;
|
||||
} catch (Throwable e) {
|
||||
log("\ncommit:\n", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void logCommand(String sql) {
|
||||
if (getWorkerPane() instanceof IDatabasePane) {
|
||||
((IDatabasePane) getWorkerPane()).logCommand(sql);
|
||||
}
|
||||
}
|
||||
|
||||
private void log(String sql) {
|
||||
if (getWorkerPane() instanceof IDatabasePane) {
|
||||
((IDatabasePane) getWorkerPane()).logCommand(sql);
|
||||
}
|
||||
}
|
||||
|
||||
private void log(String sql, Throwable e) {
|
||||
if (getWorkerPane() instanceof IDatabasePane) {
|
||||
((IDatabasePane) getWorkerPane()).logCommand(sql);
|
||||
}
|
||||
}
|
||||
|
||||
public void executeUpdate(String sql, XmlDatabase xmlDatabase) {
|
||||
try {
|
||||
logCommand(sql);
|
||||
DbTransactionInterface dbTransaction = getCurrentTransaction();
|
||||
int rowsUpdated = dbTransaction.update(sql);
|
||||
log("\nsuccessful executed\n" + rowsUpdated + " rows updated");
|
||||
if (xmlDatabase != null) {
|
||||
xmlDatabase.getTestCase().getVariableEngine().put(xmlDatabase.getId() + ".update", rowsUpdated);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log("\nException:\n", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void executeInsert(String sql, XmlDatabase xmlDatabase) {
|
||||
try {
|
||||
logCommand(sql);
|
||||
DbTransactionInterface dbTransaction = getCurrentTransaction();
|
||||
int rowsInserted = dbTransaction.insert(sql);
|
||||
log("\nsuccessful executed\n" + rowsInserted + " rows inserted");
|
||||
if (xmlDatabase != null) {
|
||||
xmlDatabase.getTestCase().getVariableEngine().put(xmlDatabase.getId() + ".insert", rowsInserted);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log("\nException:\n", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void executeDelete(String sql, XmlDatabase xmlDatabase) {
|
||||
try {
|
||||
logCommand(sql);
|
||||
DbTransactionInterface dbTransaction = getCurrentTransaction();
|
||||
int rowsDeleted = dbTransaction.delete(sql);
|
||||
log("\nsuccessful executed\n" + rowsDeleted + " rows deleted");
|
||||
if (xmlDatabase != null) {
|
||||
xmlDatabase.getTestCase().getVariableEngine().put(xmlDatabase.getId() + ".delete", rowsDeleted);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log("\nException:\n", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void executeSelect(String sql, XmlDatabase xmlDatabase) {
|
||||
try {
|
||||
((IDatabasePane) getWorkerPane()).logCommand(sql);
|
||||
DbTransactionInterface dbTransaction = getCurrentTransaction();
|
||||
Vector<?> v = dbTransaction.selectUnCommitted(sql);
|
||||
if (v != null && v.size() != 0) {
|
||||
log("\nsuccessful executed");
|
||||
int col = Integer.valueOf((String) v.firstElement());
|
||||
int numLines = (v.size() - 1) / col;
|
||||
// formatierte Ausgabe der Daten in der Console
|
||||
log("\ncolumns " + col + ", " + numLines + " rows\n");
|
||||
// Werte als list <String[]> eintragen
|
||||
List<String[]> result = new ArrayList<String[]>();
|
||||
int elem = 1;
|
||||
for (int line = 0; line < numLines; line++) {
|
||||
log("" + (line + 1) + ": ");
|
||||
String[] rowContent = new String[col];
|
||||
for (int i = 0; i < col; i++) {
|
||||
log(v.get(elem).toString() + ", ");
|
||||
rowContent[i] = v.get(elem++).toString();
|
||||
}
|
||||
log("\n");
|
||||
result.add(rowContent);
|
||||
}
|
||||
if (xmlDatabase != null) {
|
||||
xmlDatabase.getTestCase().getVariableEngine().put(xmlDatabase.getId() + ".rows", numLines);
|
||||
xmlDatabase.getTestCase().getVariableEngine().put(xmlDatabase.getId() + ".column", col);
|
||||
xmlDatabase.getTestCase().getVariableEngine().put(xmlDatabase.getId() + ".result", result);
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log("\nException:\n", e);
|
||||
}
|
||||
}
|
||||
|
||||
protected void connect() {
|
||||
|
||||
}
|
||||
|
||||
protected void disconnect() {
|
||||
|
||||
}
|
||||
|
||||
protected void execute() {
|
||||
String sqlStatement = ((IDatabasePane) getWorkerPane()).getSqlStatement();
|
||||
if (sqlStatement == null || sqlStatement.isEmpty()) {
|
||||
log("Do not execute empty SQL statement\n");
|
||||
LogHandler.log("DBSIM", LogLevel.INFO, "no");
|
||||
return;
|
||||
}
|
||||
if (sqlStatement.startsWith("select")) {
|
||||
executeSelect(sqlStatement, null);
|
||||
}
|
||||
}
|
||||
|
||||
protected void testConnection() {
|
||||
// aus dem SimPanel die DB-conenction holen
|
||||
// diese merken
|
||||
// Verbindung aufbauen
|
||||
if (getCurrentTransaction() != null) {
|
||||
log("connection ok\n");
|
||||
}
|
||||
}
|
||||
|
||||
protected void clear() {
|
||||
((IDatabasePane) getWorkerPane()).clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,712 @@
|
||||
/*
|
||||
* Copyright (c) 2013 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.simulation;
|
||||
|
||||
import static com.itac.util.logging.LogLevel.DEBUG;
|
||||
import static com.itac.util.logging.LogLevel.ERROR;
|
||||
import static com.itac.util.logging.LogLevel.INFO;
|
||||
import static com.itac.util.logging.LogLevel.WARN;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.itac.mes.datainterface.ConfigurationException;
|
||||
import com.itac.mes.datainterface.annotations.AAutoHandler;
|
||||
import com.itac.mes.datainterface.annotations.AInit;
|
||||
import com.itac.mes.datainterface.annotations.AInstantiationType;
|
||||
import com.itac.mes.datainterface.annotations.InstantiationType;
|
||||
import com.itac.mes.datainterface.data.Duration;
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.oib.LayerDetectionMode;
|
||||
import com.itac.mes.datainterface.data.smt.ContainerMslAdjustment;
|
||||
import com.itac.mes.datainterface.data.smt.ContainerQuantityAdjustment;
|
||||
import com.itac.mes.datainterface.data.smt.Filter;
|
||||
import com.itac.mes.datainterface.data.smt.InterlockingMechanism;
|
||||
import com.itac.mes.datainterface.data.smt.LineSettings;
|
||||
import com.itac.mes.datainterface.data.smt.PlacementRecipeCheck;
|
||||
import com.itac.mes.datainterface.data.smt.PlacementRecipeGeneratePattern;
|
||||
import com.itac.mes.datainterface.data.smt.PlacementRecipeMode;
|
||||
import com.itac.mes.datainterface.data.smt.PlacementRecipePattern;
|
||||
import com.itac.mes.datainterface.data.smt.PlacementRecipePatternType;
|
||||
import com.itac.mes.datainterface.data.smt.PlacementRecipeType;
|
||||
import com.itac.mes.datainterface.data.smt.PmMachine;
|
||||
import com.itac.mes.datainterface.data.smt.PmSettings;
|
||||
import com.itac.mes.datainterface.data.smt.SearchReplacePattern;
|
||||
import com.itac.mes.datainterface.data.smt.SerialnumberPositionMode;
|
||||
import com.itac.mes.datainterface.data.smt.SetupDetails;
|
||||
import com.itac.mes.datainterface.data.smt.SmtConfiguration;
|
||||
import com.itac.mes.datainterface.data.smt.StationMessageDetails;
|
||||
import com.itac.mes.datainterface.data.smt.TrMachine;
|
||||
import com.itac.mes.datainterface.data.smt.TrSettings;
|
||||
import com.itac.mes.datainterface.data.smt.TraceabilityMode;
|
||||
import com.itac.mes.datainterface.data.smt.WorkorderBasedSetupSettings;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
import com.itac.mes.datainterface.factories.AConfigurableHandler;
|
||||
import com.itac.mes.datainterface.factories.CommonFactory;
|
||||
import com.itac.mes.datainterface.gui.DataInterfaceMenuAction;
|
||||
import com.itac.mes.datainterface.gui.GuiFactory;
|
||||
import com.itac.mes.datainterface.gui.IMachineSimulation;
|
||||
import com.itac.mes.datainterface.gui.ISimulationMessageReceiver;
|
||||
import com.itac.mes.datainterface.gui.IWorkerPane;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
/*
|
||||
* Copyright (c) 2010 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
public abstract class DefaultMachineSimulation extends AConfigurableHandler implements IMachineSimulation {
|
||||
|
||||
private static final String LOGGER = DefaultMachineSimulation.class.getSimpleName();
|
||||
|
||||
@AAutoHandler(InstantiationType.TOOL)
|
||||
private Toolbox toolbox;
|
||||
|
||||
/**
|
||||
* overrideExistingFiles: wenn dieser Parameter true ist (vom DefaultFileHandler erbende Instanzen können das ändern) dann werden die
|
||||
* Dateien in den Zielverzeichnissen (backup, error, unprocessed, work) gelöscht und durch das neue File ueberschrieben, falls möglich.
|
||||
*/
|
||||
protected boolean overrideExistingfiles;
|
||||
private Map<String, DataInterfaceMenuAction> mnuItemMap = new HashMap<>();
|
||||
|
||||
private IWorkerPane simulationPane;
|
||||
|
||||
private CommonFactory<?> factory;
|
||||
|
||||
public DefaultMachineSimulation() {
|
||||
super();
|
||||
}
|
||||
|
||||
@AInit
|
||||
public void initProcedure() {
|
||||
// der Maschinenname wird als Prefix abgelegt
|
||||
// Pane erzeugen. wenn es moeglich ist die Klasse zu erzeugen (weil die Klassen im classpath sind) dann auch die
|
||||
// Referenz setzen
|
||||
IWorkerPane tmpSimulationPane = GuiFactory.getMachineSimulationPane(this.getClass(), getInstanceName());
|
||||
if (tmpSimulationPane != null) {
|
||||
simulationPane = tmpSimulationPane;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimulationType() {
|
||||
return this.getClass().getAnnotation(AInstantiationType.class).name();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return die Toolbox, mit der die Maschinensimulation erzeugt wurde
|
||||
*/
|
||||
protected Toolbox getToolbox() {
|
||||
return toolbox;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param factory
|
||||
*/
|
||||
public void setFactory(Object factory) {
|
||||
if (factory instanceof CommonFactory<?>) {
|
||||
this.factory = (CommonFactory<?>) factory;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public Set<String> getCustomActionNames() {
|
||||
return mnuItemMap.keySet();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setActionProperties(DataInterfaceMenuAction action) {
|
||||
// default-Implementierung feur alle erbenden Klassen; kann ueberschrieben werden wenn gewuenscht
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean executeAction(DataInterfaceMenuAction action) {
|
||||
return executeAction(action.getMethodName(), 0);
|
||||
}
|
||||
|
||||
public boolean executeAction(String action, XmlConstruct xmlConstruct) {
|
||||
return executeAction(action, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean executeAction(String action, long timeout) {
|
||||
LogHandler.log(LOGGER, DEBUG, "execute action " + action + " on machinesimulation " + getName());
|
||||
DataInterfaceMenuAction menuItem = mnuItemMap.get(action);
|
||||
if (menuItem == null) {
|
||||
LogHandler.log(LOGGER, WARN, "action " + action + " not found for machinesimulation " + getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
execute(menuItem);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* einen Wert eines konfig-Parameters ändern (z.Zt. nur smt-Werte) für Pattern und filter können die einzelnen Werte per . getrennt
|
||||
* werden...
|
||||
*
|
||||
* @param parameterName
|
||||
* @param parameterValue
|
||||
*/
|
||||
@Override
|
||||
public boolean changeConfiguration(String parameterName, String parameterValue, String line, String machine) {
|
||||
LogHandler.log(LOGGER, DEBUG, "change configuration value for line '" + line + "' machine '" + machine + "'");
|
||||
boolean fieldFound = false;
|
||||
try {
|
||||
// try to change a value for a specific type
|
||||
if (line.equalsIgnoreCase("") || line.equals("*")) {
|
||||
InstantiationType selectedType = InstantiationType.valueOf(machine.toUpperCase());
|
||||
List<AConfigurableHandler> handlers = factory.getHandlersOfType(selectedType);
|
||||
LogHandler.log(LOGGER, INFO, "found {0} handlers of type {1}", handlers.size(), selectedType);
|
||||
for (AConfigurableHandler handler : handlers) {
|
||||
// set even private fields
|
||||
LogHandler.log(LOGGER, DEBUG, "try to set value {0} for parameter {1} into handler {2}", parameterValue, parameterName, handler.getClass()
|
||||
.getSimpleName());
|
||||
|
||||
Field[] commonFields = handler.getClass().getDeclaredFields();
|
||||
for (Field field : commonFields) {
|
||||
if (field.getName().equalsIgnoreCase(parameterName)) {
|
||||
safeSetField(handler, field, parameterName, parameterValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
List<SmtConfiguration> smtConfigurations = factory.getAllSmtConfigurations();
|
||||
|
||||
if (smtConfigurations == null) {
|
||||
LogHandler.log(LOGGER, ERROR, "changing configuration value for line '" + line + "' machine '" + machine
|
||||
+ "' not possible because smtConfiguration is null");
|
||||
return false;
|
||||
}
|
||||
|
||||
Field[] commonFields = SmtConfiguration.class.getDeclaredFields();
|
||||
for (SmtConfiguration smtConfiguration : smtConfigurations) {
|
||||
// ist das Feld mit dem Namen da? passt der Datentyp? dann den Wert aendern
|
||||
|
||||
for (Field field : commonFields) {
|
||||
if (field.getName().equalsIgnoreCase(parameterName)) {
|
||||
safeSetField(smtConfiguration, field, parameterName, parameterValue);
|
||||
fieldFound = true;
|
||||
}
|
||||
}
|
||||
if (fieldFound) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (machine != null) {
|
||||
TrMachine trMachine = smtConfiguration.getSmtMachineListTR().get(machine);
|
||||
if (changeTrMachineSettings(trMachine, parameterName, parameterValue, line, machine)) {
|
||||
return true;
|
||||
} else {
|
||||
if (trMachine != null) {
|
||||
changeLineSetting(trMachine.getSmtLineSettings(), parameterName, parameterValue);
|
||||
}
|
||||
}
|
||||
|
||||
PmMachine pmMachine = smtConfiguration.getMachineListPM().get(machine);
|
||||
if (changePmMachineSettings(pmMachine, parameterName, parameterValue, line, machine)) {
|
||||
return true;
|
||||
} else {
|
||||
if (pmMachine != null) {
|
||||
changeLineSetting(pmMachine.getSmtLineSettings(), parameterName, parameterValue);
|
||||
}
|
||||
}
|
||||
|
||||
// change this value in al configured lines
|
||||
boolean changed = false;
|
||||
for (String lineName : smtConfiguration.getLineNames()) {
|
||||
LineSettings lineSettings = smtConfiguration.getLineSettings(lineName);
|
||||
|
||||
if (changeLineSetting(lineSettings, parameterName, parameterValue)) {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!fieldFound) {
|
||||
|
||||
LogHandler.log(LOGGER, ERROR, "change config value: setting " + parameterName + " to " + parameterValue
|
||||
+ " failed because field " + parameterName + " was not found in smtConfiguration");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return fieldFound;
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(LOGGER, ERROR, "changing configuration value failed", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param instance
|
||||
* @param field
|
||||
* @param parameterName
|
||||
* @param parameterValue
|
||||
* @throws Exception
|
||||
*/
|
||||
private void safeSetField(Object instance, Field field, String parameterName, String parameterValue) throws ConfigurationException {
|
||||
field.setAccessible(true);
|
||||
LogHandler.log(LOGGER, DEBUG, "change handler value: setting {0} to {1}", field.getName(), parameterValue);
|
||||
try {
|
||||
if (field.getType() == boolean.class) {
|
||||
field.setBoolean(instance, Boolean.parseBoolean(parameterValue));
|
||||
} else if (field.getType() == String.class) {
|
||||
field.set(instance, parameterValue);
|
||||
} else if (field.getType() == int.class) {
|
||||
field.set(instance, Integer.parseInt(parameterValue));
|
||||
} else if (field.getType() == Duration.class) {
|
||||
field.set(instance, new Duration(parameterValue));
|
||||
} else if (field.getType() == SearchReplacePattern.class) {
|
||||
setSearchReplacePatternValue(instance, field, parameterName, parameterValue);
|
||||
} else if (field.getType() == Filter.class) {
|
||||
setFilterValue(instance, field, parameterName, parameterValue);
|
||||
} else if (field.getType() == PlacementRecipeCheck.class) {
|
||||
setPlacementRecipeCheckValue(instance, field, parameterName, parameterValue);
|
||||
} else if (field.getType() == WorkorderBasedSetupSettings.class) {
|
||||
setSpecialTraceSettingsValue(instance, field, parameterName, parameterValue);
|
||||
} else if (field.getType() == TraceabilityMode.class) {
|
||||
field.set(instance, TraceabilityMode.get(parameterValue));
|
||||
} else if (field.getType() == LayerDetectionMode.class) {
|
||||
field.set(instance, LayerDetectionMode.get(parameterValue));
|
||||
} else if (field.getType() == SerialnumberPositionMode.class) {
|
||||
field.set(instance, SerialnumberPositionMode.get(parameterValue));
|
||||
} else {
|
||||
|
||||
// make a setter by name and try to get first param from method, call for known type int
|
||||
String methodName = "set" + field.getName();
|
||||
for (Method method : instance.getClass().getDeclaredMethods()) {
|
||||
if (method.getName().equalsIgnoreCase(methodName) && method.getParameterTypes().length == 1) {
|
||||
try {
|
||||
Class<?> k = method.getParameterTypes()[0];
|
||||
method.setAccessible(true);
|
||||
if (k == int.class) {
|
||||
int a = Integer.parseInt(parameterValue);
|
||||
method.invoke(instance, a);
|
||||
return;
|
||||
} else if (k == Integer.class) {
|
||||
Integer a = Integer.valueOf(parameterValue);
|
||||
method.invoke(instance, a);
|
||||
return;
|
||||
} else if (k == String.class) {
|
||||
method.invoke(instance, parameterValue);
|
||||
return;
|
||||
}
|
||||
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
|
||||
// ignore this exception: for special Source parameter there is more than one function to set a value
|
||||
// one with String-para and another with enum-parameter. try all available functions here
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new ConfigurationException("unable to set value of type {0} into field {1}", field.getType().getSimpleName(), field.getName());
|
||||
}
|
||||
} catch (IllegalArgumentException | IllegalAccessException e) {
|
||||
throw new ConfigurationException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean setPlacementRecipeCheckValue(Object smtConfiguration, Field field, String parameterName,
|
||||
String parameterValue) throws IllegalAccessException {
|
||||
// das object selbst ermitteln
|
||||
Object obj = field.get(smtConfiguration);
|
||||
String[] values = parameterValue.split("\\="); // Beispiel: active=true
|
||||
Field[] subFields = PlacementRecipeCheck.class.getDeclaredFields();
|
||||
for (Field subField : subFields) {
|
||||
if (subField.getName().equalsIgnoreCase(values[0])) {
|
||||
subField.setAccessible(true);
|
||||
String value = null;
|
||||
if (values.length > 1) {
|
||||
value = values[1];
|
||||
} else {
|
||||
value = "";
|
||||
}
|
||||
|
||||
LogHandler.log(LOGGER, DEBUG,
|
||||
"change PlacementRecipeCheck value for " + parameterName + ": setting " + values[0] + " to " + value);
|
||||
if (subField.getType() == PlacementRecipeMode.class) {
|
||||
subField.set(obj, PlacementRecipeMode.get(value));
|
||||
} else if (subField.getType() == PlacementRecipeType.class) {
|
||||
subField.set(obj, PlacementRecipeType.get(value));
|
||||
} else if (subField.getType() == List.class) {
|
||||
// diverse Sonderfälle für Liste.
|
||||
if (value.equalsIgnoreCase("clear")) {
|
||||
subField.set(obj, new ArrayList<PlacementRecipePattern>());
|
||||
} else {
|
||||
if (parameterValue.indexOf("add(") >= 0) {
|
||||
// from placementRecipePatternList=add(PRODUCT({search=.*_(.*_.*)_.*},{replace=$1}))
|
||||
// get add(PRODUCT({search=.*_(.*_.*)_.*},{replace=$1}))
|
||||
String patternString = parameterValue.substring(parameterValue.indexOf("add(") + 4, parameterValue.length() - 1);
|
||||
if (subField.get(obj) instanceof ArrayList<?>) {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<PlacementRecipePattern> v = (List<PlacementRecipePattern>) subField.get(obj);
|
||||
v.add(getPlacementRecipeReplacePattern(patternString));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (subField.getType() == PlacementRecipeGeneratePattern.class) {
|
||||
PlacementRecipeGeneratePattern p = new PlacementRecipeGeneratePattern();
|
||||
p.setPatternText(value);
|
||||
subField.set(obj, p);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
LogHandler.log(LOGGER, DEBUG, "value for PlacementRecipeCheck " + parameterName + " not changed");
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param handler
|
||||
* @param field
|
||||
* @param parameterName
|
||||
* @param parameterValue
|
||||
* @return
|
||||
* @throws IllegalAccessException
|
||||
* @throws IllegalArgumentException
|
||||
* @throws ConfigurationException
|
||||
* @throws Exception
|
||||
*/
|
||||
private boolean setSpecialTraceSettingsValue(Object handler, Field field, String parameterName,
|
||||
String parameterValue) throws IllegalAccessException, ConfigurationException {
|
||||
// das object selbst ermitteln
|
||||
String[] values = parameterValue.split("=");
|
||||
// expected: 2 values, 1:setBarcodePattern, 2: value)
|
||||
WorkorderBasedSetupSettings instField = (WorkorderBasedSetupSettings) field.get(handler);
|
||||
if (values[0].equalsIgnoreCase("BarcodePattern")) {
|
||||
// The object should have a setter method
|
||||
instField.setBarcodePattern(values.length > 1 ? values[1] : "");
|
||||
return true;
|
||||
} else {
|
||||
Field[] subFields = WorkorderBasedSetupSettings.class.getDeclaredFields();
|
||||
for (Field subField : subFields) {
|
||||
if (subField.getName().equalsIgnoreCase(values[0])) {
|
||||
safeSetField(instField, subField, parameterName, values[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LogHandler.log(LOGGER, DEBUG, "value for setSpecialTrace " + parameterName + " not changed");
|
||||
return false;
|
||||
}
|
||||
|
||||
protected PlacementRecipePattern getPlacementRecipeReplacePattern(String patternString) {
|
||||
// remains "PRODUCT(search=.*_(.*_.*)_.*,replace=$1)" here
|
||||
LogHandler.log(LOGGER, DEBUG, patternString);
|
||||
String typeString = patternString.substring(0, patternString.indexOf("("));
|
||||
|
||||
PlacementRecipePattern result = new PlacementRecipePattern();
|
||||
result.setPlacementRecipePatternType(PlacementRecipePatternType.valueOf(typeString));
|
||||
String searchReplaceString = patternString.substring(patternString.indexOf("(") + 1, patternString.length() - 1);
|
||||
if (searchReplaceString.startsWith("{")) {
|
||||
// complex form, expression may contain {} as well
|
||||
String v = matchingParenthesis(searchReplaceString);
|
||||
setPartialPattern(result, v);
|
||||
String remain = searchReplaceString.substring(v.length() + 3).trim();
|
||||
setPartialPattern(result, matchingParenthesis(remain));
|
||||
} else {
|
||||
// simplified form, comma only
|
||||
setPartialPattern(result, searchReplaceString.substring(0, searchReplaceString.indexOf(",")));
|
||||
setPartialPattern(result, searchReplaceString.substring(searchReplaceString.indexOf(",") + 1, searchReplaceString.length()).trim());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
protected void setPartialPattern(PlacementRecipePattern result, String value) {
|
||||
// e.g. search=.*_(.*_.*)_.*
|
||||
// e.g. replace=.*_(.*_.*)_.*
|
||||
String sValue = value.trim();
|
||||
if (sValue.startsWith("search=")) {
|
||||
result.setSearchPattern(sValue.substring(7));
|
||||
return;
|
||||
} else if (sValue.startsWith("replace=")) {
|
||||
result.setReplacePattern(sValue.substring(8));
|
||||
return;
|
||||
}
|
||||
throw new IllegalArgumentException("unable to modify PlacementRecipePattern with " + value);
|
||||
}
|
||||
|
||||
/**
|
||||
* search in a string the first { and the corresponding closing } and returns the substring between.
|
||||
*
|
||||
* exception when not closed
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
protected String matchingParenthesis(String k) {
|
||||
if (k == null) {
|
||||
throw new IllegalArgumentException("can not find matching parenthesis in null string");
|
||||
}
|
||||
if (k.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
int level = 0;
|
||||
int pos = 0;
|
||||
int startpos = -1;
|
||||
do {
|
||||
if (k.charAt(pos) == '{') {
|
||||
if (level == 0) {
|
||||
startpos = pos;
|
||||
}
|
||||
level++;
|
||||
}
|
||||
if (k.charAt(pos) == '}') {
|
||||
level--;
|
||||
}
|
||||
pos++;
|
||||
} while ((level > 0 || startpos == -1) && pos < k.length());
|
||||
|
||||
if (level == 0) {
|
||||
return k.substring(startpos + 1, pos - 1);
|
||||
}
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
private boolean setFilterValue(Object smtConfiguration, Field field, String parameterName, String parameterValue) throws IllegalArgumentException,
|
||||
IllegalAccessException {
|
||||
Object obj = field.get(smtConfiguration);
|
||||
String[] values = parameterValue.split("="); // Beispiel: active=true
|
||||
Field[] subFields = Filter.class.getDeclaredFields();
|
||||
for (Field subField : subFields) {
|
||||
if (subField.getName().equalsIgnoreCase(values[0])) {
|
||||
subField.setAccessible(true);
|
||||
String value = null;
|
||||
if (values.length >= 1) {
|
||||
value = values[1];
|
||||
} else {
|
||||
value = "";
|
||||
}
|
||||
LogHandler.log(LOGGER, DEBUG, "change Filter value for " + parameterName + ": setting " + values[0] + " to " + value);
|
||||
if (subField.getType() == boolean.class) {
|
||||
subField.setBoolean(obj, Boolean.parseBoolean(values[1]));
|
||||
} else if (subField.getType() == String.class) {
|
||||
subField.set(obj, value);
|
||||
}
|
||||
// hier muessen die Felder explizit gesetzt werden
|
||||
((Filter) obj).setActive(((Filter) obj).isActive());
|
||||
((Filter) obj).setFilterPattern(((Filter) obj).getFilterPattern());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
LogHandler.log(LOGGER, DEBUG, "value for Filter " + parameterName + " not changed");
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
private boolean setSearchReplacePatternValue(Object smtConfiguration, Field field, String parameterName,
|
||||
String parameterValue) throws IllegalArgumentException, IllegalAccessException {
|
||||
Object obj = field.get(smtConfiguration);
|
||||
String[] values = parameterValue.split("\\="); // Beispiel: active=true
|
||||
Field[] subFields = SearchReplacePattern.class.getDeclaredFields();
|
||||
for (Field subField : subFields) {
|
||||
if (subField.getName().equalsIgnoreCase(values[0])) {
|
||||
subField.setAccessible(true);
|
||||
String value = null;
|
||||
if (values.length > 1) {
|
||||
value = values[1];
|
||||
} else {
|
||||
value = "";
|
||||
}
|
||||
|
||||
LogHandler.log(LOGGER, DEBUG,
|
||||
"change SearchReplacePattern value for " + parameterName + ": setting " + values[0] + " to " + value);
|
||||
if (subField.getType() == boolean.class) {
|
||||
subField.setBoolean(obj, Boolean.parseBoolean(values[1]));
|
||||
} else if (subField.getType() == String.class) {
|
||||
subField.set(obj, value);
|
||||
}
|
||||
// hier muessen die Felder explizit gesetzt werden
|
||||
((SearchReplacePattern) obj).setActive(((SearchReplacePattern) obj).isActive());
|
||||
((SearchReplacePattern) obj).setReplacePattern(((SearchReplacePattern) obj).getReplacePattern());
|
||||
((SearchReplacePattern) obj).setSearchPattern(((SearchReplacePattern) obj).getSearchPattern());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
LogHandler.log(LOGGER, DEBUG, "value for SearchReplacePattern " + parameterName + " not changed");
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean changePmMachineSettings(PmMachine pmMachine, String parameterName, String parameterValue, String line,
|
||||
String machine) throws IllegalAccessException {
|
||||
boolean fieldFound = false;
|
||||
|
||||
Field[] pmSettingsFields = PmSettings.class.getDeclaredFields();
|
||||
// Wert <20>ndern in diesem Object
|
||||
for (Field field : pmSettingsFields) {
|
||||
if (field.getName().equals(parameterName)) {
|
||||
field.setAccessible(true);
|
||||
fieldFound = true;
|
||||
if (pmMachine == null) {
|
||||
LogHandler.log(LOGGER, ERROR,
|
||||
"cannot change value because pmMachine not found for line '" + line + "' machine '" + machine + "'");
|
||||
continue;
|
||||
}
|
||||
LogHandler.log(LOGGER, DEBUG,
|
||||
pmMachine.getName() + ": change config value : setting " + field.getName() + " to " + parameterValue);
|
||||
|
||||
if (field.getType() == boolean.class) {
|
||||
field.setBoolean(pmMachine.getSmtSettings(), Boolean.parseBoolean(parameterValue));
|
||||
} else if (field.getType() == String.class) {
|
||||
field.set(pmMachine.getSmtSettings(), parameterValue);
|
||||
} else if (field.getType() == StationMessageDetails.class) {
|
||||
field.set(pmMachine.getSmtSettings(), StationMessageDetails.get(parameterValue));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fieldFound;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param trMachine
|
||||
* @param parameterName
|
||||
* @param parameterValue
|
||||
* @param line
|
||||
* @param machine
|
||||
* @return true, wenn der Wert des Feldes geändert wurde, sonst false
|
||||
* @throws IllegalArgumentException
|
||||
* @throws IllegalAccessException
|
||||
*/
|
||||
private boolean changeTrMachineSettings(TrMachine trMachine, String parameterName, String parameterValue, String line,
|
||||
String machine) throws IllegalAccessException {
|
||||
boolean fieldFound = false;
|
||||
Field[] trSettingsFields = TrSettings.class.getDeclaredFields();
|
||||
// Wert <20>ndern in diesem Object
|
||||
for (Field field : trSettingsFields) {
|
||||
if (field.getName().equalsIgnoreCase(parameterName)) {
|
||||
field.setAccessible(true);
|
||||
fieldFound = true;
|
||||
if (trMachine == null) {
|
||||
LogHandler.log(LOGGER, ERROR,
|
||||
"cannot change value because trMachine not found for line '" + line + "' machine '" + machine + "'");
|
||||
continue;
|
||||
}
|
||||
LogHandler.log(LOGGER, DEBUG,
|
||||
trMachine.getName() + ": change config value: setting " + field.getName() + " to " + parameterValue);
|
||||
|
||||
if (field.getType() == boolean.class) {
|
||||
field.setBoolean(trMachine.getSmtSettings(), Boolean.parseBoolean(parameterValue));
|
||||
} else if (field.getType() == String.class) {
|
||||
field.set(trMachine.getSmtSettings(), parameterValue);
|
||||
} else if (field.getType() == InterlockingMechanism.class) {
|
||||
field.set(trMachine.getSmtSettings(), InterlockingMechanism.get(parameterValue));
|
||||
}
|
||||
}
|
||||
}
|
||||
return fieldFound;
|
||||
}
|
||||
|
||||
private boolean changeLineSetting(LineSettings lineSettings, String parameterName, String parameterValue)
|
||||
throws IllegalAccessException {
|
||||
boolean fieldFound = false;
|
||||
if (lineSettings != null) {
|
||||
Field[] lineSettingsFields = LineSettings.class.getDeclaredFields();
|
||||
|
||||
for (Field lineField : lineSettingsFields) {
|
||||
if (lineField.getName().equalsIgnoreCase(parameterName)) {
|
||||
lineField.setAccessible(true);
|
||||
fieldFound = true;
|
||||
LogHandler.log(LOGGER, DEBUG,
|
||||
lineSettings.getLineName() + ": change lineconfig value: setting " + lineField.getName() + " to " + parameterValue);
|
||||
if (lineField.getType() == boolean.class) {
|
||||
lineField.setBoolean(lineSettings, Boolean.parseBoolean(parameterValue));
|
||||
} else if (lineField.getType() == String.class) {
|
||||
lineField.set(lineSettings, parameterValue);
|
||||
} else if (lineField.getType() == ContainerQuantityAdjustment.class) {
|
||||
lineField.set(lineSettings, ContainerQuantityAdjustment.get(parameterValue));
|
||||
} else if (lineField.getType() == ContainerMslAdjustment.class) {
|
||||
lineField.set(lineSettings, ContainerMslAdjustment.get(parameterValue));
|
||||
} else if (lineField.getType() == SetupDetails.class) {
|
||||
lineField.set(lineSettings, SetupDetails.get(parameterValue));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return fieldFound;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<DataInterfaceMenuAction> getMenuItems() {
|
||||
return mnuItemMap.values();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DataInterfaceMenuAction menuItem) {
|
||||
LogHandler.log(LOGGER, ERROR, "execute action '" + menuItem.getMethodName() + "' on simulation instance '" + getInstanceName()
|
||||
+ "', type '" + getSimulationType() + "'");
|
||||
// anhand der action den Methodennamen finden, per Reflection diese Methode am eigenen Objekt aufrufen
|
||||
for (DataInterfaceMenuAction tmpMenuItem : mnuItemMap.values()) {
|
||||
if (tmpMenuItem.getMenuText().equalsIgnoreCase(menuItem.getMenuText())) {
|
||||
String methodName = tmpMenuItem.getMethodName();
|
||||
try {
|
||||
Method method = getClass().getDeclaredMethod(methodName, new Class<?>[0]);
|
||||
method.setAccessible(true); // es darf auch eine private Methode sein
|
||||
method.invoke(this, new Object[0]);
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(LOGGER, ERROR, "failed to execute method " + methodName + " simulation instance '" + getInstanceName()
|
||||
+ "', type '" + getSimulationType() + "'", e);
|
||||
// List all available Methods
|
||||
LogHandler.log(LOGGER, INFO, "list available methods:");
|
||||
for (Method method : getClass().getDeclaredMethods()) {
|
||||
LogHandler.log(LOGGER, INFO, " : " + method.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IWorkerPane getWorkerPane() {
|
||||
return simulationPane;
|
||||
}
|
||||
|
||||
public void addSimMenuItem(DataInterfaceMenuAction menuItem) {
|
||||
mnuItemMap.put(menuItem.getMethodName(), menuItem);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasAction(String action) {
|
||||
return mnuItemMap.containsKey(action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataInterfaceMenuAction getCustomAction(String name) {
|
||||
return mnuItemMap.get(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSimulationMessageReceiver(ISimulationMessageReceiver simulationMessageReceiver) {
|
||||
// diesen Listener an alle customActions dranhaengen
|
||||
for (DataInterfaceMenuAction customAction : mnuItemMap.values()) {
|
||||
customAction.addSimulationMessageReceiver(simulationMessageReceiver);
|
||||
customAction.setInstanceName(getInstanceName());
|
||||
}
|
||||
}
|
||||
|
||||
public void setSimulationPane(IWorkerPane machineSimPane) {
|
||||
this.simulationPane = machineSimPane;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
com.itac.mes.datainterface.parser.XmlApiParser
|
||||
com.itac.mes.datainterface.process.XmlApiProcessor
|
||||
com.itac.mes.datainterface.filehandler.XmlApiFileHandler
|
||||
com.itac.mes.datainterface.simulation.DatabaseSimulation
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.itac.mes.datainterface.data;
|
||||
|
||||
/*
|
||||
* Copyright (c) 2008 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part
|
||||
* of this file in any form be copied, printed, edited or otherwise distributed,
|
||||
* be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author frankp
|
||||
*/
|
||||
public class UploadXmlTestPlanUnitTest {
|
||||
|
||||
public UploadXmlTestPlanUnitTest() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.itac.easyworks.api.idl.MaterialBinData;
|
||||
import com.itac.easyworks.api.idl.SerialNumberData;
|
||||
|
||||
public class VariableEngineTest {
|
||||
|
||||
class SubPanelState {
|
||||
public String panelName;
|
||||
public boolean place;
|
||||
public String reason;
|
||||
}
|
||||
|
||||
class BoardRequestResult {
|
||||
|
||||
public static final String REJECTED = "Rejected";
|
||||
public static final String CONFIRMED = "Confirmed";
|
||||
|
||||
public String boardPath;
|
||||
public String boardSide;
|
||||
public String reason;
|
||||
|
||||
public String requestResult;
|
||||
public SubPanelState[] subPanelStates;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSimpleVariable() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
out.put("$variable", "123");
|
||||
Assert.assertTrue("Variable nicht enthalten", out.containsVariable("$variable"));
|
||||
Assert.assertTrue("Variable nicht enthalten", out.containsVariable("variable"));
|
||||
Assert.assertEquals("Variable nicht ermittelt mit $", "123", out.get("$variable"));
|
||||
Assert.assertEquals("Variable nicht ermittelt ohne $", "123", out.get("variable"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStructuredVariable() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
double qty = 0.0D;
|
||||
int expire = 0;
|
||||
double quantity = 100.0d;
|
||||
double cost = 100.0d;
|
||||
int costbase = 10;
|
||||
out.put("$variable", new MaterialBinData("matbinnr", "product", qty, "chargeNr", "binLocation", "locationDesc", "state",
|
||||
expire, "dateCode", quantity, cost, costbase));
|
||||
Object x = out.get("$variable.materialBinNr");
|
||||
Assert.assertNotNull(x);
|
||||
Assert.assertEquals("matbinnr", x.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStructuredArrayVariable() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
double qty = 0.0D;
|
||||
int expire = 0;
|
||||
double quantity = 100.0d;
|
||||
double cost = 100.0d;
|
||||
int costbase = 10;
|
||||
out.put("$variable", new MaterialBinData[] { new MaterialBinData("matbinnr", "product", qty, "chargeNr", "binLocation",
|
||||
"locationDesc", "state", expire, "dateCode", quantity, cost, costbase) });
|
||||
Object x = out.get("$variable[0].materialBinNr");
|
||||
Assert.assertNotNull(x);
|
||||
Assert.assertEquals("matbinnr", x.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStringArrayVariable() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
out.put("$variable", new String[] { "matbinnr", "product", "chargeNr" });
|
||||
Object x = out.get("$variable[0]");
|
||||
Assert.assertNotNull(x);
|
||||
Assert.assertEquals("matbinnr", x.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTimeVariable() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
Assert.assertEquals(1228991477, out.getTimeVariable("$TIME", 1228991477000L));
|
||||
Assert.assertEquals(1228991477, out.getTimeVariable("$TIME(int)", 1228991477758L));
|
||||
Assert.assertEquals(1228991477000L, out.getTimeVariable("$TIME(long)", 1228991477000L));
|
||||
Assert.assertEquals("20081211113117", out.getTimeVariable("$TIME(yyyyMMddHHmmss)", 1228991477000L));
|
||||
Assert.assertEquals(1228991478, out.getTimeVariable("$TIME(int,00:00:01)", 1228991477000L));
|
||||
Assert.assertEquals(1228991478, out.getTimeVariable("$TIME(int,+00:00:01)", 1228991477000L));
|
||||
Assert.assertEquals(1228991476, out.getTimeVariable("$TIME(int,-00:00:01)", 1228991477000L));
|
||||
Assert.assertEquals(1228991478000L, out.getTimeVariable("$TIME(long,00:00:01)", 1228991477000L));
|
||||
Assert.assertEquals(1228991478000L, out.getTimeVariable("$TIME(long,+00:00:01)", 1228991477000L));
|
||||
Assert.assertEquals(1228991476000L, out.getTimeVariable("$TIME(long,-00:00:01)", 1228991477000L));
|
||||
Assert.assertEquals("20081211113118", out.getTimeVariable("$TIME(yyyyMMddHHmmss,00:00:01)", 1228991477000L));
|
||||
Assert.assertEquals("20081211113118", out.getTimeVariable("$TIME(yyyyMMddHHmmss,+00:00:01)", 1228991477000L));
|
||||
Assert.assertEquals("20081211113116", out.getTimeVariable("$TIME(yyyyMMddHHmmss,-00:00:01)", 1228991477000L));
|
||||
Assert.assertEquals("20081201113117", out.getTimeVariable("$TIME(yyyyMMddHHmmss,-240:00:00)", 1228991477000L));
|
||||
Assert.assertNotNull(out.get("$TIME(int)"));
|
||||
// GMT 0 Test Winter
|
||||
Assert.assertEquals("10:31:17 11.12.2008", out.getTimeVariable("$TIMEGMT0(HH:mm:ss dd.MM.yyyy)", 1228991477000L));
|
||||
Assert.assertEquals(1228987877, out.getTimeVariable("$TIMEGMT0(int)", 1228991477000L));
|
||||
Assert.assertEquals(1228987877000L, out.getTimeVariable("$TIMEGMT0(long)", 1228991477000L));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVariableDump() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
out.put("$TIME", "nicht setzbare variable");
|
||||
out.dump(true);
|
||||
// falsches Zahlenformat
|
||||
Assert.assertNotNull(out.get("$TIME(int, 123:222:444,123)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContainsTimeVariable() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
Assert.assertTrue(out.containsVariable("$TIME"));
|
||||
Assert.assertTrue(out.containsVariable("$TIME(yyyyMMddHHmmss,-240:00:00)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStructuredArray() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
SerialNumberData[] dataArray = new SerialNumberData[] { new SerialNumberData("SN1", "pos1") };
|
||||
out.put("variable", dataArray);
|
||||
|
||||
Assert.assertTrue(out.containsVariable("variable"));
|
||||
Assert.assertTrue(out.containsVariable("variable[0].serialNumber"));
|
||||
Assert.assertTrue(out.containsVariable("variable[0].serialNumberPos"));
|
||||
Assert.assertTrue(out.containsVariable("variable.length"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testListVariable() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
ArrayList<SerialNumberData> a = new ArrayList<SerialNumberData>();
|
||||
a.add(new SerialNumberData("SN1", "pos1"));
|
||||
out.put("listVariable", a);
|
||||
|
||||
Assert.assertTrue(out.containsVariable("listVariable"));
|
||||
Assert.assertEquals(1, out.get("listVariable.length"));
|
||||
Assert.assertTrue(out.containsVariable("listVariable[0].serialNumber"));
|
||||
Assert.assertTrue(out.containsVariable("listVariable[0].serialNumberPos"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testListOfStringArray() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
String[] stringArray1 = new String[] { "r1c1", "r1c2", "r1c3" };
|
||||
String[] stringArray2 = new String[] { "r2c1", "r2c2", "r2c3" };
|
||||
String[] stringArray3 = new String[] { "r3c1", "r3c2", "r3c3" };
|
||||
|
||||
List<String[]> stringArrayList = new ArrayList<String[]>();
|
||||
stringArrayList.add(stringArray1);
|
||||
stringArrayList.add(stringArray2);
|
||||
stringArrayList.add(stringArray3);
|
||||
|
||||
out.put("listVariable", stringArrayList);
|
||||
Assert.assertTrue(out.containsVariable("listVariable"));
|
||||
Assert.assertEquals(3, out.get("listVariable.length"));
|
||||
Assert.assertTrue(out.containsVariable("listVariable[0]"));
|
||||
Assert.assertTrue(out.containsVariable("listVariable[1]"));
|
||||
Assert.assertTrue(out.containsVariable("listVariable[2]"));
|
||||
Assert.assertTrue(out.containsVariable("listVariable[0,1]"));
|
||||
Assert.assertEquals("r1c1", out.get("listVariable[0,0]"));
|
||||
Assert.assertEquals("r1c2", out.get("listVariable[0,1]"));
|
||||
Assert.assertEquals("r1c3", out.get("listVariable[0,2]"));
|
||||
Assert.assertEquals("r2c1", out.get("listVariable[1,0]"));
|
||||
Assert.assertEquals("r2c2", out.get("listVariable[1,1]"));
|
||||
Assert.assertEquals("r2c3", out.get("listVariable[1,2]"));
|
||||
Assert.assertEquals("r3c1", out.get("listVariable[2,0]"));
|
||||
Assert.assertEquals("r3c2", out.get("listVariable[2,1]"));
|
||||
Assert.assertEquals("r3c3", out.get("listVariable[2,2]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExplicitNullValue() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
Assert.assertNull(out.get("$null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStructuredArrayContent() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
|
||||
BoardRequestResult brr = new BoardRequestResult();
|
||||
brr.boardPath = "boardPath";
|
||||
brr.requestResult = "Confirmed";
|
||||
brr.subPanelStates = new SubPanelState[2];
|
||||
brr.subPanelStates[0] = new SubPanelState();
|
||||
brr.subPanelStates[0].place = true;
|
||||
brr.subPanelStates[1] = new SubPanelState();
|
||||
brr.subPanelStates[1].place = false;
|
||||
|
||||
out.put("$r1.return", brr);
|
||||
out.dump(true);
|
||||
|
||||
Object o = out.get("$r1.return.subPanelStates[0].place");
|
||||
Assert.assertEquals(true, o);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testStructuredArrayContent2() {
|
||||
VariableEngine out = new VariableEngine();
|
||||
out.put("$b", new Integer[]{1,0,3});
|
||||
|
||||
BoardRequestResult brr = new BoardRequestResult();
|
||||
brr.boardPath = "boardPath";
|
||||
brr.requestResult = "Confirmed";
|
||||
brr.subPanelStates = new SubPanelState[2];
|
||||
brr.subPanelStates[0] = new SubPanelState();
|
||||
brr.subPanelStates[0].place = true;
|
||||
brr.subPanelStates[1] = new SubPanelState();
|
||||
brr.subPanelStates[1].place = false;
|
||||
|
||||
out.put("$r1.return.subPanelStates[$b[1]].place", brr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldSplitEmptyString(){
|
||||
String testString = "";
|
||||
VariableEngine testee = new VariableEngine();
|
||||
List <String > result = testee.getFunctionNames(testString);
|
||||
assertNotNull(result);
|
||||
assertEquals(0, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldSplitSimpleFunctionName(){
|
||||
String testString = "function1()";
|
||||
VariableEngine testee = new VariableEngine();
|
||||
List <String > result = testee.getFunctionNames(testString);
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size() );
|
||||
assertEquals("function1", result.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldSplitMultipleFunctionName(){
|
||||
String testString = "function1()->function2->function3()";
|
||||
VariableEngine testee = new VariableEngine();
|
||||
List <String > result = testee.getFunctionNames(testString);
|
||||
assertNotNull(result);
|
||||
assertEquals(3, result.size() );
|
||||
assertEquals("function1", result.get(0));
|
||||
assertEquals("function2", result.get(1));
|
||||
assertEquals("function3", result.get(2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Copyright (c) 2010 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.UploadXmlTestPlanUnit;
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestCase;
|
||||
import com.itac.mes.datainterface.parser.data.XmlTestSuite;
|
||||
import com.itac.mes.datainterface.parser.xmlapi.AssertionParser;
|
||||
|
||||
/**
|
||||
* @author frankp created 2011
|
||||
*/
|
||||
public class XmlAssertionTest {
|
||||
private Node getNode(String text) throws SAXException, IOException, ParserConfigurationException {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
InputSource is = new InputSource(new StringReader(text));
|
||||
Document document = builder.parse(is);
|
||||
return document.getDocumentElement();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseAssertionMissingId() throws SAXException, IOException, ParserConfigurationException, Exception {
|
||||
// <if leftCondition="$variable" operand="equals" rightCondition="EXPECTED"/>
|
||||
AssertionParser assertionParser = new AssertionParser(AssertionParser.ASSERT, new Toolbox());
|
||||
assertionParser.parse(getNode("<assert test=\"$variable\" expected=\"1;3;5\" condition=\"in\" />"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseAssertionWithIncondition() throws SAXException, IOException, ParserConfigurationException, Exception {
|
||||
// <if leftCondition="$variable" operand="equals" rightCondition="EXPECTED"/>
|
||||
AssertionParser assertionParser = new AssertionParser("", new Toolbox());
|
||||
XmlAssertion construct = assertionParser
|
||||
.parse(getNode("<assert id=\"unique\" test=\"$variable\" expected=\"1;3;5\" condition=\"in\" />"));
|
||||
|
||||
UploadXmlTestPlanUnit xmlTestPlan = new UploadXmlTestPlanUnit();
|
||||
XmlTestSuite testSuite = new XmlTestSuite(xmlTestPlan);
|
||||
XmlTestCase testCase = new XmlTestCase(testSuite);
|
||||
|
||||
testCase.getVariableEngine().put("$variable", "0");
|
||||
construct.setTestCase(testCase);
|
||||
Assert.assertFalse("0 is not in value list", construct.executeAssert(null));
|
||||
testCase.getVariableEngine().put("$variable", "1");
|
||||
construct.setTestCase(testCase);
|
||||
Assert.assertTrue("1 is in value list", construct.executeAssert(null));
|
||||
testCase.getVariableEngine().put("$variable", "notinteger");
|
||||
construct.setTestCase(testCase);
|
||||
Assert.assertFalse("notinteger is not in value list", construct.executeAssert(null));
|
||||
testCase.getVariableEngine().put("$variable", "anyString");
|
||||
construct.setTestCase(testCase);
|
||||
Assert.assertFalse("anyString is in value list", construct.executeAssert(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseAssertion() throws SAXException, IOException, ParserConfigurationException, Exception {
|
||||
// <if leftCondition="$variable" operand="equals" rightCondition="EXPECTED"/>
|
||||
AssertionParser assertionParser = new AssertionParser("", new Toolbox());
|
||||
XmlAssertion construct = assertionParser
|
||||
.parse(getNode("<assert id=\"unique\" test=\"$variable\" expected=\"1;3;5\" condition=\"in\" />"));
|
||||
|
||||
UploadXmlTestPlanUnit xmlTestPlan = new UploadXmlTestPlanUnit();
|
||||
XmlTestSuite testSuite = new XmlTestSuite(xmlTestPlan);
|
||||
XmlTestCase testCase = new XmlTestCase(testSuite);
|
||||
|
||||
testCase.getVariableEngine().put("$variable", "0");
|
||||
construct.setTestCase(testCase);
|
||||
Assert.assertFalse("0 is not in value list", construct.executeAssert(null));
|
||||
testCase.getVariableEngine().put("$variable", "1");
|
||||
construct.setTestCase(testCase);
|
||||
Assert.assertTrue("1 is in value list", construct.executeAssert(null));
|
||||
testCase.getVariableEngine().put("$variable", "notinteger");
|
||||
construct.setTestCase(testCase);
|
||||
Assert.assertFalse("notinteger is not in value list", construct.executeAssert(null));
|
||||
testCase.getVariableEngine().put("$variable", "anyString");
|
||||
construct.setTestCase(testCase);
|
||||
Assert.assertFalse("anyString is in value list", construct.executeAssert(null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author frankp
|
||||
*
|
||||
*/
|
||||
public class XmlInstanceTest {
|
||||
|
||||
@Test
|
||||
public void testPatter() {
|
||||
|
||||
Pattern methodPattern = Pattern.compile("set\\s(\\w*)\\s*=\\s(\\p{ASCII}*)"); // example
|
||||
|
||||
// String p = "call m1 (paramList, param2 ) ";
|
||||
String p = "set m2 = paramList, param2 ";
|
||||
|
||||
Matcher matcher = methodPattern.matcher(p);
|
||||
|
||||
System.out.println(matcher.groupCount());
|
||||
if (matcher.find()) {
|
||||
|
||||
for (int i = 0; i <= matcher.groupCount(); i++) {
|
||||
|
||||
System.out.println("group: " + i + "-->" + matcher.group(i));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (c) 2008 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part
|
||||
* of this file in any form be copied, printed, edited or otherwise distributed,
|
||||
* be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.data.xmlapi;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author frankp
|
||||
*/
|
||||
public class XmlTemplateTest {
|
||||
|
||||
@Test
|
||||
public void testPrint() {
|
||||
XmlTemplate xmlTemplate = new XmlTemplate("0123");
|
||||
xmlTemplate.execute(null);
|
||||
Assert.assertNotNull(xmlTemplate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.filehandler;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.itac.mes.datainterface.ConfigurationException;
|
||||
import com.itac.mes.datainterface.DataInterfaceConfiguration;
|
||||
import com.itac.mes.datainterface.data.Station;
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.factories.AConfigurableHandler;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
|
||||
public class XmlApiFileHandlerTest {
|
||||
|
||||
@Test
|
||||
public void testSingleInstanceDefaultFileHandler() throws ConfigurationException {
|
||||
DataInterfaceConfiguration configuration = mock(DataInterfaceConfiguration.class);
|
||||
|
||||
String tempDir = System.getProperty("java.io.tmpdir") + File.separator + "junittest";
|
||||
File dr = new File(tempDir);
|
||||
if (dr.mkdir()) {
|
||||
LogHandler.debug("tempdir created");
|
||||
}
|
||||
String s = "filehandler.xmlapi.";
|
||||
when(configuration.getValue(s + "workDir", String.class)).thenReturn(dr.getAbsolutePath());
|
||||
when(configuration.getValue(s + "errorDir", String.class)).thenReturn(dr.getAbsolutePath());
|
||||
when(configuration.getValue(s + "errorPattern", String.class)).thenReturn("{0}");
|
||||
when(configuration.getValue(s + "unprocessedDir", String.class)).thenReturn(dr.getAbsolutePath());
|
||||
when(configuration.getValue(s + "unprocessedPattern", String.class)).thenReturn("{0}");
|
||||
when(configuration.getValue(s + "backupDir", String.class)).thenReturn(dr.getAbsolutePath());
|
||||
when(configuration.getValue(s + "backupPattern", String.class)).thenReturn("{0}");
|
||||
when(configuration.getValue(s + "outputDir", String.class)).thenReturn(dr.getAbsolutePath());
|
||||
when(configuration.getValue(s + "outputPattern", String.class)).thenReturn("{0}");
|
||||
when(configuration.getValue(s + "pass", String.class)).thenReturn("P");
|
||||
when(configuration.getValue(s + "fail", String.class)).thenReturn("FAIL");
|
||||
when(configuration.getValue(s + "backupLevel", Integer.class)).thenReturn(DefaultFileHandler.BACKUP_NONE);
|
||||
when(configuration.getValue(s + "workDirClean", Boolean.class)).thenReturn(false);
|
||||
|
||||
Toolbox toolbox = mock(Toolbox.class);
|
||||
|
||||
when(toolbox.getLayer("TOP")).thenReturn(0);
|
||||
when(toolbox.getStation("myStation")).thenReturn(new Station("myStation", "01012010", false));
|
||||
when(toolbox.getStatus("good")).thenReturn(0);
|
||||
when(toolbox.getStatus("fail")).thenReturn(1);
|
||||
|
||||
XmlApiFileHandler dfh = new XmlApiFileHandler();
|
||||
|
||||
assertNotNull(dfh);
|
||||
|
||||
dfh.setHandler(configuration, DataInterfaceConfiguration.class);
|
||||
dfh.setHandler(toolbox, Toolbox.class);
|
||||
dfh.callAtInit();
|
||||
dfh.configure();
|
||||
|
||||
assertEquals(AConfigurableHandler.OK, dfh.getConfigurationResult());
|
||||
assertEquals("", dfh.getConfigurationText());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Node;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlCondition;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlConstruct;
|
||||
|
||||
public class AssertionParserTest {
|
||||
|
||||
private Node getNode(String text) throws SAXException, IOException, ParserConfigurationException {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
InputSource is = new InputSource(new StringReader(text));
|
||||
Document document = builder.parse(is);
|
||||
return document.getDocumentElement();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseAssertion() throws SAXException, IOException, ParserConfigurationException {
|
||||
AssertionParser out = new AssertionParser(AssertionParser.ASSERT, new Toolbox());
|
||||
try {
|
||||
out.parse(getNode("<assert id=\"unique\" />"));
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals("missing attribute 'condition' for element 'assert'", e.getMessage());
|
||||
}
|
||||
try {
|
||||
out.parse(getNode("<assert id=\"unique\" condition=\"unique\"/>"));
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals("missing attribute 'test' for element 'assert'", e.getMessage());
|
||||
}
|
||||
try {
|
||||
out.parse(getNode("<assert id=\"unique\" condition=\"unique\" test=\"\" />"));
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals("attribute 'test' for element 'assert' is null or empty", e.getMessage());
|
||||
}
|
||||
try {
|
||||
out.parse(getNode("<assert id=\"unique\" condition=\"unique\" test=\"abc\" />"));
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals("Assertion construct wrong:\n 'condition' (unique) is an invalid value; allowed "
|
||||
+ "conditions are 'less,greater,equal,lessEqual,greaterEqual,notEqual,isRegExp,exists,notExists,in'\n", e.getMessage());
|
||||
}
|
||||
try {
|
||||
XmlConstruct construct = out.parse(getNode("<assert id=\"unique\" condition=\"in\" test=\"abc\" />"));
|
||||
Assert.assertNull("case 11", construct);
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals("missing attribute 'expected' for element 'assert'", e.getMessage());
|
||||
}
|
||||
try {
|
||||
XmlConstruct construct = out.parse(getNode("<assert id=\"unique\" condition=\"in\" test=\"abc\" />"));
|
||||
Assert.assertNull("case 12", construct);
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals("missing attribute 'expected' for element 'assert'", e.getMessage());
|
||||
}
|
||||
try {
|
||||
XmlConstruct construct = out.parse(getNode("<assert id=\"unique\" condition=\"" + XmlCondition.EXISTS.getText()
|
||||
+ "\" test=\"abc\" />"));
|
||||
Assert.assertNull("case 13", construct);
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals("attribute 'test' is not a variable for element 'assert'", e.getMessage());
|
||||
}
|
||||
try {
|
||||
XmlConstruct construct = out.parse(getNode("<assert id=\"unique\" condition=\"" + XmlCondition.NOTEXISTS.getText()
|
||||
+ "\" test=\"abc\" />"));
|
||||
Assert.assertNull("case 13b", construct);
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals("attribute 'test' is not a variable for element 'assert'", e.getMessage());
|
||||
}
|
||||
try {
|
||||
out.parse(getNode("<assert id=\"unique\" condition=\"" + XmlCondition.NOTEXISTS.getText() + "\" test=\"$abc\" />"));
|
||||
} catch (Exception e) {
|
||||
Assert.fail("case 13c");
|
||||
}
|
||||
try {
|
||||
out.parse(getNode("<assert id=\"unique\" condition=\"" + XmlCondition.NOTEXISTS.getText() + "\" test=\"$abc\" />"));
|
||||
} catch (Exception e) {
|
||||
Assert.fail("case 13d");
|
||||
}
|
||||
|
||||
try {
|
||||
XmlConstruct construct = out.parse(getNode("<assert id=\"unique\" condition=\"in\" test=\"abc\" />"));
|
||||
Assert.assertNull("case14", construct);
|
||||
} catch (Exception e) {
|
||||
Assert.assertEquals("missing attribute 'expected' for element 'assert'", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* Copyright (c) 2008 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.parser.xmlapi;
|
||||
|
||||
import static com.itac.util.PropertyNames.PROP_ITAC_APPID;
|
||||
|
||||
import java.io.StringReader;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.xml.sax.InputSource;
|
||||
|
||||
import com.itac.mes.datainterface.data.Toolbox;
|
||||
import com.itac.mes.datainterface.data.xmlapi.XmlApiFunction;
|
||||
import com.itac.util.logging.LogHandler;
|
||||
import com.itac.util.logging.LogLevel;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author frankp
|
||||
*/
|
||||
public class FunctionParserTest {
|
||||
|
||||
private static FunctionParser functionParser;
|
||||
|
||||
public FunctionParserTest() {
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpClass() throws Exception {
|
||||
System.setProperty(PROP_ITAC_APPID, "testid");
|
||||
functionParser = new FunctionParser("ApiFunctionParser", new Toolbox());
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownClass() throws Exception {
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParseImsApiFunction() {
|
||||
// Beispiel: Function =
|
||||
// @ItacMethodDescriptor(argNames={"sessionContext", "stationNumber", "processLayer", "setupFlag", "keyValues",
|
||||
// "setupFilter", "componentFilter"})
|
||||
// public com.itac.mes.imsapi.domain.container.Result_setupGetMaterialSetup
|
||||
// setupGetMaterialSetup(com.itac.mes.imsapi.domain.container.IMSApiSessionContextStruct sessionContext,
|
||||
// String stationNumber, int processLayer, int setupFlag, com.itac.mes.imsapi.domain.container.KeyValue[] keyValues,
|
||||
// String[] setupFilter, String[] componentFilter);
|
||||
// in xml:
|
||||
// <setupGetMaterialSetup stationNumber="01010010" processLayer="1" setupFlag="1">
|
||||
// <keyValues> // parameterName
|
||||
// <KeyValue key="" value=""/>
|
||||
// <KeyValue key="" value=""/>
|
||||
// </keyValues>
|
||||
// <setupfilter>
|
||||
// <String value="abc"/>
|
||||
// <String value="def"/>
|
||||
// </setupfilter>
|
||||
// <componentFilter>
|
||||
// <String value="stu" />
|
||||
// <String value="xyz" />
|
||||
// </componentFilter>
|
||||
// </setupGetMaterialSetup>
|
||||
|
||||
// String xmlString =
|
||||
// "<setupGetMaterialSetup stationNumber=\"01010010\" processLayer=\"1\" setupFlag=\"1\"><keyValues><KeyValue key=\"SERIAL_NUMBER\" value=\"sn1\"/><KeyValue key=\"SERIAL_NUMBER_POS\" value=\"1\"/></keyValues><setupFilter><String value=\"abc\"/><String value=\"def\"/></setupFilter><componentFilter><String value=\"stu\" /><String value=\"xyz\" /></componentFilter></setupGetMaterialSetup>";
|
||||
String xmlString2 = "<getMdaDocuments id=\"unique\" target=\"EWAPI\" stationNr=\"01010010\">" + "<keyValues>"
|
||||
+ "<KeyValuePair name =\"1\" value=\"x\"/>" + "<KeyValuePair name =\"2\" value=\"y\"/>"
|
||||
+ "<KeyValuePair name =\"3\" value=\"z\"/>" + "</keyValues>" + "<mdaDataTypes>"
|
||||
+ "<KeyValuePair name =\"4\" value=\"a\" />" + "<KeyValuePair name =\"5\" value=\"b\" />" + "</mdaDataTypes>"
|
||||
+ "</getMdaDocuments>";
|
||||
|
||||
try {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
InputSource is = new InputSource(new StringReader(xmlString2));
|
||||
Document document = builder.parse(is);
|
||||
|
||||
Node rootNode = document.getDocumentElement();
|
||||
XmlApiFunction k = functionParser.parse(rootNode);
|
||||
|
||||
k.getStructuredArray(document, "KeyValuePair", (Element) rootNode, "keyValues");
|
||||
} catch (Exception e) {
|
||||
LogHandler.log(getClass().getSimpleName(), LogLevel.ERROR, "testParseImsApiFunction failed", e);
|
||||
Assert.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* Copyright (c) 2016 iTAC Software AG, Germany. All Rights Reserved.
|
||||
*
|
||||
* This software is protected by copyright. Under no circumstances may any part of this file in any form be copied,
|
||||
* printed, edited or otherwise distributed, be stored in a retrieval system, or be translated into another language
|
||||
* without the written permission of iTAC Software AG.
|
||||
*/
|
||||
package com.itac.mes.datainterface.simulation;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.itac.mes.datainterface.data.smt.PlacementRecipePattern;
|
||||
|
||||
/**
|
||||
* @author frankp
|
||||
*
|
||||
*/
|
||||
public class DefaultMachineSimulationTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
String patternString = "PRODUCT({search=.*_(.*_.*)_.*},{replace=$1})";
|
||||
|
||||
DefaultMachineSimulation testee = new DefaultMachineSimulation() {};
|
||||
PlacementRecipePattern pattern = testee.getPlacementRecipeReplacePattern(patternString);
|
||||
assertNotNull(pattern);
|
||||
|
||||
assertEquals(".*_(.*_.*)_.*", pattern.getSearchPattern());
|
||||
assertEquals("$1", pattern.getReplacePattern());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAutoTrim() {
|
||||
String patternString = "PRODUCT({ search=.*_(.*_.*)_.*} , {replace=$1})";
|
||||
|
||||
DefaultMachineSimulation testee = new DefaultMachineSimulation() {};
|
||||
PlacementRecipePattern pattern = testee.getPlacementRecipeReplacePattern(patternString);
|
||||
assertNotNull(pattern);
|
||||
|
||||
assertEquals(".*_(.*_.*)_.*", pattern.getSearchPattern());
|
||||
assertEquals("$1", pattern.getReplacePattern());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithParenthesis() {
|
||||
String patternString = "PRODUCT({search=.*_{.*_.*}_.*},{replace=${.}1})";
|
||||
|
||||
DefaultMachineSimulation testee = new DefaultMachineSimulation() {};
|
||||
PlacementRecipePattern pattern = testee.getPlacementRecipeReplacePattern(patternString);
|
||||
assertNotNull(pattern);
|
||||
|
||||
assertEquals(".*_{.*_.*}_.*", pattern.getSearchPattern());
|
||||
assertEquals("${.}1", pattern.getReplacePattern());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithParenthesisSimpleVersion() {
|
||||
String patternString = "PRODUCT(search=.*_{.*_.*}_.*,replace=${.}1)";
|
||||
|
||||
DefaultMachineSimulation testee = new DefaultMachineSimulation() {};
|
||||
PlacementRecipePattern pattern = testee.getPlacementRecipeReplacePattern(patternString);
|
||||
assertNotNull(pattern);
|
||||
|
||||
assertEquals(".*_{.*_.*}_.*", pattern.getSearchPattern());
|
||||
assertEquals("${.}1", pattern.getReplacePattern());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMatchingPar1() {
|
||||
String patternString = "{search=.*_(.*_.*)_.*},{replace=$1})";
|
||||
|
||||
DefaultMachineSimulation testee = new DefaultMachineSimulation() {};
|
||||
String result = testee.matchingParenthesis(patternString);
|
||||
assertEquals("search=.*_(.*_.*)_.*", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMatchingPar2() {
|
||||
// The string itself contains {}
|
||||
String patternString = "{search=.*_{.*_.*}_.*},{replace=$1})";
|
||||
|
||||
DefaultMachineSimulation testee = new DefaultMachineSimulation() {};
|
||||
String result = testee.matchingParenthesis(patternString);
|
||||
assertEquals("search=.*_{.*_.*}_.*", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMatchingPar3() {
|
||||
String patternString = "{{}}";
|
||||
|
||||
DefaultMachineSimulation testee = new DefaultMachineSimulation() {};
|
||||
String result = testee.matchingParenthesis(patternString);
|
||||
assertEquals("{}", result);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testMatchingPar() {
|
||||
String patternString = "{";
|
||||
|
||||
DefaultMachineSimulation testee = new DefaultMachineSimulation() {};
|
||||
testee.matchingParenthesis(patternString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMatchingPar4() {
|
||||
String patternString = " {s}";
|
||||
|
||||
DefaultMachineSimulation testee = new DefaultMachineSimulation() {};
|
||||
String result = testee.matchingParenthesis(patternString);
|
||||
assertEquals("s", result);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testMatchingParNull() {
|
||||
DefaultMachineSimulation testee = new DefaultMachineSimulation() {};
|
||||
testee.matchingParenthesis(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMatchingParEmptyString() {
|
||||
String patternString = "";
|
||||
|
||||
DefaultMachineSimulation testee = new DefaultMachineSimulation() {};
|
||||
String result = testee.matchingParenthesis(patternString);
|
||||
assertEquals("", result);
|
||||
}}
|
||||
Reference in New Issue
Block a user