diff --git a/Klausuren/Sd1/2021winter/Solve/pom.xml b/Klausuren/Sd1/2021winter/Solve/pom.xml index 82d6a05bdcbb19d96f6449f8a755d763d405db04..ff72469de4e9fff7c3070aa8293ab6ccd97e3eab 100644 --- a/Klausuren/Sd1/2021winter/Solve/pom.xml +++ b/Klausuren/Sd1/2021winter/Solve/pom.xml @@ -34,7 +34,7 @@ <dependency> <groupId>de.hdm_stuttgart.mi.exam</groupId> <artifactId>unitmarking</artifactId> - <version>1.2</version> + <version>1.3</version> </dependency> </dependencies> diff --git a/Klausuren/Sd1/2021winter/Solve/src/main/java/de/hdm_stuttgart/mi/sd1/task2/SquarePolynom.java b/Klausuren/Sd1/2021winter/Solve/src/main/java/de/hdm_stuttgart/mi/sd1/task2/SquarePolynom.java index 519f934e3a54ac9abf7b2104ab3a80c80db653be..ea75d6df36b6765925624639345e9c9711f43446 100644 --- a/Klausuren/Sd1/2021winter/Solve/src/main/java/de/hdm_stuttgart/mi/sd1/task2/SquarePolynom.java +++ b/Klausuren/Sd1/2021winter/Solve/src/main/java/de/hdm_stuttgart/mi/sd1/task2/SquarePolynom.java @@ -29,7 +29,7 @@ public class SquarePolynom { * @param x The argument i.e. x = 3.0 * @return Returning e.g. \( a \cdot 3.0^2 + b \cdot 3.0 + c\) for \( x = 3.0 \). */ - public double get(double x) { + public double get(double x) { return x * (a * x + b) + c; // Horner's scheme } diff --git a/Klausuren/Sd1/2021winter/Solve/src/test/java/de/hdm_stuttgart/mi/sd1/ignore_me/ObjectWrapper.java b/Klausuren/Sd1/2021winter/Solve/src/test/java/de/hdm_stuttgart/mi/sd1/ignore_me/ObjectWrapper.java deleted file mode 100644 index 1ed49868d156121e9a440e00ebb2d03dc56988c0..0000000000000000000000000000000000000000 --- a/Klausuren/Sd1/2021winter/Solve/src/test/java/de/hdm_stuttgart/mi/sd1/ignore_me/ObjectWrapper.java +++ /dev/null @@ -1,270 +0,0 @@ -package de.hdm_stuttgart.mi.sd1.ignore_me; - -import org.junit.Assert; - -import java.lang.reflect.*; -import java.util.Arrays; -import java.util.StringJoiner; -import java.util.stream.Collectors; - -public class ObjectWrapper<T> { - - private final Class classz; - private final T instance; - - static public void assertFinal(final Class classZ, final String fieldName) { - try { - final int modifier = classZ.getDeclaredField(fieldName).getModifiers(); - Assert.assertTrue("»" + fieldName + "« can be modified, no immutable!", Modifier.isFinal(modifier)); - - } catch (NoSuchFieldException e) { - Assert.fail("No such field »" + fieldName + "«"); - } - } - - public ObjectWrapper(final Class<T> classz, final Object ... parameter) { - this.classz = classz; - T tmpInstance = null; - final Constructor<?>[] candidates = Arrays. - stream(classz.getDeclaredConstructors()). - filter(c -> matchesArgumentList(c, parameter)). - toArray(Constructor<?>[]::new); - if (0 == candidates.length) { - Assert.fail("No suitable constructor in class »" + classz.getName() + "« matching arguments »(" + - Arrays.stream(parameter).map(Object::toString).collect(Collectors.joining(", ")) + - ")«"); - } else if (1 < candidates.length) { - Assert.fail("Multiple constructor matches due to ambiguous signature"); - } else { - try { - tmpInstance = (T) candidates[0].newInstance( - Arrays.stream(parameter).toArray()); - } catch (final IllegalAccessException e) { - Assert.fail("Unable to instantiate instance of class »" + classz.getName() + "«:\n" + - "Cannot access constructor " + candidates[0].toString()); - } catch (Exception e) { - Assert.fail("Unable to instantiate instance of class »" + classz.getName() + "«:\n "+ e); - } - } - instance = tmpInstance; - } - - public ObjectWrapper(final Class<T> classz, final Class<? extends Throwable> expectedException, final Object ... parameter) { - this.classz = classz; - T tmpInstance = null; - final Constructor<?>[] candidates = Arrays. - stream(classz.getConstructors()). - filter(c -> matchesArgumentList(c, parameter)). - toArray(Constructor<?>[]::new); - if (0 == candidates.length) { - Assert.fail("No suitable constructor in class »" + classz.getName() + "« matching arguments »(" + - Arrays.stream(parameter).map(Object::toString).collect(Collectors.joining(", ")) + - ")«"); - } else if (1 < candidates.length) { - Assert.fail("Multiple constructor matches due to ambiguous signature"); - } else { - try { - tmpInstance = (T) candidates[0].newInstance( - Arrays.stream(parameter).toArray()); - Assert.fail("Expected exception of type »" + expectedException.getName() + "« to be thrown"); - } catch (InstantiationException|IllegalAccessException|IllegalArgumentException|InvocationTargetException e) { - if (e.getCause().getClass() != expectedException) { - Assert.fail("Unable to instantiate: " + e + ", cause:\n Expected exception of type »" + - expectedException.getName() + "« but was »"+ e.getCause().getClass().getName() + "«"); - } - } - } - instance = tmpInstance; - } - - public <R> void assertFieldExists(final Class<R> valueType, final String name) { - try { - final Field field = classz.getField(name); - if (!valueType.equals(field.getType())) { - Assert.fail("Field »" + name + "« in class »" + classz.getName() + "« is not of type »" + - valueType.getName() + "«"); - } - } catch (final NoSuchFieldException e) { - Assert.fail("No such field »" + name + "« in class »" + classz.getName() + "«"); - } - } - - public <R> R get(final Class<R> valueType, final String name) { - - try { - final Field field = classz.getField(name); - if (valueType.equals(field.getType())) { - return (R) field.get(instance); - } else { - Assert.fail("Field »" + name + "« in class »" + classz.getName() + "« is not of type »" + - valueType.getName() + "«"); - } - } catch (final NoSuchFieldException e) { - Assert.fail("No such field »" + name + "« in class »" + classz.getName() + "«"); - } catch (final IllegalAccessException e) { - Assert.fail("Unable to access field »" + name + "« in class »" + classz.getName() + "«: " + e.getMessage()); - } - return null; - } - public void set(final String name, final Object value) { - - try { - final Field field = classz.getField(name); - final Class argumentType = value.getClass(); - if (field.getType().equals(argumentType) || - field.getType().equals(getPrimitiveType(argumentType))){ - field.set(instance, value); - } else { - Assert.fail("Field »" + name + "« in class »" + classz.getName() + "« is not of type »" + - argumentType.getName() + "«"); - } - } catch (final NoSuchFieldException e) { - Assert.fail("No such field »" + name + "« in class »" + classz.getName() + "«"); - } catch (final IllegalAccessException e) { - Assert.fail("Unable to access field »" + name + "« in class »" + classz.getName() + "«: " + e.getMessage()); - } - } - - public <R> R invoke(final Class<R> returnType, final String name, final Object ... parameter) { - - final Method[] candidates = Arrays. - stream(classz.getDeclaredMethods()). - filter(m-> m.getName().equals(name) && matchesArgumentList(m, parameter)). - toArray(Method[]::new); - - if (0 == candidates.length) { - Assert.fail("No suitable method " + getSignature(returnType, name, parameter) + - " found"); - } else if (1 < candidates.length) { - Assert.fail("Multiple method matches due to ambiguous signature"); - } else { - final Method method = candidates[0]; - if (method.getReturnType().equals(returnType)) { - try { - return (R) method.invoke(instance, parameter); - } catch (final IllegalAccessException e) { - Assert.fail("Unable to execute existing method: »" + method.toString() + "«"); - }catch (final IllegalArgumentException|InvocationTargetException e) { - Assert.fail("Unable to execute existing method: »" + method.toString() + "«\n" + - e + ", cause:" + e.getCause()); - } - } else { - Assert.fail("Method »" + method.getName() + "« does have return type »" + method.getReturnType() + "«" + - "rather then »" + returnType.getName() + "«"); - } - } - return null; - } - - private <R> StringBuilder getSignature(final Class<R> returnType, final String name, final Object ... parameter) { - - final StringBuilder ret = new StringBuilder(); - appendType(returnType, ret); - - return ret.append(' ').append(name).append('(') - .append(Arrays.stream(parameter).map(this::appendObjectsType).collect(Collectors.joining(", "))) - .append(')'); - } - - private StringBuilder appendObjectsType (final Object object) { - final StringBuilder builder = new StringBuilder(); - if (null == object) { - builder.append("null"); - } else { - appendType(object.getClass(), builder); - } - return builder; - } - - private <R> void appendType(final Class<R> type, StringBuilder result) { - - if (type.isArray()) { - final Class <?> componentType = type.getComponentType(); - result.append(componentType.getName()).append("[]"); - } else { - result.append(type.getName()); - } - } - - public <R> R invoke(final Class<R> returnType, final String name, - final Class<? extends Throwable> expectedException, final Object ... parameter) { - - final Method[] candidates = Arrays. - stream(classz.getMethods()). - filter(m-> m.getName().equals(name) && matchesArgumentList(m, parameter)). - toArray(Method[]::new); - - if (0 == candidates.length) { - Assert.fail("No suitable method found"); - } else if (1 < candidates.length) { - Assert.fail("Multiple method matches due to ambiguous signature"); - } else { - final Method method = candidates[0]; - if (method.getReturnType().equals(returnType)) { - try { - R ret = (R) method.invoke(instance, parameter); - Assert.fail("Expected exception of type »" + expectedException.getName() + "«"); - return ret; - } catch (final IllegalAccessException| IllegalArgumentException|InvocationTargetException e) { - if (e.getCause().getClass() != expectedException) { - Assert.fail("Unable to execute method: " + e + ", cause:\n Expected exception of type »" + - expectedException.getName() + "« but was »"+ e.getCause().getClass().getName() + "«"); - } - } - } else { - Assert.fail("Method »" + method.getName() + "« does have return type »" + method.getReturnType() + "«" + - "rather then »" + returnType.getName() + "«"); - } - } - return null; - } - - /** - * Check for a given array of objects matching an {@link Executable}'s argument list. - * - * @param executable - * @param parameter - * @return <code>true</code> if parameters match the {@link Executable}'s argument list, <code>false</code> - * otherwise. - */ - private boolean matchesArgumentList(final Executable executable, final Object ... parameter) { - - if (executable.getParameterCount() != parameter.length) { - return false; - } else { - final Class<?>[] formalArgumentTypes = executable.getParameterTypes(); - for (int i = 0; i < formalArgumentTypes.length; i++) { - final Class parametersClass = parameter[i].getClass(); - - if (!formalArgumentTypes[i].equals(parametersClass) && - !formalArgumentTypes[i].equals(getPrimitiveType(parametersClass))) { - return false; - } - } - } - return true; - } - - static private Class<?> getPrimitiveType (final Class<?> in) { - if (in.equals(Byte.class)) { - return byte.class; - } else if (in.equals(Short.class)) { - return short.class; - } else if (in.equals(Integer.class)) { - return int.class; - } else if (in.equals(Long.class)) { - return long.class; - } else if (in.equals(Float.class)) { - return float.class; - } else if (in.equals(Double.class)) { - return double.class; - } else if (in.equals(Boolean.class)) { - return boolean.class; - } else if (in.equals(Character.class)) { - return char.class; - } else { - return in; // Type is no primitive - } - } - -} diff --git a/Klausuren/Sd1/2021winter/Solve/src/test/java/de/hdm_stuttgart/mi/sd1/task2/TestSquarePolynom.java b/Klausuren/Sd1/2021winter/Solve/src/test/java/de/hdm_stuttgart/mi/sd1/task2/TestSquarePolynom.java index 8c35e0519ab39148637d78a41a21589152818b80..7eb275560b0304d24c4f31b41ec883184b0544f4 100644 --- a/Klausuren/Sd1/2021winter/Solve/src/test/java/de/hdm_stuttgart/mi/sd1/task2/TestSquarePolynom.java +++ b/Klausuren/Sd1/2021winter/Solve/src/test/java/de/hdm_stuttgart/mi/sd1/task2/TestSquarePolynom.java @@ -2,7 +2,7 @@ package de.hdm_stuttgart.mi.sd1.task2; import de.hdm_stuttgart.mi.exam.unitmarking.ExaminationTestDefaults; import de.hdm_stuttgart.mi.exam.unitmarking.Marking; -import de.hdm_stuttgart.mi.sd1.ignore_me.ObjectWrapper; +import de.hdm_stuttgart.mi.exam.unitmarking.reflect.ObjectWrapper; import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Test; diff --git a/ws/Artifacts/Unitmarking/pom.xml b/ws/Artifacts/Unitmarking/pom.xml index 437709fb4fd7536c57c0cd07d38b2ae8ca318a7b..dab3034bff762c4a22e9a50a2529059856f9c722 100644 --- a/ws/Artifacts/Unitmarking/pom.xml +++ b/ws/Artifacts/Unitmarking/pom.xml @@ -4,7 +4,7 @@ <groupId>de.hdm_stuttgart.mi.exam</groupId> <artifactId>unitmarking</artifactId> - <version>1.2</version> + <version>1.3</version> <packaging>jar</packaging> <name>unitmarking</name> @@ -13,7 +13,7 @@ <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <oxygenxml.version>25.0.0.0</oxygenxml.version> + <oxygenxml.version>25.1.0.0</oxygenxml.version> </properties> <distributionManagement> @@ -23,32 +23,12 @@ </repository> </distributionManagement> - <repositories> - - <repository> - <id>oxygenxml-repo</id> - <url>https://maven.mi.hdm-stuttgart.de/nexus/repository/oxygen</url> - </repository> - </repositories> - <dependencies> - <dependency> - <groupId>com.oxygenxml</groupId> - <artifactId>oxygen-patched-xerces</artifactId> - <version>${oxygenxml.version}</version> - </dependency> - - <dependency> - <groupId>com.oxygenxml</groupId> - <artifactId>oxygen</artifactId> - <version>${oxygenxml.version}</version> - </dependency> - <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> - <version>2.19.0</version> + <version>2.20.0</version> </dependency> <dependency> @@ -57,24 +37,6 @@ <version>4.13.2</version> </dependency> - <dependency> - <groupId>com.rackspace.eclipse.webtools.sourceediting</groupId> - <artifactId>org.eclipse.wst.xml.xpath2.processor</artifactId> - <version>2.1.100</version> - </dependency> - - <dependency> - <groupId>org.jdom</groupId> - <artifactId>jdom2</artifactId> - <version>2.0.6.1</version> - </dependency> - - <dependency> - <groupId>jaxen</groupId> - <artifactId>jaxen</artifactId> - <version>1.2.0</version> - </dependency> - </dependencies> <build> @@ -82,7 +44,7 @@ <extension> <groupId>org.apache.maven.wagon</groupId> <artifactId>wagon-ssh-external</artifactId> - <version>3.5.2</version> + <version>3.5.3</version> </extension> </extensions> <plugins> diff --git a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/exam/unitmarking/reflect/ObjectWrapper.java b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/exam/unitmarking/reflect/ObjectWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..2c82e7f88d92905b7378e7248c7a77d22b75ac9f --- /dev/null +++ b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/exam/unitmarking/reflect/ObjectWrapper.java @@ -0,0 +1,282 @@ +package de.hdm_stuttgart.mi.exam.unitmarking.reflect; + +import org.junit.Assert; + +import java.lang.reflect.*; +import java.util.Arrays; +import java.util.stream.Collectors; + +public class ObjectWrapper<T> { + + private final Class<?> classz; + private final T instance; + + static public void assertFinal(final Class<?> classZ, final String fieldName) { + try { + final int modifier = classZ.getDeclaredField(fieldName).getModifiers(); + Assert.assertTrue("»" + fieldName + "« can be modified, no immutable!", Modifier.isFinal(modifier)); + + } catch (NoSuchFieldException e) { + Assert.fail("No such field »" + fieldName + "«"); + } + } + + public <R> void assertFieldExists(final Class<R> valueType, final String name) { + try { + final Field field = classz.getField(name); + if (!valueType.equals(field.getType())) { + Assert.fail("Field »" + name + "« in class »" + classz.getName() + "« is not of type »" + + valueType.getName() + "«"); + } + } catch (final NoSuchFieldException e) { + Assert.fail("No such field »" + name + "« in class »" + classz.getName() + "«"); + } + } + + public <R> R get(final Class<R> valueType, final String name) { + + try { + final Field field = classz.getField(name); + if (valueType.equals(field.getType())) { + return (R) field.get(instance); + } else { + Assert.fail("Field »" + name + "« in class »" + classz.getName() + "« is not of type »" + + valueType.getName() + "«"); + } + } catch (final NoSuchFieldException e) { + Assert.fail("No such field »" + name + "« in class »" + classz.getName() + "«"); + } catch (final IllegalAccessException e) { + Assert.fail("Unable to access field »" + name + "« in class »" + classz.getName() + "«: " + e.getMessage()); + } + return null; + } + public void set(final String name, final Object value) { + + try { + final Field field = classz.getField(name); + final Class<?> argumentType = value.getClass(); + if (field.getType().equals(argumentType) || + field.getType().equals(getPrimitiveType(argumentType))){ + field.set(instance, value); + } else { + Assert.fail("Field »" + name + "« in class »" + classz.getName() + "« is not of type »" + + argumentType.getName() + "«"); + } + } catch (final NoSuchFieldException e) { + Assert.fail("No such field »" + name + "« in class »" + classz.getName() + "«"); + } catch (final IllegalAccessException e) { + Assert.fail("Unable to access field »" + name + "« in class »" + classz.getName() + "«: " + e.getMessage()); + } + } + + private Constructor<T> getConstructor(final Object ... parameter) { + final Constructor<?>[] candidates = Arrays. + stream(classz.getDeclaredConstructors()). + filter(c -> matchesArgumentList(c, parameter)). + toArray(Constructor<?>[]::new); + if (0 == candidates.length) { + Assert.fail("No suitable constructor »" + + getSignature(classz.getSimpleName(), parameter) + "« found"); + } else if (1 < candidates.length) { + Assert.fail("Multiple constructor matches due to ambiguous signature: " + Arrays.toString(candidates)); + } + return (Constructor<T>) candidates[0]; + } + + public ObjectWrapper(final Class<T> classz, final Object ... parameter) { + this.classz = classz; + T tmpInstance = null; + final Constructor<T> constructor = getConstructor(parameter); + try { + tmpInstance = constructor.newInstance( + Arrays.stream(parameter).toArray()); + } catch (final IllegalAccessException e) { + Assert.fail("Unable to instantiate instance of class »" + classz.getName() + "«:\n" + + "Cannot access constructor " + constructor.toString()); + } catch (final InstantiationException|IllegalArgumentException|InvocationTargetException e) { + Assert.fail("Unable to instantiate instance of class »" + classz.getName() + "«:\n "+ e); + } + instance = tmpInstance; + } + + public ObjectWrapper(final Class<T> classz, final Class<? extends Throwable> expectedException, final Object ... parameter) { + this.classz = classz; + T tmpInstance = null; + final Constructor<T> constructor = getConstructor(parameter); + try { + tmpInstance = (T) constructor.newInstance( + Arrays.stream(parameter).toArray()); + Assert.fail("Expected exception of type »" + expectedException.getName() + "« to be thrown"); + } catch (final InstantiationException|IllegalAccessException|IllegalArgumentException|InvocationTargetException e) { + if (e.getCause().getClass() != expectedException) { + Assert.fail("Unable to instantiate: " + e + ", cause:\n Expected exception of type »" + + expectedException.getName() + "« but was »"+ e.getCause().getClass().getName() + "«"); + } + } + instance = tmpInstance; + } + + private Method getMethod(final Class<?> returnType, final String name, final Object ... parameter) { + + final Method[] candidates = Arrays. + stream(classz.getDeclaredMethods()). + filter(m-> m.getName().equals(name) && matchesArgumentList(m, parameter)). + toArray(Method[]::new); + + if (0 == candidates.length) { + Assert.fail("No suitable method »" + getSignature(returnType, name, parameter) + + "« found"); + } else if (1 < candidates.length) { + Assert.fail("Multiple method matches due to ambiguous signature"); + } + return candidates[0]; + } + + public <R> R invoke(final Class<R> returnType, final String name, final Object ... parameter) { + + final Method method = getMethod(returnType, name, parameter); + if (method.getReturnType().equals(returnType)) { + try { + return (R) method.invoke(instance, parameter); + } catch (final IllegalAccessException e) { + Assert.fail("Unable to access method »" + method.toString() + "«: \n\t" + e.getMessage()); + }catch (final IllegalArgumentException|InvocationTargetException e) { + Assert.fail("Unable to execute method: »" + method.toString() + "«\n" + + e + ", cause:" + e.getCause()); + } + } else { + Assert.fail("Method »" + method.getName() + "« does have return type »" + method.getReturnType() + "«" + + ", expected »" + getSimplifiedTypeName(returnType) + "«"); + } + return null; + } + + public <R> R invoke(final Class<R> returnType, final String name, + final Class<? extends Throwable> expectedException, final Object ... parameter) { + + final Method method = getMethod(returnType, name, parameter); + if (method.getReturnType().equals(returnType)) { + try { + R ret = (R) method.invoke(instance, parameter); + Assert.fail("Expected exception of type »" + expectedException.getName() + "«"); + return ret; + } catch (final IllegalAccessException| IllegalArgumentException|InvocationTargetException e) { + if (e.getCause().getClass() != expectedException) { + Assert.fail("Unable to execute method: " + e + ", cause:\n Expected exception of type »" + + expectedException.getName() + "« but was »"+ e.getCause().getClass().getName() + "«"); + } + } + } else { + Assert.fail("Method »" + method.getName() + "« does have return type »" + method.getReturnType() + "«" + + "rather then »" + returnType.getName() + "«"); + } + return null; + } + + // Constructor use + private StringBuilder getSignature(final String name, final Object ... parameter) { + + final StringBuilder ret = new StringBuilder(classz.getName()).append("::"); + + return ret.append(name).append('(') + .append(Arrays.stream(parameter).map(this::appendObjectsType).collect(Collectors.joining(", "))) + .append(')'); + } + + // Method use + private <R> StringBuilder getSignature(final Class<R> returnType, final String name, final Object ... parameter) { + + return getSignature(name, parameter).insert(0, ' ').insert(0, returnType.getName()); + } + + private StringBuilder appendObjectsType (final Object object) { + final StringBuilder builder = new StringBuilder(); + if (null == object) { + builder.append("null"); + } else { + appendType(object.getClass(), builder); + } + return builder; + } + + static private String getSimplifiedTypeName(final Class<?> classz) { + if (Byte.TYPE == classz) { + return "byte"; + } else if (Short.TYPE == classz) { + return "short"; + } else if (Integer.TYPE == classz) { + return "int"; + } else if (Long.TYPE == classz) { + return "long"; + } else if (Float.TYPE == classz) { + return "float"; + } else if (Double.TYPE == classz) { + return "double"; + } else if (Character.TYPE == classz) { + return "char"; + } else if (Boolean.TYPE == classz) { + return "boolean"; + } else { + return classz.getName(); + } + } + + private <R> void appendType(final Class<R> type, StringBuilder result) { + + if (type.isArray()) { + final Class <?> componentType = type.getComponentType(); + result.append(getSimplifiedTypeName(componentType)).append("[]"); + } else { + result.append(getSimplifiedTypeName(type)); + } + } + + /** + * Check for a given array of objects matching an {@link Executable}'s argument list. + * + * @param executable Method or constructor + * @param parameter List + * @return <code>true</code> if parameters match the {@link Executable}'s argument list, <code>false</code> + * otherwise. + */ + private boolean matchesArgumentList(final Executable executable, final Object ... parameter) { + + if (executable.getParameterCount() != parameter.length) { + return false; + } else { + final Class<?>[] formalArgumentTypes = executable.getParameterTypes(); + for (int i = 0; i < formalArgumentTypes.length; i++) { + final Class<?> parametersClass = parameter[i].getClass(); + + if (!formalArgumentTypes[i].equals(parametersClass) && + !formalArgumentTypes[i].equals(getPrimitiveType(parametersClass))) { + return false; + } + } + } + return true; + } + + static private Class<?> getPrimitiveType (final Class<?> in) { + if (in.equals(Byte.class)) { + return byte.class; + } else if (in.equals(Short.class)) { + return short.class; + } else if (in.equals(Integer.class)) { + return int.class; + } else if (in.equals(Long.class)) { + return long.class; + } else if (in.equals(Float.class)) { + return float.class; + } else if (in.equals(Double.class)) { + return double.class; + } else if (in.equals(Boolean.class)) { + return boolean.class; + } else if (in.equals(Character.class)) { + return char.class; + } else { + return in; // Type is no primitive + } + } + +} diff --git a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/exam/unitmarking/xml/WellformedCheckHandler.java b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/exam/unitmarking/xml/WellformedCheckHandler.java deleted file mode 100644 index 65d5e1786cd168fcfe75c14523dd194aa7d971bc..0000000000000000000000000000000000000000 --- a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/exam/unitmarking/xml/WellformedCheckHandler.java +++ /dev/null @@ -1,38 +0,0 @@ -package de.hdm_stuttgart.mi.exam.unitmarking.xml; - -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.DefaultHandler; - -import java.util.List; -import java.util.Vector; -import java.util.stream.Collectors; - -public class WellformedCheckHandler extends DefaultHandler { - - private List<SAXParseException> problems = new Vector<>(); - - @Override - public void warning(SAXParseException e) throws SAXException { - problems.add(e); - } - - @Override - public void error(SAXParseException e) throws SAXException { - problems.add(e); - } - - @Override - public void fatalError(SAXParseException e) throws SAXException { - problems.add(e); - } - - public String formatErrorMessages() { - return problems.stream().map(s -> "line=" + s.getLineNumber() + - ", column=" + s.getColumnNumber() + ":\n " + s.getMessage()). - collect(Collectors.joining("\n ")); - } - public void clear() { - problems.clear(); - } -} \ No newline at end of file diff --git a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/exam/unitmarking/xml/XmlTestSupport.java b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/exam/unitmarking/xml/XmlTestSupport.java deleted file mode 100644 index 0634376c5a523fc465e2269733a7ddd7d9eb807e..0000000000000000000000000000000000000000 --- a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/exam/unitmarking/xml/XmlTestSupport.java +++ /dev/null @@ -1,215 +0,0 @@ -package de.hdm_stuttgart.mi.exam.unitmarking.xml; - -import org.apache.xerces.impl.Constants; -import org.junit.Assert; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.DefaultHandler; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; - -public class XmlTestSupport { - - /** - * <p>The XML Schema namespace as being defined in - * https://www.w3.org/TR/xmlschema-1/#Instance_Document_Constructions.</p> - */ - static public final String - xmlns_xsi = "http://www.w3.org/2001/XMLSchema-instance", - /** - * <p>The schema reference attribute name, see {@link #xmlns_xsi} for explanation.</p> - */ - noNamespaceSchemaLocationAttributeName = "noNamespaceSchemaLocation"; - - // XMLConstants only provides W3C_XML_SCHEMA_NS_URI rather than XSD-1.1; - static private final SchemaFactory schemaFactory = SchemaFactory.newInstance( - Constants.W3C_XML_SCHEMA11_NS_URI); - private final DocumentBuilder validatingBuilder, nonValidatingBuilder; - - /** - * The directory containing schema unit tests. - */ - public final String testDirectoryPathname; - - /** - * Unit test support for schema unit tests. - * - * @param testDirectoryPathname see {@link #testDirectoryPathname} - */ - public XmlTestSupport(final String testDirectoryPathname) { - this.testDirectoryPathname = testDirectoryPathname; - final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder validatingBuilderTmp = null, nonValidatingBuilderTmp = null; - try { - factory.setNamespaceAware(true); - factory.setXIncludeAware(true); - - factory.setValidating(false); - nonValidatingBuilderTmp = factory.newDocumentBuilder(); - nonValidatingBuilderTmp.setErrorHandler(new DefaultHandler()); - - factory.setValidating(true); - validatingBuilderTmp = factory.newDocumentBuilder(); - validatingBuilderTmp.setErrorHandler(new DefaultHandler()); - - } catch (ParserConfigurationException e) { - Assert.fail("Unable to create non-validating parser:" + e); - } finally { - nonValidatingBuilder = nonValidatingBuilderTmp; - validatingBuilder = validatingBuilderTmp; - } - } - - /** - * Assert whether or not the given instance is valid. - * - * @param instanceFilename The XML instance containing an XML schema reference to be handled. - * @param expectValidInstance A value of true of false will cause the assertion to fail in case the instance is - * invalid or valid respectively. - */ - private void assertExpectedValidationStatus(final String instanceFilename, final boolean expectValidInstance) { - - final Path instancePath = Paths.get(testDirectoryPathname, instanceFilename).normalize(); - - final Attr schemaPathNameAttr = parseWellFormed( // Schema reference found? - instancePath).getAttributeNodeNS(xmlns_xsi, noNamespaceSchemaLocationAttributeName); - - Assert.assertNotNull( // Oops, no schema! - "No schema provided by attribute " + noNamespaceSchemaLocationAttributeName - + " from namespace\n" + xmlns_xsi + " in file " + getClickableFileName(instanceFilename, 1), - schemaPathNameAttr); - - final Path schemaPath = Paths.get( - instancePath.getParent().toString(), // Strip filename from path, - schemaPathNameAttr.getValue()).normalize(); // add relative schema path - - parseWellFormed(schemaPath); // Schema is well-formed? - final Path xmlSchemaPath = Paths.get("src/main/resources/XMLSchema.xsd"); - validate(schemaPath, xmlSchemaPath, true);// Schema valid with respect to XML schema standard ? - validate(instancePath, schemaPath, expectValidInstance); // Instance valid or invalid with respect to given XML schema ? - } - - /** - * <p>Assert a given instance to be valid. The following steps will be evaluated:</p> - * - * <ol> - * <li> - * <p>Check instance for well-formedness</p> - * <p>Possible failure: Instnce may not be well-formed.</p> - * </li> - * <li> - * <p>Get the associated schema using the instance's {@link #noNamespaceSchemaLocationAttributeName} - * * attribute value.</p> - * <p>Possible failures:</p> - * <ul> - * <li>Missing attribute or wrong namespace</li> - * <li>Missing or wrong attribute value not being resolvable to an XML Schema.</li> - * </ul> - * </li> - * <li> - * <p>Check the associated schema to be well-formed.</p> - * <p>Possible failure: The schema may not be well-formed.</p> - * </li> - * <li> - * <p>Check the associated schema itself to be valid with respect to - * * <a href="https://www.w3.org/TR/xmlschema-1/#normative-schemaSchema">A Schema for Schemas</a>.</p> - * <p>Possible failure: The schema may not be well-formed.</p> - * </li> - * <li id="valid2schema"> - * <p>Check the instance for validity with respect to the associated schema.</p> - * <p>Possible failure: The instance may not be valid.</p> - * </li> - * </ol> - * - * <p>Any negative outcome will result in a test failure.</p> - * - * @param instanceFilename The instance to be examined. - */ - public void assertValid(final String instanceFilename) { - assertExpectedValidationStatus(instanceFilename, true); - } - - /** - * <p>Similar to {@link #assertValid(String)} except for the <a href="#valid2schema">very last step</a> being - * expected to fail.</p> - * - * @param instanceFilename The instance to be examined. - */ - public void assertInvalid(final String instanceFilename) { - assertExpectedValidationStatus(instanceFilename, false); - } - - void validate(final Path instancePath, final Path schemaPath, final boolean expectValidInstance) { - - final String instanceFilename = instancePath.getFileName().toString(); - - try { - - // Weird: Caching validators by schema for re-use fails - // on xs:ID attributes on repeated parsing! - // So always re-create! - final Document schemaDoc = validatingBuilder.parse(schemaPath.toFile()); - final Validator validator = schemaFactory.newSchema(new DOMSource(schemaDoc)).newValidator(); - validator.setFeature("http://apache.org/xml/features/validation/schema", true); - validator.setFeature("http://apache.org/xml/features/validation/assert-comments-and-pi-checking", true); - validator.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); - validator.setFeature("http://apache.org/xml/features/honour-all-schemaLocations", true); - - validator.validate( // Re-do parsing: Starting from DOMSource(root) - new StreamSource(instancePath.toFile())); // conceals line numbers, sigh! - if (!expectValidInstance) { - Assert.fail("Instance " + getClickableFileName(instanceFilename, 1) + " is supposed to be invalid"); - } - } catch (final SAXParseException e) { - if (expectValidInstance) { - Assert.fail("Instance " + getClickableFileName(instanceFilename, e.getLineNumber()) + - " is invalid:\n" + format(e) + "\n"); - } - } catch (final SAXException e) { - if (expectValidInstance) { - Assert.fail("Instance " + instanceFilename + " is NOT valid reason:" + e + "\n"); - } - } catch (final IOException e) { - Assert.fail("Unable to read " + instanceFilename + ": " + e + "\n"); - } - } - - private Element parseWellFormed(final Path instancePath) { - try { - return nonValidatingBuilder.parse( - instancePath.toFile()).getDocumentElement(); - } catch (final SAXParseException e) { - Assert.fail("Unable to parse " + instancePath.toString() + - ":\n " + getClickableFileName(instancePath.getFileName().toString(), e.getLineNumber()) + ")\n" + - format(e) + "\nDocument possibly not well-formed\n"); - } catch (final SAXException e) { - Assert.fail("Unable to parse '" + instancePath + "':\n" + e); - } catch (final IOException e) { - Assert.fail("Unable to read '" + instancePath + "':\n" + e); - } - return null; // Runtime unreachable due to previously either returning or assert based test failure. - } - - static private String format(final SAXParseException e) { - return "line=" + e.getLineNumber() + ", column=" + e.getColumnNumber() + ":\n" + - e.getMessage(); - } - - // See - // https://stackoverflow.com/questions/7930844/is-it-possible-to-have-clickable-class-names-in-console-output-in-intellij - static private String getClickableFileName(final String fileName, final int line) { - return ".(" + fileName + ":" + line + ")"; - } -} \ No newline at end of file diff --git a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/AssertXpathResult.java b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/AssertXpathResult.java deleted file mode 100644 index e3b497e64a7b782d71ea8ee7e2be8199ebc5d226..0000000000000000000000000000000000000000 --- a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/AssertXpathResult.java +++ /dev/null @@ -1,18 +0,0 @@ -package de.hdm_stuttgart.mi.unitmarking.jdom; - -/** - * @author goik - * - */ -public class AssertXpathResult extends AssertionError { - - private static final long serialVersionUID = -1369600480719379445L; - - /** - * @param msg - */ - public AssertXpathResult(String msg) { - super(msg); - } - -} diff --git a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/DomAssert.java b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/DomAssert.java deleted file mode 100644 index 20a88df97e6888cb6c5578e00af8d68b5b016881..0000000000000000000000000000000000000000 --- a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/DomAssert.java +++ /dev/null @@ -1,83 +0,0 @@ -package de.hdm_stuttgart.mi.unitmarking.jdom; - -import java.util.List; - -import org.jdom2.Element; -import org.jdom2.xpath.XPathExpression; -import org.jdom2.xpath.XPathFactory; - -/** - * Helper methods for analyzing XML result documents - * - */ -public class DomAssert { - - final static XPathFactory xpf = XPathFactory.instance(); - - /** - * A given XPath expression is being evaluated for returning an expected number of element nodes - * - * @param msg An informative text explaining an error's cause. - * @param context XPath evaluation will start from this node - * @param xpath - * @param expectedNodeCount - */ - public static void assertNumberOfNodes(final String msg, final Element context, - final String xpath, int expectedNodeCount) { - - @SuppressWarnings({ "unchecked", "rawtypes" }) - final XPathExpression<Element> xpathExpr = (XPathExpression<Element>) (XPathExpression) xpf - .compile(xpath); - - final List<Element> matchedNodes = xpathExpr.evaluate(context); - - if (expectedNodeCount != matchedNodes.size()) { - throw new AssertXpathResult(msg + "\nExpected " + expectedNodeCount - + " node" + (expectedNodeCount == 1 ? "" : "s") + " for xpath '" - + xpath + "' but found " + matchedNodes.size()); - } - } - - /** - * A given XPath expression is being evaluated for returning exactly one element node of simple text content - * containing a given text. - * - * @param msg - * @param context - * @param xpath - * @param expectedTagName Will be evaluated unless being set to null - * @param expectedContent Will be evaluated unless being set to null - */ - public static void assertSingleNodeContent(final String msg, - final Element context, final String xpath, final String expectedTagName, - String expectedContent) { - - @SuppressWarnings({ "unchecked", "rawtypes" }) - final XPathExpression<Element> xpathExpr = (XPathExpression<Element>) (XPathExpression) xpf - .compile(xpath); - final List<Element> matchedNodes = xpathExpr.evaluate(context); - - if (1 == matchedNodes.size()) { - final Element element = matchedNodes.get(0); - - if (null != expectedTagName) { - final String actualTagName = element.getName(); - if (!expectedTagName.equals(actualTagName)) { - throw new AssertXpathResult(msg + "\nExpected <" + expectedTagName - + "> for xpath '" + xpath + "' but found <" + actualTagName + ">"); - } - } - if (null != expectedContent) { - final String actualContent = element.getValue(); - if (!expectedContent.equals(actualContent)) { - throw new AssertXpathResult(msg + "\nExpected element content '" - + expectedContent + "' for xpath '" + xpath + "' but found '" - + actualContent + "'"); - } - } - } else { - throw new AssertXpathResult("Exactly node expected for xpath '" + xpath - + "' but found " + matchedNodes.size()); - } - } -} diff --git a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/DomFilter.java b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/DomFilter.java deleted file mode 100644 index bf1aa59d028d8726d26945ad15917e73cfc89497..0000000000000000000000000000000000000000 --- a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/DomFilter.java +++ /dev/null @@ -1,19 +0,0 @@ -package de.hdm_stuttgart.mi.unitmarking.jdom; - -import org.jdom2.Document; - -/** - * Transform a given Dom Tree - * - */ -public interface DomFilter { - - /** - * transform DOM input to output - * - * @param input Input DOM tree - * @return output DOM tree - */ - public Document process(final Document input); - -} diff --git a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/DomFilterTest.java b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/DomFilterTest.java deleted file mode 100644 index e2de875a93e8f5326c121220ce7f467f1ea700d3..0000000000000000000000000000000000000000 --- a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/jdom/DomFilterTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package de.hdm_stuttgart.mi.unitmarking.jdom; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintStream; - -import org.jdom2.Document; -import org.jdom2.Element; -import org.jdom2.JDOMException; -import org.jdom2.input.SAXBuilder; -import org.jdom2.output.Format; -import org.jdom2.output.XMLOutputter; - -public abstract class DomFilterTest { - - public static String xmlInputFileName, xmlOutputFileName; - static DomFilter domFilter; - protected static String initializationErrorString = null; - - protected static Element xmlRootElement = null; - - static protected void init (final String xmlInputFileName, - final DomFilter domFilter, - final String resultFileExtension) { - DomFilterTest.xmlInputFileName = xmlInputFileName; - DomFilterTest.xmlOutputFileName = xmlInputFileName + resultFileExtension; - DomFilterTest.domFilter = domFilter; - processAndParseResult(); - } - - static protected void processAndParseResult() { - - final SAXBuilder builder = new SAXBuilder(); - final Document input; - try { - input = builder.build(xmlInputFileName); - } catch (JDOMException | IOException e) { - initializationErrorString = "Error parsing input:" + e.getLocalizedMessage(); - return; - } - - final PrintStream out; - try { - out = new PrintStream(xmlOutputFileName); - } catch (FileNotFoundException e1) { - initializationErrorString = "Unable to open result file '" + xmlOutputFileName - + "' for writing"; - return; - } - - // Print to file - final Document result = domFilter.process(input); - xmlRootElement = result.getRootElement(); - final Format outFormat = Format.getPrettyFormat(); - final XMLOutputter printer = new XMLOutputter(outFormat); - try { - printer.output(result, out); - } catch (IOException e) { - initializationErrorString = "Error serializing result document to file '" + xmlOutputFileName + "': " + e.getLocalizedMessage(); - return; - } - // Print to standard out as well - try { - printer.output(result, System.out); - } catch (IOException e) { - initializationErrorString = "Error serializing result document to standard output: " + e.getLocalizedMessage(); - } - } -} diff --git a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/CreateTestClass.java b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/CreateTestClass.java deleted file mode 100644 index ec8c8fd62ae27c4be940e3fbdfdcbc172fb08251..0000000000000000000000000000000000000000 --- a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/CreateTestClass.java +++ /dev/null @@ -1,85 +0,0 @@ -package de.hdm_stuttgart.mi.unitmarking.xsd; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jdom2.Document; -import org.jdom2.JDOMException; -import org.jdom2.ProcessingInstruction; -import org.jdom2.filter.Filters; -import org.jdom2.input.SAXBuilder; -import org.jdom2.input.sax.XMLReaders; -import org.jdom2.xpath.XPathExpression; -import org.jdom2.xpath.XPathFactory; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -/** - * Evaluate a given set of XML document instances - * - */ -class CreateTestClass { - - private static Logger log = LogManager.getLogger(CreateTestClass.class); - private final String xmlTestFileDir; - - /** - * - * @param xmlTestFileDir Directory containing XML instances to be processed. - */ - CreateTestClass(final String xmlTestFileDir) { - - this.xmlTestFileDir = xmlTestFileDir; - - System.out.println("private final XmlTestSupport xmlTestSupport = new XmlTestSupport(\""+ - xmlTestFileDir +"\");\n"); - - Arrays.stream(new File(xmlTestFileDir).listFiles(path -> path.getPath().endsWith(".xml"))). - sorted(Comparator.comparing(File::toString)). - forEach(this::readTestHeader); - } - - private void readTestHeader(final File instanceFilename) { - - final List<ProcessingInstruction> xmlTestList = InstanceSetEvaluation.getProcessingInstructions(instanceFilename); - - switch (xmlTestList.size()) { - case 0: - log.info("No 'xmlTest PI found, possible dependency file"); - break; - case 1: - writeTest(instanceFilename.getName(), xmlTestList.get(0)); - break; - default: - log.info("Found " + xmlTestList.size() + "' annotations in file '" + instanceFilename.getPath() + "'\n"); - } - } - - private void writeTest(final String fileName, final ProcessingInstruction pi) { - - final int points = Integer.parseInt(pi.getPseudoAttributeValue("points")); - final boolean expectedToBeValid = Boolean.parseBoolean(pi.getPseudoAttributeValue("expectedToBeValid")); - - System.out.println("@Test @Marking(points = " + points + ")"); - - final String fileBaseName = fileName.replaceFirst("[.][^.]+$", ""); - System.out.println("public void test_" + fileBaseName + "() {"); - - - if (expectedToBeValid) { - System.out.println(" xmlTestSupport.assertValid(\"" + fileName + "\");"); - } else { - System.out.println(" xmlTestSupport.assertInvalid(\"" + fileName + "\");"); - } - - final String preconditionValidFilename = pi.getPseudoAttributeValue("preconditionValid"); - - if (null != preconditionValidFilename) { - System.out.println(" xmlTestSupport.assertValid(\"" + preconditionValidFilename + "\");"); - } - System.out.println("}\n"); - } -} diff --git a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/GenerateUnitTestClass.java b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/GenerateUnitTestClass.java deleted file mode 100644 index d6abbda96cacea7234a1e6a773b4fe0d308fcb87..0000000000000000000000000000000000000000 --- a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/GenerateUnitTestClass.java +++ /dev/null @@ -1,14 +0,0 @@ -package de.hdm_stuttgart.mi.unitmarking.xsd; - - -/** - * Hack: Should be copied avoiding versioning problems. - */ -public class GenerateUnitTestClass { - - public static void main(String[] args) { - - final CreateTestClass create = - new CreateTestClass("SchemaTest"); - } -} diff --git a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/InstanceSetEvaluation.java b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/InstanceSetEvaluation.java deleted file mode 100644 index 45d80584583fc52a1806ca31cb9649299fd462c8..0000000000000000000000000000000000000000 --- a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/InstanceSetEvaluation.java +++ /dev/null @@ -1,146 +0,0 @@ -package de.hdm_stuttgart.mi.unitmarking.xsd; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Vector; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jdom2.Document; -import org.jdom2.JDOMException; -import org.jdom2.ProcessingInstruction; -import org.jdom2.filter.Filters; -import org.jdom2.input.SAXBuilder; -import org.jdom2.input.sax.XMLReaders; -import org.jdom2.xpath.XPathExpression; -import org.jdom2.xpath.XPathFactory; - -/** - * Evaluate a given set of XML document instances - * - */ -public class InstanceSetEvaluation { - - /** - * Base directory containing xml test file instances. - */ - public final String xmlTestFileDir; - - /** - * true if all tests have been successful. - */ - public final boolean allTestsSucceeded; - - private static Logger log = LogManager.getLogger(InstanceSetEvaluation.class); - - final static List<InstanceTest> tests = new Vector<>(); - final static StringBuffer warnings = new StringBuffer(); - - final StringBuffer messages = new StringBuffer(), errorMessages = new StringBuffer(); - - /** - * Read the list of all processing instructions (PIs) of a given XML file. - * - * @param instanceFilename The xml source to be searched for PIs. - * @return The list of all PIs. - * - */ - static public List<ProcessingInstruction> getProcessingInstructions(final File instanceFilename) { - final SAXBuilder metainfoParser = new SAXBuilder(XMLReaders.NONVALIDATING); - try { - final Document doc = metainfoParser.build(instanceFilename); - - final XPathExpression<ProcessingInstruction> searchHeader = - XPathFactory.instance().compile( - "/processing-instruction('xmlTest')", - Filters.processinginstruction()); - return searchHeader.evaluate(doc); - } catch (final JDOMException e) { - log.error("Document '" + instanceFilename.getPath() + - "' is invalid:", e); - warnings.append("Unable to parse document " + instanceFilename.getPath() + ": " + e + "\n"); - } catch (final IOException e) { - warnings.append("Unable to read document " + instanceFilename.getPath() + ": " + e + "\n"); - } - return new ArrayList<>(); - } - - /** - * @return Individual failed test(s) error message(s). - */ - public String getErrorMessages() { - return errorMessages.toString(); - } - - /** - * @return Individual test's and aggregated results. - */ - public String getMessages() { - return "\n" + warnings.toString() + "\n" + messages.toString(); - } - - /** - * - * @param xmlTestFileDir Directory containing XML instances to be processed. - * @param xsdSchemaFilename Schema defining validation rules. - */ - public InstanceSetEvaluation(final String xmlTestFileDir, final String xsdSchemaFilename) { - this.xmlTestFileDir = xmlTestFileDir; - - final File rootDirectory = new File(xmlTestFileDir); - - final File[] xmlFiles = rootDirectory.listFiles( - path -> path.getPath().endsWith(".xml")); - - Arrays.sort(xmlFiles); - - for (final File f: xmlFiles) { - readTestHeader(f, xsdSchemaFilename); - } - - tests.forEach(t -> messages.append(t + "\n")); - tests.stream().filter(t -> !t.testSucceeded).forEach(t -> errorMessages.append(t + "\n")); - - allTestsSucceeded = tests. - stream(). - map(t -> t.testSucceeded). - reduce((a, b) -> a && b). - get(); - - final int maxPoints, reachedPoints; - { - int tmpMaxPoints = 0, tmpReachedPoints = 0; - - for (final InstanceTest t: tests) { - tmpMaxPoints += t.reachablePoints; - if (t.testSucceeded) { - tmpReachedPoints += t.reachablePoints; - } - } - maxPoints = tmpMaxPoints; - reachedPoints = tmpReachedPoints; - } - - messages.append(reachedPoints + " of " + maxPoints + - " points have been reached"); - } - - void readTestHeader(final File instanceFilename, final String xsdSchemaFilename) { - - final List<ProcessingInstruction> xmlTestList = getProcessingInstructions(instanceFilename); - - switch (xmlTestList.size()) { - case 0: - log.info("No 'xmlTest PI found, possible dependency file"); - break; - case 1: - tests.add(new InstanceTest(xmlTestList.get(0), xmlTestFileDir, xsdSchemaFilename, instanceFilename)); - break; - default: - warnings.append("Found " + xmlTestList.size() + "' annotations in file '" + instanceFilename.getPath() + "'\n"); - } - } -} \ No newline at end of file diff --git a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/InstanceTest.java b/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/InstanceTest.java deleted file mode 100644 index 11e0bf683dfa31d369c02a206404fc48e1765720..0000000000000000000000000000000000000000 --- a/ws/Artifacts/Unitmarking/src/main/java/de/hdm_stuttgart/mi/unitmarking/xsd/InstanceTest.java +++ /dev/null @@ -1,178 +0,0 @@ -package de.hdm_stuttgart.mi.unitmarking.xsd; - -import java.io.File; -import java.io.IOException; -import java.util.Optional; - -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jdom2.ProcessingInstruction; -import org.jdom2.input.SAXBuilder; -import org.jdom2.input.sax.XMLReaderSAX2Factory; -import org.jdom2.input.sax.XMLReaders; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -/** - * Test and evaluate an individual XML instance. - * - */ -public class InstanceTest { - - private static Logger log = LogManager.getLogger(InstanceTest.class); - - final SAXBuilder parser = new SAXBuilder(XMLReaders.XSDVALIDATING); - final SAXBuilder b = new SAXBuilder(new XMLReaderSAX2Factory(false)); - final File instanceFilename; - - /** - * An examinee may reach this number of point. The value is being defined in - * the corresponding XML instance's PI like e.g.: - * - * <?xmlTest - points = "2" ... ?> - * - */ - public final int reachablePoints; - - /** - * Is this instance expected to be valid or not? The value is being defined in - * the corresponding XML instance's PI like e.g.: - * - * <?xmlTest expectedToBeValid= "false" ... ?> - */ - public final boolean expectedToBeValid; - /** - * Does the current instance test succeed? - */ - public final boolean testSucceeded; - - /** - * Error message in case of unexpected behavior e.g. - * when an invalid instance is supposed to be valid. - */ - public final Optional<String> errMsg; - - @Override - public String toString() { - - final String result = reachablePoints + ((1 == reachablePoints) ? " point." : " points."); - if (testSucceeded) { - return "++ " + instanceFilename + ": Gaining " + result ; - } else { - return "--" + errMsg.get() + " Missing " + result; - } - } - - /** - * Testing an individual instance to be either valid or invalid. - * - * @param xmlTest The PI meta annotation header containing the expected - * result, points etc. - * @param xmlTestFileDir The directory containing the XML instance files. - * @param xsdSchemaFilename The schema to be used for validation. - * @param xmlInstance The current instance to be evaluated. - */ - public InstanceTest(final ProcessingInstruction xmlTest, - final String xmlTestFileDir, final String xsdSchemaFilename, final File xmlInstance) { - Validator validator = null; - - final SchemaFactory sf = SchemaFactory.newInstance( - "http://www.w3.org/XML/XMLSchema/v1.1"); - - Schema s; - try { - s = sf.newSchema (new File(xsdSchemaFilename)); - validator = s.newValidator(); - } catch (final SAXParseException e) { - System.err.println(getErrorDescription(e)); - System.exit(1); - } catch (SAXException e) { - System.err.println(getErrorDescription(e, xsdSchemaFilename)); - System.exit(1); - } - - this.instanceFilename = xmlInstance; - - if (null == xmlTest.getPseudoAttributeValue("points")) { - log.fatal("Mandatory <?xmlTest points='...' ... ?> is missing in file '" - + xmlInstance + "'"); - System.exit(1); - } - reachablePoints = Integer.parseInt(xmlTest.getPseudoAttributeValue("points")); - - if (null == xmlTest.getPseudoAttributeValue("expectedToBeValid")) { - log.fatal("Mandatory <?xmlTest expectedToBeValid='true|false' ... ?> is missing in file '" + xmlInstance + "'"); - System.exit(1); - } - expectedToBeValid = Boolean.parseBoolean(xmlTest.getPseudoAttributeValue("expectedToBeValid")); - - final Optional<String> preconditionValidFilename; - - boolean preconditionSucceeded = false; - String tmpPreconditionErrMsg = null; - - if (null == xmlTest.getPseudoAttributeValue("preconditionValid")) { - preconditionValidFilename = Optional.empty(); - } else { - preconditionValidFilename = Optional.of(xmlTestFileDir + File.separator + - xmlTest.getPseudoAttributeValue("preconditionValid")); - try { - validator.validate(new StreamSource(new File(preconditionValidFilename.get()))); - - log.info("Precondition file '" + preconditionValidFilename.get() + "' is valid"); - preconditionSucceeded = true; - } catch (final SAXException e) { - tmpPreconditionErrMsg = " " + xmlInstance + - ":\n Precondition file »" + preconditionValidFilename.get() + "« is invalid:\n " + - e.getMessage() + "\n "; - log.info(tmpPreconditionErrMsg + ": " + e.getCause() + ":" + e.getMessage()); - } catch (final IOException e) { - tmpPreconditionErrMsg = " " + xmlInstance + ": Precondition file '" + preconditionValidFilename.get() + "' cannot be read:" + e.getMessage(); - log.info(tmpPreconditionErrMsg, e); - } - } - - if (!preconditionValidFilename.isPresent() || preconditionSucceeded) { - boolean tmpInstanceIsValid = false; - try { - validator.validate(new StreamSource(xmlInstance)); - - tmpInstanceIsValid = true; - } catch (final SAXException e) { - log.info(" " + xmlInstance + " is invalid:" + e.getMessage()); - } catch (final IOException e) { - log.info(" " + xmlInstance + " cannot be read:" + e.getMessage()); - } - testSucceeded = expectedToBeValid == tmpInstanceIsValid; - if (testSucceeded) { - errMsg = Optional.empty(); - } else if (expectedToBeValid) { - errMsg = Optional.of(" " + xmlInstance + - " is expected to be valid!"); - } else { - errMsg = Optional.of(" " + xmlInstance + - " is expected to be invalid!"); - } - } else { - testSucceeded = false; - errMsg = Optional.of(tmpPreconditionErrMsg); - - } - } - static String getErrorDescription(final SAXParseException e) { - return "Your schema cannot be parsed:\n" + - e.getSystemId() + ", line " + e.getLineNumber() + ", column " + e.getLineNumber() + ": " + e.getLocalizedMessage() + - "\nThis may indicate your document is not well-formed\n\nAborting!\n\n\n"; - } - static String getErrorDescription(final SAXException e, final String fileName) { - return "Your schema " + fileName + " cannot be parsed:\n" + - e.getLocalizedMessage() + - "\nAre you using non-standard features?\n\nAborting!\n\n\n"; - } -}