Testat 3b und experimentelle sichere Ausführung für Testat 3a

This commit is contained in:
2025-08-26 17:37:34 +02:00
parent 4a2d0ccd6f
commit 74e22ec5b2
22 changed files with 2973 additions and 378 deletions
+123 -122
View File
@@ -9,136 +9,137 @@ import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFram
public class Tests {
@Test(name = "Stack - add - size - 15")
public void testStackAdd() {
int points = 0;
@Test(name = "Stack - add - size - 15")
public void testStackAdd() {
int points = 0;
Stack stack = new Stack();
int size = stack.size();
if (size != 0) {
TracingFramework.printError("A new Stack should have size 0 but was " + size);
} else {
points += 3;
}
Stack stack = new Stack();
int size = stack.size();
if (size != 0) {
TracingFramework.printError("A new Stack should have size 0 but was " + size);
} else {
points += 3;
}
try {
stack.addToTop("A");
size = stack.size();
if (size != 1) {
TracingFramework.printError("addToTop(\"A\") should add one element to the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(\"A\") should not throw an Exception. " + e.getClass().getName());
}
try {
stack.addToTop("A");
size = stack.size();
if (size != 1) {
TracingFramework.printError("addToTop(\"A\") should add one element to the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(\"A\") should not throw an Exception. " + e.getClass().getName());
}
try {
stack.addToTop(null);
size = stack.size();
if (size != 1) {
TracingFramework.printError("addToTop(null) should not change the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(null) should not throw an Exception. " + e.getClass().getName());
}
try {
stack.addToTop(null);
size = stack.size();
if (size != 1) {
TracingFramework.printError("addToTop(null) should not change the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(null) should not throw an Exception. " + e.getClass().getName());
}
try {
stack.addToTop("B");
size = stack.size();
if (size != 2) {
TracingFramework.printError("addToTop(\"B\") should add one element to the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(\"B\") should not throw an Exception. " + e.getClass().getName());
}
try {
stack.addToTop("B");
size = stack.size();
if (size != 2) {
TracingFramework.printError("addToTop(\"B\") should add one element to the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(\"B\") should not throw an Exception. " + e.getClass().getName());
}
try {
stack.addToTop("");
size = stack.size();
if (size != 2) {
TracingFramework.printError("addToTop(\"\") should not add elements to the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(\"\") should not throw an Exception. " + e.getClass().getName());
}
try {
stack.addToTop("");
size = stack.size();
if (size != 2) {
TracingFramework.printError("addToTop(\"\") should not add elements to the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(\"\") should not throw an Exception. " + e.getClass().getName());
}
addPoints(points);
}
addPoints(points);
}
@Test(name = "Stack - remove - 5")
public void testStackRemove() {
int points = 0;
@Test(name = "Stack - remove - 5")
public void testStackRemove() {
int points = 0;
Stack stack = new Stack();
try {
String value = stack.removeFromTop();
if (value == null) {
points += 5;
} else {
points += 2;
TracingFramework
.printError("removeFromTop from empty stack should return null, but was: \"" + value + "\"");
}
} catch (Exception e) {
TracingFramework
.printError("removeFromTop from empty stack should not throw an Exception. " + e.getClass().getName());
Stack stack = new Stack();
try {
String value = stack.removeFromTop();
if (value == null) {
points += 5;
} else {
points += 2;
TracingFramework
.printError("removeFromTop from empty stack should return null, but was: \"" + value + "\"");
}
} catch (Exception e) {
TracingFramework
.printError(
"removeFromTop from empty stack should not throw an Exception. " + e.getClass().getName());
}
addPoints(points);
}
}
addPoints(points);
}
@Test(name = "Stack - add - remove - size - 30")
public void testStack() {
int points = 0;
Stack stack = new Stack();
stack.addToTop("A");
stack.addToTop("B");
stack.addToTop("C");
String value = stack.removeFromTop();
int size = stack.size();
if (size == 2) {
points += 5;
} else {
TracingFramework.printError("A stack with 2 elements should have size 2 but was " + size);
}
if ("C".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove top of A,B,C should return C but was " + value);
}
value = stack.removeFromTop();
size = stack.size();
if (size == 1) {
points += 5;
} else {
TracingFramework.printError("A stack with 1 element should have size 1 but was " + size);
}
if ("B".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove top of A,B should return B but was " + value);
}
value = stack.removeFromTop();
size = stack.size();
if (size == 0) {
points += 5;
} else {
TracingFramework.printError("A stack with 0 elements should have size 0 but was " + size);
}
if ("A".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove top of A should return A but was " + value);
}
addPoints(points);
}
@Test(name = "Stack - add - remove - size - 30")
public void testStack() {
int points = 0;
Stack stack = new Stack();
stack.addToTop("A");
stack.addToTop("B");
stack.addToTop("C");
String value = stack.removeFromTop();
int size = stack.size();
if (size == 2) {
points += 5;
} else {
TracingFramework.printError("A stack with 2 elements should have size 2 but was " + size);
}
if ("C".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove top of A,B,C should return C but was " + value);
}
value = stack.removeFromTop();
size = stack.size();
if (size == 1) {
points += 5;
} else {
TracingFramework.printError("A stack with 1 element should have size 1 but was " + size);
}
if ("B".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove top of A,B should return B but was " + value);
}
value = stack.removeFromTop();
size = stack.size();
if (size == 0) {
points += 5;
} else {
TracingFramework.printError("A stack with 0 elements should have size 0 but was " + size);
}
if ("A".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove top of A should return A but was " + value);
}
addPoints(points);
}
@Test(name = "Tree - traverse - 25")
public void testTreeTraverse() {
@@ -154,8 +155,8 @@ public class Tests {
if (Arrays.equals(actual, expect)) {
points += 25;
} else {
double[] expectSort = expect.clone();
double[] actualSort = actual.clone();
double[] expectSort = expect.clone();
double[] actualSort = actual.clone();
Arrays.sort(expectSort);
Arrays.sort(actualSort);
if (Arrays.equals(expectSort, actualSort)) {
+1 -1
View File
@@ -57,7 +57,7 @@ public class MediaLibrary { // TODO: change
public boolean addItem(MediaItem item) { // TODO: add more checks
// check invalid states
if (item == null) { // Cannot add null item, sorry
return false;
return false;
}
if (items.length == maxItems) { // Cannot add more items to the media library
return false;
+2 -15
View File
@@ -1,30 +1,17 @@
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class InMemoryPathFactory {
private static InMemoryFileSystem fileSystem;
private static final InMemoryFileSystemProvider provider = new InMemoryFileSystemProvider();
private static final InMemoryFileSystem fileSystem = new InMemoryFileSystem(provider);
private InMemoryPathFactory() {
// Utility class - private constructor
}
static {
try {
// Create the in-memory file system
URI uri = URI.create("memory://default/");
Map<String, Object> env = new HashMap<>();
fileSystem = (InMemoryFileSystem) FileSystems.newFileSystem(uri, env);
} catch (IOException e) {
throw new RuntimeException("Failed to create in-memory file system", e);
}
}
/**
* Creates a new in-memory path
*
@@ -2,12 +2,28 @@ import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* Serializes a list of strings to a file and deserializes a list of strings
* from a file.
*/
public class StringListSerializer {
/**
* Writes a list of strings to a file.
*
* @param path the path to the file
* @param list the list of strings to write
*/
public void write(Path path, List<String> list) {
// TODO: implement
}
/**
* Reads a list of strings from a file.
*
* @param path the path to the file
* @return the list of strings read from the file
*/
public List<String> read(Path path) {
// TODO: implement
return new ArrayList<>();
+575 -223
View File
@@ -7,21 +7,31 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test;
public class Tests {
@Test(name = "Aufgabe 1 - Tree - traverse - 20 Punkte")
public void testTreeTraverse() {
Method method = findMethod(Tree.class, "traverse", TreeVisitor.class)
.orElseThrow(() -> new RuntimeException(
"Method Tree.traverse(TreeVisitor) not found. Class was mutated illegally."));
int points = 20;
double[] values = new double[] { 3, 1, 5, 0, 2, 4, 6 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
double[] expect = new double[] { 3, 1, 0, 2, 5, 4, 6 };
TreeVisitor visitor = new TreeVisitor();
tree.traverse(visitor);
if (!safeExecuteVoidMethod(method, tree, visitor)) {
throw new RuntimeException("Method Tree.traverse(TreeVisitor) did not execute successfully.");
}
double[] actual = visitor.toArray();
if (!Arrays.equals(actual, expect)) {
@@ -32,7 +42,8 @@ public class Tests {
if (Arrays.equals(expectSort, actualSort)) {
points -= 10;
TracingFramework.printError(
"Traversal " + Arrays.toString(actual) + " is not pre-order but complete. Deducting 10 points.");
"Traversal " + Arrays.toString(actual)
+ " is not pre-order but complete. Deducting 10 points.");
} else {
points -= 20;
TracingFramework.printError("Traversal " + Arrays.toString(actual) + " is incomplete (no points).");
@@ -42,39 +53,83 @@ public class Tests {
addPoints(points);
}
@Test(name = "Aufgabe 1 - Tree - count - 30 Punkte")
public void testTreeCount() {
int points = 0;
@Test(name = "Aufgabe 1 - Tree - count existing once - 10 Punkte")
public void testTreeCountExisitingOnce() {
Method method = findMethod(Tree.class, "count", double.class)
.orElseThrow(() -> new RuntimeException(
"Method Tree.count(double) not found. Class was mutated illegally."));
int points = 10;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
// 5 should be found once
int count = tree.count(5);
if (count == 1) {
points += 7;
} else {
TracingFramework.printError("Count(5) should return 1 , but was " + count);
// 3 should be found once
Optional<Integer> count = executeMethod(method, tree, Integer.class, 3);
if (count.isEmpty()) {
points -= 10;
TracingFramework.printError("Execution of Tree.count(3) led to an execution. Deducting 10 points.");
} else if (count.get() != 1) {
points -= 10;
TracingFramework.printError("Tree.count(3) should return 1 , but was " + count.get());
}
// 7 should not be found
count = tree.count(7);
if (count == 0) {
points += 8;
} else {
TracingFramework.printError("Count(7) should return 0 , but was " + count);
addPoints(points);
}
@Test(name = "Aufgabe 1 - Tree - count non exisiting - 10 Punkte")
public void testTreeCountNonExisiting() {
Method method = findMethod(Tree.class, "count", double.class)
.orElseThrow(() -> new RuntimeException(
"Method Tree.count(double) not found. Class was mutated illegally."));
int points = 10;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
Optional<Integer> count = executeMethod(method, tree, Integer.class, 7);
if (count.isEmpty()) {
points -= 10;
TracingFramework.printError("Execution of Tree.count(7) led to an execution. Deducting 10 points.");
} else if (count.get() != 0) {
points -= 10;
TracingFramework.printError("Tree.count(7) should return 0 , but was " + count.get());
}
// 1 should only be found 2 (if search is efficient)
count = tree.count(1);
if (count == 2) {
points += 15;
} else if (count == 3) {
points += 8;
TracingFramework.printError("Count(1) should return 2 with efficient implementation, but was " + count);
addPoints(points);
}
@Test(name = "Aufgabe 1 - Tree - count, should find once - 10 Punkte")
public void testTreeCountShouldFindOnce() {
Method method = findMethod(Tree.class, "count", double.class)
.orElseThrow(() -> new RuntimeException(
"Method Tree.count(double) not found. Class was mutated illegally."));
int points = 10;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
Optional<Integer> count = executeMethod(method, tree, Integer.class, 1);
if (count.isEmpty()) {
points -= 10;
TracingFramework.printError("Execution of Tree.count(1) led to an execution. Deducting 10 points.");
} else if (count.get() == 2) {
// correct, to nothing
} else if (count.get() == 3) {
points -= 10;
TracingFramework
.printError("Tree.count(1) should return 2 with efficient implementation, but was " + count);
} else {
TracingFramework.printError("Count(1) should return 2 , but was " + count);
points -= 10;
TracingFramework.printError("Tree.count(1) should return 2 , but was " + count.get());
}
addPoints(points);
@@ -82,28 +137,40 @@ public class Tests {
@Test(name = "Aufgabe 1 - Tree - height - 10 Punkte")
public void testTreeHeight() {
int points = 0;
Method method = findMethod(Tree.class, "height")
.orElseThrow(() -> new RuntimeException(
"Method Tree.height() not found. Class was mutated illegally."));
int points = 10;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
int height = tree.height();
if (height == 3) {
points += 10;
} else {
TracingFramework.printError("Height should return 3 , but was " + height);
}
Optional<Integer> height = executeMethod(method, tree, Integer.class);
if (height.isEmpty()) {
points -= 10;
TracingFramework.printError("Execution of Tree.height() led to an execution. Deducting 10 points.");
} else if (height.get() != 3) {
points -= 10;
TracingFramework.printError("Tree.height() should return 3 , but was " + height.get());
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - IO - write - 10 Punkte")
public void testIOWrite() {
Method method = findMethod(StringListSerializer.class, "write", Path.class, List.class)
.orElseThrow(() -> new RuntimeException(
"Method StringListSerializer.write(Path, List) not found. Class was mutated illegally."));
StringListSerializer serializer = new StringListSerializer();
Path path = InMemoryPathFactory.createPath("/test/write.txt");
List<String> data = Arrays.asList("Hello", "World", "This is a test");
serializer.write(path, data);
if (!safeExecuteVoidMethod(method, serializer, path, data)) {
throw new RuntimeException("Failed to execute StringListSerializer.write(Path, List) method.");
}
int points = 10;
try {
List<String> content = Files.readAllLines(path);
@@ -179,298 +246,457 @@ public class Tests {
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addFirst exception - 5 Punkte")
public void testDequeAddFirst() {
int points = 5;
boolean valid = true;
Deque deque = new Deque();
try {
deque.addFirst("A");
deque.addFirst("BCDEF");
deque.addFirst("Hallo");
} catch (Exception e) {
valid = false;
points -= 5;
@Test(name = "Aufgabe 3 - Deque - addFirst null - 3 Punkte")
public void testDequeAddFirstNull() {
Method method = findMethod(Deque.class, "addFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addFirst(String) not found. Class was mutated illegally."));
int points = 3;
if (addFirstAlwaysException()) {
points -= 3;
TracingFramework.printError(
"Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception: "
+ e.getMessage()
+ ". Assuming method always throws an exception on valid values. Deducting 5 points.");
}
if (valid) {
"Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points.");
} else {
try {
deque.addFirst(null);
Deque deque = new Deque();
executeVoidMethod(method, deque, (Object) null);
points -= 3;
TracingFramework
.printError("Deque.addFirst(null) should throw an exception, but did not. Deducting 2 points.");
points -= 2;
.printError("Deque.addFirst(null) should throw an exception, but did not. Deducting 3 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
TracingFramework
.printError("Deque.addFirst(null) should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be null")) {
points -= 1;
TracingFramework.printError(
"Deque.addFirst(null) should throw an IllegalArgumentException with message 'Value cannot be null', but got: "
+ e.getMessage() + ". Deducting 1 point.");
points -= 1;
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addFirst empty - 3 Punkte")
public void testDequeAddFirstEmpty() {
Method method = findMethod(Deque.class, "addFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addFirst(String) not found. Class was mutated illegally."));
int points = 3;
if (addFirstAlwaysException()) {
points -= 3;
TracingFramework.printError(
"Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points.");
} else {
try {
deque.addFirst("");
Deque deque = new Deque();
executeVoidMethod(method, deque, "");
points -= 3;
TracingFramework
.printError("Deque.addFirst(\"\") should throw an exception, but did not. Deducting 2 points.");
points -= 2;
.printError("Deque.addFirst(\"\") should throw an exception, but did not. Deducting 3 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
TracingFramework
.printError("Deque.addFirst(\"\") should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be empty")) {
points -= 1;
TracingFramework.printError(
"Deque.addFirst(\"\") should throw an IllegalArgumentException with message 'Value cannot be null', but got: "
"Deque.addFirst(\"\") should throw an IllegalArgumentException with message 'Value cannot be empty', but got: "
+ e.getMessage() + ". Deducting 1 point.");
points -= 1;
}
}
}
try {
Method method = Deque.class.getDeclaredMethod("addFirst", String.class);
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
TracingFramework.printError(
"Deque.addFirst(String) should throw an exception, but did not. Deducting 1 point.");
points -= 1;
} else if (exceptionTypes.length != 1) {
TracingFramework.printError("Deque.addFirst(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 1 point.");
points -= 1;
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
TracingFramework.printError(
"Deque.addFirst(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 1 point.");
points -= 1;
}
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.addFirst(String) not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addLast exception - 5 Punkte")
public void testDequeAddLast() {
int points = 5;
boolean valid = true;
Deque deque = new Deque();
try {
deque.addLast("A");
deque.addLast("BCDEF");
deque.addLast("Hallo");
} catch (Exception e) {
valid = false;
points -= 5;
TracingFramework
.printError(
"Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception: "
+ e.getMessage()
+ ". Assuming method always throws an exception on valid values. Deducting 5 points.");
}
if (valid) {
try {
deque.addLast(null);
TracingFramework
.printError("Deque.addLast(null) should throw an exception, but did not. Deducting 2 points.");
@Test(name = "Aufgabe 3 - Deque - addFirst throws IllegalArgumentException - 2 Punkte")
public void testDequeAddFirstThrowsIllegalArgumentException() {
Method method = findMethod(Deque.class, "addFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addFirst(String) not found. Class was mutated illegally."));
int points = 2;
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.addFirst(String) should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.addFirst(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
points -= 2;
TracingFramework.printError(
"Deque.addFirst(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addLast null - 3 Punkte")
public void testDequeAddLastNull() {
Method method = findMethod(Deque.class, "addLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addLast(String) not found. Class was mutated illegally."));
int points = 3;
if (addLastAlwaysException()) {
points -= 3;
TracingFramework.printError(
"Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points.");
} else {
try {
Deque deque = new Deque();
executeVoidMethod(method, deque, (Object) null);
points -= 3;
TracingFramework
.printError("Deque.addLast(null) should throw an exception, but did not. Deducting 3 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
TracingFramework
.printError("Deque.addLast(null) should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
points -= 1;
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be null")) {
points -= 1;
TracingFramework.printError(
"Deque.addLast(null) should throw an IllegalArgumentException with message 'Value cannot be null', but got: "
+ e.getMessage() + ". Deducting 1 point.");
points -= 1;
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addLast empty - 3 Punkte")
public void testDequeAddLastEmpty() {
Method method = findMethod(Deque.class, "addLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addLast(String) not found. Class was mutated illegally."));
int points = 3;
if (addLastAlwaysException()) {
points -= 3;
TracingFramework.printError(
"Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points.");
} else {
try {
deque.addLast("");
Deque deque = new Deque();
executeVoidMethod(method, deque, "");
points -= 3;
TracingFramework
.printError("Deque.addLast(\"\") should throw an exception, but did not. Deducting 2 points.");
points -= 2;
.printError("Deque.addLast(\"\") should throw an exception, but did not. Deducting 3 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
TracingFramework
.printError("Deque.addLast(\"\") should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be empty")) {
points -= 1;
TracingFramework.printError(
"Deque.addLast(\"\") should throw an IllegalArgumentException with message 'Value cannot be null', but got: "
"Deque.addLast(\"\") should throw an IllegalArgumentException with message 'Value cannot be empty', but got: "
+ e.getMessage() + ". Deducting 1 point.");
points -= 1;
}
}
}
try {
Method method = Deque.class.getDeclaredMethod("addLast", String.class);
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
TracingFramework.printError(
"Deque.addLast(String) should throw an exception, but did not. Deducting 1 point.");
points -= 1;
} else if (exceptionTypes.length != 1) {
TracingFramework.printError("Deque.addLast(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 1 point.");
points -= 1;
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
TracingFramework.printError(
"Deque.addLast(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 1 point.");
points -= 1;
}
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.addLast(String) not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getFirst exception - 5 Punkte")
public void testDequeGetFirst() {
int points = 5;
boolean valid = true;
Deque deque = buildDeque("A", "BCDEF", "Hallo");
try {
deque.getFirst();
} catch (Exception e) {
valid = false;
points -= 5;
@Test(name = "Aufgabe 3 - Deque - addLast throws IllegalArgumentException - 2 Punkte")
public void testDequeAddLastThrowsIllegalArgumentException() {
Method method = findMethod(Deque.class, "addLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addLast(String) not found. Class was mutated illegally."));
int points = 2;
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.getFirst() threw an exception: " + e.getMessage()
+ ". Assuming method always throws an exception on none empty deque. Deducting 5 points.");
}
if (valid) {
setFront(deque, null);
setBack(deque, null);
try {
deque.getFirst();
"Deque.addLast(String) should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.addLast(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
points -= 2;
TracingFramework.printError(
"Deque.getFirst() should throw an exception on empty deque, but did not. Deducting 4 points.");
points -= 4;
"Deque.addLast(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getFirst empty exception - 2 Punkte")
public void testDequeGetFirstEmptyDeque() {
Method method = findMethod(Deque.class, "getFirst")
.orElseThrow(() -> new RuntimeException(
"Method Deque.getFirst() not found. Class was mutated illegally."));
int points = 2;
if (getFirstAlwaysException()) {
points -= 2;
TracingFramework.printError(
"Deque.getFirst() threw an exception on Deque with five elements. Assuming method always throws an exception on valid deque. Deducting 2 points.");
} else {
try {
Deque deque = new Deque();
executeMethod(method, deque, String.class, new Object[] {});
points -= 2;
TracingFramework
.printError(
"Deque.getFirst() should throw an exception on empty deque, but did not. Deducting 2 points.");
} catch (Exception e) {
if (!(e instanceof NoSuchElementException)) {
points -= 1;
TracingFramework.printError(
"Deque.getFirst() should throw a NoSuchElementException on empty deque, but threw: "
+ e.getClass().getName() + ". Deducting 2 point.");
points -= 2;
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Deque is empty")) {
points -= 1;
TracingFramework.printError(
"Deque.getFirst() should throw a NoSuchElementException with message 'Deque is empty', but got: "
+ e.getMessage() + ". Deducting 2 points.");
points -= 2;
+ e.getMessage() + ". Deducting 1 point.");
}
}
}
try {
Method method = Deque.class.getDeclaredMethod("getFirst");
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getFirst throws NoSuchElementException - 2 Punkte")
public void testDequeGetFirstThrowsNoSuchElementException() {
Method method = findMethod(Deque.class, "getFirst")
.orElseThrow(() -> new RuntimeException(
"Method Deque.getFirst() not found. Class was mutated illegally."));
int points = 2;
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.getFirst() should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.getFirst() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
points -= 2;
TracingFramework.printError(
"Deque.getFirst() should throw an exception, but did not. Deducting 1 point.");
points -= 1;
} else if (exceptionTypes.length != 1) {
TracingFramework.printError("Deque.getFirst() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 1 point.");
points -= 1;
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
TracingFramework.printError(
"Deque.getFirst() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 1 point.");
points -= 1;
}
"Deque.getFirst() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
} catch (Exception e) {
TracingFramework.printError("Method Deque.getFirst() not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getLast exception - 5 Punkte")
public void testDequeGetLast() {
int points = 5;
boolean valid = true;
Deque deque = buildDeque("A", "BCDEF", "Hallo");
try {
deque.getLast();
} catch (Exception e) {
valid = false;
points -= 5;
@Test(name = "Aufgabe 3 - Deque - getLast empty exception - 2 Punkte")
public void testDequeGetLastEmptyDeque() {
Method method = findMethod(Deque.class, "getLast")
.orElseThrow(() -> new RuntimeException(
"Method Deque.getLast() not found. Class was mutated illegally."));
int points = 2;
if (getLastAlwaysException()) {
points -= 2;
TracingFramework.printError(
"Deque.getLast() threw an exception: " + e.getMessage()
+ ". Assuming method always throws an exception on none empty deque. Deducting 5 points.");
}
if (valid) {
setFront(deque, null);
setBack(deque, null);
"Deque.getLast() threw an exception on Deque with five elements. Assuming method always throws an exception on valid deque. Deducting 2 points.");
} else {
try {
deque.getLast();
TracingFramework.printError(
"Deque.getLast() should throw an exception on empty deque, but did not. Deducting 4 points.");
points -= 4;
Deque deque = new Deque();
executeMethod(method, deque, String.class, new Object[] {});
points -= 2;
TracingFramework
.printError(
"Deque.getLast() should throw an exception on empty deque, but did not. Deducting 2 points.");
} catch (Exception e) {
if (!(e instanceof NoSuchElementException)) {
points -= 1;
TracingFramework.printError(
"Deque.getLast() should throw a NoSuchElementException on empty deque, but threw: "
+ e.getClass().getName() + ". Deducting 2 point.");
points -= 2;
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Deque is empty")) {
points -= 1;
TracingFramework.printError(
"Deque.getLast() should throw a NoSuchElementException with message 'Deque is empty', but got: "
+ e.getMessage() + ". Deducting 2 points.");
points -= 2;
+ e.getMessage() + ". Deducting 1 point.");
}
}
}
try {
Method method = Deque.class.getDeclaredMethod("getLast");
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getLast throws NoSuchElementException - 2 Punkte")
public void testDequeGetLastThrowsNoSuchElementException() {
Method method = findMethod(Deque.class, "getLast")
.orElseThrow(() -> new RuntimeException(
"Method Deque.getLast() not found. Class was mutated illegally."));
int points = 2;
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.getLast() should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.getLast() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
points -= 2;
TracingFramework.printError(
"Deque.getLast() should throw an exception, but did not. Deducting 1 point.");
points -= 1;
} else if (exceptionTypes.length != 1) {
TracingFramework.printError("Deque.getLast() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 1 point.");
points -= 1;
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
TracingFramework.printError(
"Deque.getLast() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 1 point.");
points -= 1;
}
"Deque.getLast() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
} catch (Exception e) {
TracingFramework.printError("Method Deque.getLast() not found. Class was mutated illegally.");
}
addPoints(points);
}
/**
* Checks if addFirst throws any exception when called.
*
* We assume that if any exception is thrown on valid values, it always throws
* an exception.
*
* @return True if addFirst throws any exception, false otherwise.
*/
private boolean addFirstAlwaysException() {
Deque deque = new Deque();
Consumer<String> adder = findConsumer(deque, "addFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addFirst(String) not found. Class was mutated illegally."));
return adderThrowsAnyException(adder, "A", "BCDEF", "Hallo");
}
/**
* Checks if addLast throws any exception when called.
*
* We assume that if any exception is thrown on valid values, it always throws
* an exception.
*
* @return True if addLast throws any exception, false otherwise.
*/
private boolean addLastAlwaysException() {
Deque deque = new Deque();
Consumer<String> adder = findConsumer(deque, "addLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addLast(String) not found. Class was mutated illegally."));
return adderThrowsAnyException(adder, "A", "BCDEF", "Hallo");
}
/**
* Checks if the specified adder method throws any exception when called
* with the given values.
*
* @param adder The adder method to test.
* @param values The values to add.
* @return True if the adder throws any exception, false otherwise.
*/
private boolean adderThrowsAnyException(Consumer<String> adder, String... values) {
try {
for (String value : values) {
adder.accept(value);
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* Checks if getFirst throws any exception when called,
* while the corresponding poller method is called successfully.
*
* We assume that if any exception is thrown on valid values, it always throws
* an exception.
*
* @return True if the getter throws any exception, false otherwise.
*/
private boolean getFirstAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
Supplier<String> getter = findSupplier(deque, "getFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.getFirst() not found. Class was mutated illegally."));
Supplier<String> poller = findSupplier(deque, "pollFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.pollFirst() not found. Class was mutated illegally."));
return getterAnyThrowsException(getter, poller, 5);
}
/**
* Checks if getLast throws any exception when called,
* while the corresponding poller method is called successfully.
*
* We assume that if any exception is thrown on valid values, it always throws
* an exception.
*
* @return True if getLast throws any exception, false otherwise.
*/
private boolean getLastAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
// should be executable five times when deque is not empty
Supplier<String> getter = findSupplier(deque, "getLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.getLast() not found. Class was mutated illegally."));
Supplier<String> poller = findSupplier(deque, "pollLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.pollLast() not found. Class was mutated illegally."));
return getterAnyThrowsException(getter, poller, 5);
}
/**
* Checks if the specified getter method throws any exception when called,
* while the corresponding poller method is called successfully.
*
* @param getter The getter method to test.
* @param poller The poller method to call.
* @param n The number of times to call the methods.
* @return True if the getter throws any exception, false otherwise.
*/
private boolean getterAnyThrowsException(Supplier<String> getter, Supplier<String> poller, int n) {
try {
for (int i = 0; i < n; i++) {
getter.get();
poller.get();
}
} catch (Exception e) {
return true;
}
return false;
}
/**
* Builds a deque from the given values.
*
* @param values The values to add.
* @return The built deque.
*/
public Deque buildDeque(String... values) {
Deque deque = new Deque();
for (String value : values) {
@@ -620,6 +846,132 @@ public class Tests {
}
}
/**
* General utility methods below...
*/
/**
* Finds a method in a class by name and parameter types.
*
* @param clazz The class to search in.
* @param name The name of the method.
* @param parameterTypes The parameter types of the method.
* @return An Optional containing the found method, or empty if not found.
*/
public static Optional<Method> findMethod(Class<?> clazz, String name, Class<?>... parameterTypes) {
try {
return Optional.of(clazz.getDeclaredMethod(name, parameterTypes));
} catch (NoSuchMethodException e) {
return Optional.empty();
}
}
/**
* Checks if a method has a specific return type.
*
* @param method The method to check.
* @param returnType The expected return type.
* @return True if the method has the expected return type, false otherwise.
*/
public static boolean hasReturnType(Method method, Class<?> returnType) {
return method.getReturnType().equals(returnType);
}
public static <T> Optional<T> executeMethod(Method method, Object instance, Class<T> returnType, Object... args) {
try {
Object result = method.invoke(instance, args);
return Optional.of(returnType.cast(result));
} catch (Exception e) {
e.printStackTrace();
return Optional.empty();
}
}
public static void executeVoidMethod(Method method, Object instance, Object... args) throws Exception {
method.invoke(instance, args);
}
public static boolean safeExecuteVoidMethod(Method method, Object instance, Object... args) {
try {
executeVoidMethod(method, instance, args);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* Converts a reference type to its primitive value if applicable.
* If the object is a boxed primitive and the target type is a primitive,
* returns the primitive value. Otherwise, returns the object as is.
*
* @param value The object to convert.
* @param primitiveType The target primitive class (e.g., int.class,
* double.class).
* @return The primitive value or the original object.
*/
public static Object toPrimitiveIfPossible(Object value, Class<?> primitiveType) {
if (value == null) {
return null;
}
if (primitiveType == int.class && value instanceof Integer) {
return ((Integer) value).intValue();
} else if (primitiveType == double.class && value instanceof Double) {
return ((Double) value).doubleValue();
} else if (primitiveType == boolean.class && value instanceof Boolean) {
return ((Boolean) value).booleanValue();
} else if (primitiveType == long.class && value instanceof Long) {
return ((Long) value).longValue();
} else if (primitiveType == float.class && value instanceof Float) {
return ((Float) value).floatValue();
} else if (primitiveType == short.class && value instanceof Short) {
return ((Short) value).shortValue();
} else if (primitiveType == byte.class && value instanceof Byte) {
return ((Byte) value).byteValue();
} else if (primitiveType == char.class && value instanceof Character) {
return ((Character) value).charValue();
}
return value;
}
/**
* Finds a consumer method in a class by name and parameter type.
*
* @param <T> The type of the parameter for the consumer.
* @param obj The object to search in.
* @param methodName The name of the method.
* @param parameterType The parameter type of the method.
* @return An Optional containing the found consumer, or empty if not found.
*/
public static <T> Optional<Consumer<T>> findConsumer(Object obj, String methodName, Class<T> parameterType) {
Optional<Method> method = findMethod(obj.getClass(), methodName, parameterType);
if (method.isEmpty()) {
return Optional.empty();
}
return Optional.of(arg -> safeExecuteVoidMethod(method.get(), obj, toPrimitiveIfPossible(arg, parameterType)));
}
/**
* Finds a supplier method in a class by name and return type.
*
* @param <T> The type of the return value for the supplier.
* @param obj The object to search in.
* @param methodName The name of the method.
* @param returnType The expected return type of the method.
* @return An Optional containing the found supplier, or empty if not found.
*/
public static <T> Optional<Supplier<T>> findSupplier(Object obj, String methodName, Class<T> returnType) {
Optional<Method> method = findMethod(obj.getClass(), methodName);
if (method.isEmpty()) {
return Optional.empty();
}
return Optional.of(() -> {
Optional<T> result = executeMethod(method.get(), obj, returnType);
return result.orElse(null);
});
}
/**
* The points of each test case.
*/
+1 -5
View File
@@ -130,11 +130,7 @@ public class Tree {
* If null, the height is 0.
* @return The height of the subtree, which is the
* number of edges on the longest path from the current node
* to a leaf node. If the subtree is empty, returns 0.
* If the subtree has only one node, returns 1.
* If the subtree has only two nodes, returns 2.
* If the subtree has three nodes, returns 3.
* And so on.
* to a leaf node.
*/
public int height(TreeNode current) {
// TODO: implement
+16 -12
View File
@@ -12,14 +12,14 @@ public class TreeVisitor {
* The list of visited tree nodes.
*/
private List<TreeNode> visited = new ArrayList<>();
/**
* Creates a new visitor with an empty list of nodes.
*/
public TreeVisitor() {
super();
}
/**
* Returns the list with the visited nodes.
*
@@ -28,7 +28,7 @@ public class TreeVisitor {
public List<TreeNode> getVisited() {
return visited;
}
/**
* Visits the tree node and adds it to the list
* of visited nodes.
@@ -38,7 +38,7 @@ public class TreeVisitor {
public void visit(TreeNode node) {
visited.add(node);
}
/**
* Converts the visited node list into an int
* array containing the values of the nodes.
@@ -48,25 +48,29 @@ public class TreeVisitor {
public double[] toArray() {
double[] result = new double[visited.size()];
for (int i = 0; i < result.length; i++) {
//Added null check - otherwise Jack test crash
if(visited.get(i) == null) result[i] = Integer.MAX_VALUE;
else result[i] = visited.get(i).getValue();
// Added null check - otherwise Jack test crash
if (visited.get(i) == null)
result[i] = Integer.MAX_VALUE;
else
result[i] = visited.get(i).getValue();
}
return result;
}
@Override
public String toString() {
String result = "";
for (int i = 0; i < visited.size(); i++) {
//Added null check - otherwise Jack test crash
if(visited.get(i) == null) result += "[NULL]";
else result += visited.get(i).getValue();
// Added null check - otherwise Jack test crash
if (visited.get(i) == null)
result += "[NULL]";
else
result += visited.get(i).getValue();
if (i != visited.size() - 1) {
result += ", ";
}
}
return result;
}
}
+253
View File
@@ -0,0 +1,253 @@
import java.util.NoSuchElementException;
/**
* Represents a double-ended queue (deque) that allows adding and removing items
* from both ends.
*/
public class Deque {
/**
* The front item of the deque.
*/
private Item front;
/**
* The back item of the deque.
*/
private Item back;
/**
* Constructs an empty deque.
*/
public Deque() {
this.front = null;
this.back = null;
}
/**
* Returns the front item in the deque.
*
* @return The front item in the deque.
*/
private Item getFront() {
return front;
}
/**
* Returns the back item in the deque.
*
* @return The back item in the deque.
*/
private Item getBack() {
return back;
}
/**
* Sets the front item in the deque.
*
* @param front The item to set as the front.
*/
private void setFront(Item front) {
this.front = front;
}
/**
* Sets the back item in the deque.
*
* @param back The item to set as the back.
*/
private void setBack(Item back) {
this.back = back;
}
/**
* Adds an item to the front of the deque, if the value is not null or empty.
*
* @param value The value of the item to add.
*/
public void addFirst(String value) { // TODO: change
if (value == null) {
// TODO: change
return;
}
if (value.isEmpty()) {
// TODO: change
return;
}
Item item = new Item(value);
if (isEmpty()) {
setFront(item);
setBack(item);
} else {
item.setNext(getFront());
getFront().setPrev(item);
setFront(item);
}
}
/**
* Adds an item to the back of the deque, if the value is not null or empty.
*
* @param value The value of the item to add.
*/
public void addLast(String value) { // TODO: change
if (value == null) {
// TODO: change
return;
}
if (value.isEmpty()) {
// TODO: change
return;
}
Item item = new Item(value);
if (isEmpty()) {
setFront(item);
setBack(item);
} else {
item.setPrev(getBack());
getBack().setNext(item);
setBack(item);
}
}
/**
* Returns the value of the front item in the deque, or null if the deque is
* empty.
*
* @return The value of the front item in the deque, or null if the deque is
* empty.
*/
public String peekFirst() {
if (isEmpty()) {
return null;
} else {
return getFront().getValue();
}
}
/**
* Returns the value of the back item in the deque, or null if the deque is
* empty.
*
* @return The value of the back item in the deque, or null if the deque is
* empty.
*/
public String peekLast() {
if (isEmpty()) {
return null;
} else {
return getBack().getValue();
}
}
/**
* Removes and returns the front item in the deque, or null if the deque is
* empty.
*
* @return The value of the removed front item, or null if the deque is empty.
*/
public String pollFirst() {
if (isEmpty()) {
return null;
} else {
String value = getFront().getValue();
setFront(getFront().getNext());
if (getFront() == null) {
setBack(null);
}
return value;
}
}
/**
* Removes and returns the back item in the deque, or null if the deque is
* empty.
*
* @return The value of the removed back item, or null if the deque is empty.
*/
public String pollLast() {
if (isEmpty()) {
return null;
} else {
String value = getBack().getValue();
setBack(getBack().getPrev());
if (getBack() == null) {
setFront(null);
} else {
getBack().setNext(null);
}
return value;
}
}
/**
* Returns the value of the first item in the deque, or throws an exception if
* the deque is empty.
*
* @return The value of the first item in the deque.
* @throws NoSuchElementException if the deque is empty.
*/
public String getFirst() { // TODO: change
// TODO: add check
return getFront().getValue();
}
/**
* Returns the value of the last item in the deque, or throws an exception if
* the deque is empty.
*
* @return The value of the last item in the deque.
* @throws NoSuchElementException if the deque is empty.
*/
public String getLast() { // TODO: change
// TODO: add check
return getBack().getValue();
}
/**
* Returns the number of items in the deque.
*
* @return The number of items in the deque.
*/
public int size() {
int count = 0;
Item current = getFront();
while (current != null) {
count++;
current = current.getNext();
}
return count;
}
/**
* Checks if the deque is empty.
*
* @return true if the deque is empty, false otherwise.
*/
public boolean isEmpty() {
return getFront() == null && getBack() == null;
}
/**
* Returns a string representation of the deque.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Item current = getFront();
sb.append("[");
while (current != null) {
sb.append(current.getValue());
current = current.getNext();
if (current != null) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
+154
View File
@@ -0,0 +1,154 @@
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Set;
public class InMemoryByteChannel implements SeekableByteChannel {
private final Path path;
private byte[] data;
private int position = 0;
private boolean isOpen = true;
private final boolean writable;
private final boolean forcedIOException;
public InMemoryByteChannel(Path path, Set<? extends OpenOption> options) {
this.path = path;
this.writable = options.contains(StandardOpenOption.WRITE) ||
options.contains(StandardOpenOption.CREATE) ||
options.contains(StandardOpenOption.CREATE_NEW);
this.forcedIOException = path.toString().contains("forcedIOException");
// Load existing data or create new
byte[] existingData = InMemoryFileSystem.getStorage().get(path.toString());
if (existingData != null) {
this.data = existingData.clone();
} else {
this.data = new byte[0];
}
if (options.contains(StandardOpenOption.TRUNCATE_EXISTING)) {
this.data = new byte[0];
}
if (options.contains(StandardOpenOption.APPEND)) {
this.position = data.length;
}
}
@Override
public int read(ByteBuffer dst) throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
if (forcedIOException) {
throw new IOException("Forced IOException for testing purposes");
}
if (position >= data.length) {
return -1; // EOF
}
int remaining = Math.min(dst.remaining(), data.length - position);
dst.put(data, position, remaining);
position += remaining;
return remaining;
}
@Override
public int write(ByteBuffer src) throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
if (!writable) {
throw new IOException("Channel is not writable");
}
int bytesToWrite = src.remaining();
int newSize = Math.max(data.length, position + bytesToWrite);
if (newSize > data.length) {
byte[] newData = new byte[newSize];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
src.get(data, position, bytesToWrite);
position += bytesToWrite;
return bytesToWrite;
}
@Override
public long position() throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
return position;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
if (newPosition < 0) {
throw new IllegalArgumentException("Position cannot be negative");
}
this.position = (int) newPosition;
return this;
}
@Override
public long size() throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
return data.length;
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
if (!writable) {
throw new IOException("Channel is not writable");
}
if (size < data.length) {
byte[] newData = new byte[(int) size];
System.arraycopy(data, 0, newData, 0, (int) size);
data = newData;
if (position > size) {
position = (int) size;
}
}
return this;
}
@Override
public boolean isOpen() {
return isOpen;
}
@Override
public void close() throws IOException {
if (isOpen && writable) {
// Save data back to storage
InMemoryFileSystem.getStorage().put(path.toString(), data);
}
isOpen = false;
}
}
+88
View File
@@ -0,0 +1,88 @@
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.nio.file.spi.FileSystemProvider;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class InMemoryFileSystem extends FileSystem {
private final String SEPARATOR = "/";
private static final Map<String, byte[]> storage = new ConcurrentHashMap<>();
private final InMemoryFileSystemProvider provider;
private boolean isOpen = true;
public InMemoryFileSystem(InMemoryFileSystemProvider provider) {
this.provider = provider;
}
public static Map<String, byte[]> getStorage() {
return storage;
}
@Override
public FileSystemProvider provider() {
return provider;
}
@Override
public void close() throws IOException {
isOpen = false;
}
@Override
public boolean isOpen() {
return isOpen;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public String getSeparator() {
return SEPARATOR;
}
@Override
public Iterable<Path> getRootDirectories() {
return Collections.singletonList(getPath(SEPARATOR));
}
@Override
public Iterable<FileStore> getFileStores() {
return Collections.emptyList();
}
@Override
public Set<String> supportedFileAttributeViews() {
return Collections.emptySet();
}
@Override
public Path getPath(String first, String... more) {
StringBuilder sb = new StringBuilder(first);
for (String part : more) {
if (!first.endsWith(SEPARATOR) && !part.startsWith(SEPARATOR)) {
sb.append(SEPARATOR);
}
sb.append(part);
}
return new InMemoryPath(this, sb.toString());
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
throw new UnsupportedOperationException();
}
@Override
public UserPrincipalLookupService getUserPrincipalLookupService() {
throw new UnsupportedOperationException();
}
@Override
public WatchService newWatchService() throws IOException {
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,126 @@
import java.io.IOException;
import java.net.URI;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.FileAttributeView;
import java.nio.file.spi.FileSystemProvider;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class InMemoryFileSystemProvider extends FileSystemProvider {
private static final String SCHEME = "memory";
private final Map<String, InMemoryFileSystem> fileSystems = new ConcurrentHashMap<>();
@Override
public String getScheme() {
return SCHEME;
}
@Override
public FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException {
String key = uri.getHost();
if (key == null)
key = "default";
InMemoryFileSystem fs = new InMemoryFileSystem(this);
fileSystems.put(key, fs);
return fs;
}
@Override
public FileSystem getFileSystem(URI uri) {
String key = uri.getHost();
if (key == null)
key = "default";
InMemoryFileSystem fs = fileSystems.get(key);
if (fs == null) {
throw new FileSystemNotFoundException();
}
return fs;
}
@Override
public Path getPath(URI uri) {
return getFileSystem(uri).getPath(uri.getPath());
}
@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs)
throws IOException {
return new InMemoryByteChannel(path, options);
}
@Override
public DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter)
throws IOException {
throw new UnsupportedOperationException("Directory operations not supported");
}
@Override
public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException {
// For simplicity, we'll just track that this directory exists
InMemoryFileSystem.getStorage().put(dir.toString() + "/", new byte[0]);
}
@Override
public void delete(Path path) throws IOException {
if (InMemoryFileSystem.getStorage().remove(path.toString()) == null) {
throw new NoSuchFileException(path.toString());
}
}
@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {
throw new UnsupportedOperationException("Copy operation not supported");
}
@Override
public void move(Path source, Path target, CopyOption... options) throws IOException {
throw new UnsupportedOperationException("Move operation not supported");
}
@Override
public boolean isSameFile(Path path, Path path2) throws IOException {
throw new UnsupportedOperationException("isSameFile not supported");
}
@Override
public boolean isHidden(Path path) throws IOException {
throw new UnsupportedOperationException("Hidden file operations not supported");
}
@Override
public FileStore getFileStore(Path path) throws IOException {
throw new UnsupportedOperationException("FileStore operations not supported");
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
throw new UnsupportedOperationException("Check access not supported");
}
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
throw new UnsupportedOperationException("File attribute views not supported");
}
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options)
throws IOException {
throw new UnsupportedOperationException("File attributes not supported");
}
@Override
public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException {
throw new UnsupportedOperationException("Reading attributes not supported");
}
@Override
public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException {
throw new UnsupportedOperationException("Setting attributes not supported");
}
}
+175
View File
@@ -0,0 +1,175 @@
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchEvent.Modifier;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class InMemoryPath implements Path {
private final InMemoryFileSystem fileSystem;
private final String path;
private static final String SEPARATOR = "/";
public InMemoryPath(InMemoryFileSystem fileSystem, String path) {
this.fileSystem = fileSystem;
this.path = normalizePath(path);
}
private String normalizePath(String path) {
if (path == null || path.isEmpty()) {
return SEPARATOR;
}
if (!path.startsWith(SEPARATOR)) {
path = SEPARATOR + path;
}
return path;
}
@Override
public int compareTo(Path other) {
return this.path.compareTo(other.toString());
}
@Override
public boolean endsWith(Path other) {
return this.path.endsWith(other.toString());
}
@Override
public Path getFileName() {
int lastSeparator = path.lastIndexOf(SEPARATOR);
if (lastSeparator == -1 || lastSeparator == path.length() - 1) {
return this;
}
return new InMemoryPath(fileSystem, path.substring(lastSeparator + 1));
}
@Override
public FileSystem getFileSystem() {
return fileSystem;
}
@Override
public Path getName(int index) {
String[] parts = path.split(SEPARATOR);
if (index < 0 || index >= parts.length) {
throw new IllegalArgumentException("Index out of bounds");
}
return new InMemoryPath(fileSystem, parts[index]);
}
@Override
public int getNameCount() {
if (path.equals(SEPARATOR))
return 0;
return path.split(SEPARATOR).length - 1; // -1 because split on "/" creates empty first element
}
@Override
public Path getParent() {
int lastSeparator = path.lastIndexOf(SEPARATOR);
if (lastSeparator <= 0) {
return null;
}
return new InMemoryPath(fileSystem, path.substring(0, lastSeparator));
}
@Override
public Path getRoot() {
return new InMemoryPath(fileSystem, SEPARATOR);
}
@Override
public boolean isAbsolute() {
return path.startsWith(SEPARATOR);
}
@Override
public Path normalize() {
return this; // Already normalized in constructor
}
@Override
public WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException {
throw new UnsupportedOperationException("Watch service not supported");
}
@Override
public Path relativize(Path other) {
// Simplified implementation
return new InMemoryPath(fileSystem, other.toString());
}
@Override
public Path resolve(Path other) {
if (other.isAbsolute()) {
return other;
}
String resolvedPath = path;
if (!path.endsWith("/")) {
resolvedPath += "/";
}
resolvedPath += other.toString();
return new InMemoryPath(fileSystem, resolvedPath);
}
@Override
public boolean startsWith(Path other) {
return this.path.startsWith(other.toString());
}
@Override
public Path subpath(int beginIndex, int endIndex) {
String[] parts = path.split("/");
if (beginIndex < 0 || endIndex > parts.length - 1 || beginIndex >= endIndex) {
throw new IllegalArgumentException("Invalid indices");
}
StringBuilder sb = new StringBuilder();
for (int i = beginIndex + 1; i <= endIndex; i++) { // +1 because parts[0] is empty
if (!sb.isEmpty())
sb.append("/");
sb.append(parts[i]);
}
return new InMemoryPath(fileSystem, sb.toString());
}
@Override
public Path toAbsolutePath() {
return this; // Already absolute
}
@Override
public Path toRealPath(LinkOption... options) throws IOException {
return this;
}
@Override
public URI toUri() {
return URI.create("memory://default" + path);
}
@Override
public String toString() {
return path;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof InMemoryPath))
return false;
InMemoryPath other = (InMemoryPath) obj;
return path.equals(other.path);
}
@Override
public int hashCode() {
return path.hashCode();
}
}
+63
View File
@@ -0,0 +1,63 @@
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class InMemoryPathFactory {
private static InMemoryFileSystem fileSystem;
private InMemoryPathFactory() {
// Utility class - private constructor
}
static {
try {
// Create the in-memory file system
URI uri = URI.create("memory://default/");
Map<String, Object> env = new HashMap<>();
fileSystem = (InMemoryFileSystem) FileSystems.newFileSystem(uri, env);
} catch (IOException e) {
throw new RuntimeException("Failed to create in-memory file system", e);
}
}
/**
* Creates a new in-memory path
*
* @param path the path string
* @return a InMemoryPath that exists only in memory
*/
public static Path createPath(String path) {
return new InMemoryPath(fileSystem, path);
}
/**
* Gets the in-memory file system instance
*
* @return the file system
*/
public static FileSystem getFileSystem() {
return fileSystem;
}
/**
* Clears all data from the in-memory file system
*/
public static void clear() {
InMemoryFileSystem.getStorage().clear();
}
/**
* Checks if a path exists in memory
*
* @param path the path to check
* @return true if the path exists
*/
public static boolean exists(Path path) {
return InMemoryFileSystem.getStorage().containsKey(path.toString());
}
}
+86
View File
@@ -0,0 +1,86 @@
/**
* Represents an item in a doubly linked deque.
*/
public class Item {
/**
* The value of the item.
*/
private String value;
/**
* The previous item in the deque.
*/
private Item prev;
/**
* The next item in the deque.
*/
private Item next;
/**
* Constructor for creating a new item.
*
* @param value The value of the item.
*/
public Item(String value) {
this.value = value;
this.prev = null;
this.next = null;
}
/**
* Returns the value of the item.
*
* @return The value of the item.
*/
public String getValue() {
return value;
}
/**
* Sets the value of the item.
*
* @param value The value of the item.
*/
public void setValue(String value) {
this.value = value;
}
/**
* Returns the previous item in the deque.
*
* @return The previous item in the deque.
*/
public Item getPrev() {
return prev;
}
/**
* Sets the previous item in the deque.
*
* @param prev The previous item in the deque.
*/
public void setPrev(Item prev) {
this.prev = prev;
}
/**
* Returns the next item in the deque.
*
* @return The next item in the deque.
*/
public Item getNext() {
return next;
}
/**
* Sets the next item in the deque.
*
* @param next The next item in the deque.
*/
public void setNext(Item next) {
this.next = next;
}
}
+127
View File
@@ -0,0 +1,127 @@
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
public class Main {
public static void main(String[] args) {
System.out.println();
System.out.println("=========================================");
System.out.println("Aufgabe 1 - Baum");
System.out.println("=========================================");
System.out.println();
System.out.println("Creating tree with 4 nodes: 2, 1, 3, 1");
Tree tree = new Tree();
tree.insert(2);
tree.insert(1);
tree.insert(3);
tree.insert(1);
TreeVisitor v = new TreeVisitor();
// post-order traversal
tree.traverse(v);
System.out.println("Visiting all nodes in post-order.");
System.out.println("Expected output: [3.0, 1.0, 1.0, 2.0]");
System.out.println("Actual output: " + v);
// count
System.out.println("Node count of 2 should be 1 and was " + tree.count(2));
System.out.println("Node count of 1 should be 2 and was " + tree.count(1));
// height
System.out.println("Height of the tree should be 3 and was " + tree.height());
System.out.println();
System.out.println("=========================================");
System.out.println("Aufgabe 2 - I/O-Serialisierung von Listen");
System.out.println("=========================================");
System.out.println();
// Create a StringListSerializer to test our implementation
StringListSerializer serializer = new StringListSerializer();
Path erlkingPath = InMemoryPathFactory.createPath("/test/erlking.txt");
List<String> erlkingData = Arrays.asList(
"Who rides so late through night and wind?",
"It is the father with his child.",
"He holds the boy tightly in his arms,",
"He holds him safely, he keeps him warm.",
"My son, why do you hide your face so anxiously?",
"Father, do you not see the Erlking?",
"The Erlking with crown and tail?",
"My son, it is a streak of fog.",
"Come, go with me! Many pretty games I play with you;",
"Many colorful flowers are at the shore;",
"My mother has many golden garments.",
"Father, father, do you not hear what the Erlking promises me?",
"Be calm, stay calm, my child;",
"The wind rustles through the dry leaves.",
"Do you not want to come with me?",
"Father, father, do you not see the Erlking's daughter?",
"The Erlking's daughter with her golden garments?",
"My son, my son, I see it clearly:",
"The old willows look so gray and twisted.",
"I love you, I want to play with you,",
"And if you are not willing, I will use force.",
"Father, father, now he has seized me!",
"The Erlking has hurt me!",
"The father shudders, he rides swiftly,",
"He holds in his arms the moaning child,",
"He reaches the farmhouse with great effort;",
"In his arms, the child was dead.",
"- Johann Wolfgang von Goethe, 1782");
// WARNING: Reading depends on writing!
System.out.println("Writing 'Erlking' data to memory path: " + erlkingPath);
serializer.write(erlkingPath, erlkingData);
System.out.println("Wrote 'Erlking' data to memory path.");
System.out.println("");
System.out.println("Reading 'Erlking' data from memory path:");
List<String> erlkingReadData = serializer.read(erlkingPath);
for (String line : erlkingReadData) {
System.out.println(" " + line);
}
System.out.println("");
if (erlkingData.equals(erlkingReadData)) {
System.out.println("Read content matches original content.");
} else {
System.out.println("Read content does NOT match original content.");
}
System.out.println();
System.out.println("=========================================");
System.out.println("Aufgabe 3 - Exceptions");
System.out.println("=========================================");
System.out.println();
Deque deque = new Deque();
// getFirst
System.out.println("Checking if getFirst on empty deque throws NoSuchElementException");
try {
deque.getFirst();
System.out.println("FAILURE: No exception thrown.");
} catch (NoSuchElementException e) {
System.out.println("SUCCESS: NoSuchElementException thrown.");
} catch (Exception e) {
System.out.println("FAILURE: Unexpected exception thrown. Exception thrown: " + e.getClass().getName());
System.out.println(e.getMessage());
}
System.out.println();
// addLast
System.out.println("Checking if addLast(null) throws IllegalArgumentException");
try {
deque.addLast(null);
System.out.println("FAILURE: No exception thrown.");
} catch (IllegalArgumentException e) {
System.out.println("SUCCESS: IllegalArgumentException thrown.");
} catch (Exception e) {
System.out.println("FAILURE: Unexpected exception thrown. Exception thrown: " + e.getClass().getName());
System.out.println(e.getMessage());
}
}
}
@@ -0,0 +1,32 @@
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
/**
* Serializes a list of strings to a file and deserializes a list of strings
* from a file.
*/
public class StringListSerializer {
/**
* Writes a list of strings to a file.
*
* @param path the path to the file
* @param list the list of strings to write
*/
public void write(Path path, List<String> list) {
// TODO: implement
}
/**
* Reads a list of strings from a file.
*
* @param path the path to the file
* @return the list of strings read from the file
*/
public List<String> read(Path path) {
// TODO: implement
return Arrays.asList("Not", "implemented", "yet");
}
}
+819
View File
@@ -0,0 +1,819 @@
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
import java.util.function.Supplier;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test;
public class Tests {
@Test(name = "Aufgabe 1 - Tree - traverse - 20 Punkte")
public void testTreeTraverse() {
int points = 20;
double[] values = new double[] { 3, 5, 1, 6, 4, 2, 0 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
// post-order
double[] expect = new double[] { 6, 4, 5, 2, 0, 1, 3 };
TreeVisitor visitor = new TreeVisitor();
tree.traverse(visitor);
double[] actual = visitor.toArray();
if (!Arrays.equals(actual, expect)) {
double[] expectSort = expect.clone();
double[] actualSort = actual.clone();
Arrays.sort(expectSort);
Arrays.sort(actualSort);
if (Arrays.equals(expectSort, actualSort)) {
points -= 10;
TracingFramework.printError(
"Traversal " + Arrays.toString(actual)
+ " is not post-order but complete. Deducting 10 points.");
} else {
points -= 20;
TracingFramework.printError("Traversal " + Arrays.toString(actual) + " is incomplete (no points).");
}
}
addPoints(points);
}
@Test(name = "Aufgabe 1 - Tree - count - 30 Punkte")
public void testTreeCount() {
int points = 0;
// non-sorted tree
double[] values = new double[] { 3, 5, 1, 1, 4, 2, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
// 5 should be found once
int count = tree.count(5);
if (count == 1) {
points += 7;
} else {
TracingFramework.printError("Count(5) should return 1 , but was " + count);
}
// 7 should not be found
count = tree.count(7);
if (count == 0) {
points += 8;
} else {
TracingFramework.printError("Count(7) should return 0 , but was " + count);
}
// 1 should only be found 2 (if search is efficient)
count = tree.count(1);
if (count == 2) {
points += 15;
} else if (count == 3) {
points += 8;
TracingFramework.printError("Count(1) should return 2 with efficient implementation, but was " + count);
} else {
TracingFramework.printError("Count(1) should return 2 , but was " + count);
}
addPoints(points);
}
@Test(name = "Aufgabe 1 - Tree - height - 10 Punkte")
public void testTreeHeight() {
int points = 0;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
int height = tree.height();
if (height == 3) {
points += 10;
} else {
TracingFramework.printError("Height should return 3 , but was " + height);
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - IO - write - 10 Punkte")
public void testIOWrite() {
StringListSerializer serializer = new StringListSerializer();
Path path = InMemoryPathFactory.createPath("/test/write.txt");
List<String> data = Arrays.asList("Hello", "World", "This is a test");
serializer.write(path, data);
int points = 10;
try {
List<String> content = Files.readAllLines(path);
if (!content.equals(data)) {
points -= 10;
TracingFramework.printError("Written content does not match original content. Deducting 10 points.");
}
} catch (Exception e) {
points -= 10;
TracingFramework.printError("Failed to read written content: " + e.getMessage() + ". Deducting 10 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - IO - read - errorless- 5 Punkte")
public void testIOReadErrorless() {
int points = 5;
StringListSerializer serializer = new StringListSerializer();
Path path = InMemoryPathFactory.createPath("/test/read.txt");
List<String> data = Arrays.asList("Hello", "World", "This is a test");
try {
Files.write(path, data);
} catch (IOException e) {
points -= 5;
e.printStackTrace();
TracingFramework.printError(
"Failed to write test data: " + e.getMessage() + ". Erroneous test. Giving full points.");
addPoints(points);
return;
}
List<String> readData = serializer.read(path);
if (!data.equals(readData)) {
points -= 5;
TracingFramework.printError("Read content does not match original content. Deducting 5 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - IO - read - forced IOException - 5 Punkte")
public void testIOReadForcedIOException() {
int points = 5;
StringListSerializer serializer = new StringListSerializer();
Path path = InMemoryPathFactory.createPath("/test/forcedIOException.txt");
try {
List<String> readData = serializer.read(path);
if (readData == null) {
points -= 5;
TracingFramework.printError(
"Reading from /test/forcedIOException.txt path should return an empty list, but returned null. Deducting 5 points.");
} else if (!readData.isEmpty()) {
points -= 5;
TracingFramework.printError(
"Reading from /test/forcedIOException.txt path should return an empty list, but returned: "
+ readData
+ ". Deducting 5 points.");
}
} catch (Exception e) {
if (e instanceof IOException) {
points -= 5;
TracingFramework.printError(
"Reading from /test/forcedIOException.txt path should process IOException to empty list, but did not. Deducting 5 points.");
} else {
points -= 5;
TracingFramework
.printError("Reading from /test/forcedIOException.txt path throws an unexpected exception: "
+ e.getMessage());
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addFirst null - 2 Punkte")
public void testDequeAddFirstNull() {
int points = 2;
if (addFirstAlwaysException()) {
points -= 2;
TracingFramework.printError(
"Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 2 points.");
} else {
try {
Deque deque = new Deque();
deque.addFirst(null);
points -= 2;
TracingFramework
.printError("Deque.addFirst(null) should throw an exception, but did not. Deducting 2 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
TracingFramework
.printError("Deque.addFirst(null) should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be null")) {
points -= 1;
TracingFramework.printError(
"Deque.addFirst(null) should throw an IllegalArgumentException with message 'Value cannot be null', but got: "
+ e.getMessage() + ". Deducting 1 point.");
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addFirst empty - 2 Punkte")
public void testDequeAddFirstEmpty() {
int points = 2;
if (addFirstAlwaysException()) {
points -= 2;
TracingFramework.printError(
"Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 2 points.");
} else {
try {
Deque deque = new Deque();
deque.addFirst("");
points -= 2;
TracingFramework
.printError("Deque.addFirst(\"\") should throw an exception, but did not. Deducting 2 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
TracingFramework
.printError("Deque.addFirst(\"\") should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be empty")) {
points -= 1;
TracingFramework.printError(
"Deque.addFirst(\"\") should throw an IllegalArgumentException with message 'Value cannot be empty', but got: "
+ e.getMessage() + ". Deducting 1 point.");
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addFirst throws IllegalArgumentException - 2 Punkte")
public void testDequeAddFirstThrowsIllegalArgumentException() {
int points = 2;
try {
Method method = Deque.class.getDeclaredMethod("addFirst", String.class);
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.addFirst(String) should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.addFirst(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
points -= 2;
TracingFramework.printError(
"Deque.addFirst(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.addFirst(String) not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addLast null - 2 Punkte")
public void testDequeAddLastNull() {
int points = 2;
if (addLastAlwaysException()) {
points -= 2;
TracingFramework.printError(
"Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 2 points.");
} else {
try {
Deque deque = new Deque();
deque.addLast(null);
points -= 2;
TracingFramework
.printError("Deque.addLast(null) should throw an exception, but did not. Deducting 2 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
TracingFramework
.printError("Deque.addLast(null) should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be null")) {
points -= 1;
TracingFramework.printError(
"Deque.addLast(null) should throw an IllegalArgumentException with message 'Value cannot be null', but got: "
+ e.getMessage() + ". Deducting 1 point.");
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addLast empty - 2 Punkte")
public void testDequeAddLastEmpty() {
int points = 2;
if (addLastAlwaysException()) {
points -= 2;
TracingFramework.printError(
"Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 2 points.");
} else {
try {
Deque deque = new Deque();
deque.addLast("");
points -= 2;
TracingFramework
.printError("Deque.addLast(\"\") should throw an exception, but did not. Deducting 2 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
TracingFramework
.printError("Deque.addLast(\"\") should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be empty")) {
points -= 1;
TracingFramework.printError(
"Deque.addLast(\"\") should throw an IllegalArgumentException with message 'Value cannot be empty', but got: "
+ e.getMessage() + ". Deducting 1 point.");
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addLast throws IllegalArgumentException - 2 Punkte")
public void testDequeAddLastThrowsIllegalArgumentException() {
int points = 2;
try {
Method method = Deque.class.getDeclaredMethod("addLast", String.class);
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.addLast(String) should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.addLast(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
points -= 2;
TracingFramework.printError(
"Deque.addLast(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.addLast(String) not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getFirst empty exception - 2 Punkte")
public void testDequeGetFirstEmptyDeque() {
int points = 2;
if (getFirstAlwaysException()) {
points -= 2;
TracingFramework.printError(
"Deque.getFirst() threw an exception on Deque with five elements. Assuming method always throws an exception on valid deque. Deducting 2 points.");
} else {
try {
Deque deque = new Deque();
deque.getFirst();
points -= 2;
TracingFramework
.printError(
"Deque.getFirst() should throw an exception on empty deque, but did not. Deducting 2 points.");
} catch (Exception e) {
if (!(e instanceof NoSuchElementException)) {
points -= 1;
TracingFramework.printError(
"Deque.getFirst() should throw a NoSuchElementException on empty deque, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Deque is empty")) {
points -= 1;
TracingFramework.printError(
"Deque.getFirst() should throw a NoSuchElementException with message 'Deque is empty', but got: "
+ e.getMessage() + ". Deducting 1 point.");
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getFirst throws NoSuchElementException - 2 Punkte")
public void testDequeGetFirstThrowsNoSuchElementException() {
int points = 2;
try {
Method method = Deque.class.getDeclaredMethod("getFirst");
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.getFirst() should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.getFirst() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
points -= 2;
TracingFramework.printError(
"Deque.getFirst() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.getFirst() not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getLast empty exception - 2 Punkte")
public void testDequeGetLastEmptyDeque() {
int points = 2;
if (getLastAlwaysException()) {
points -= 2;
TracingFramework.printError(
"Deque.getLast() threw an exception on Deque with five elements. Assuming method always throws an exception on valid deque. Deducting 2 points.");
} else {
try {
Deque deque = new Deque();
deque.getLast();
points -= 2;
TracingFramework
.printError(
"Deque.getLast() should throw an exception on empty deque, but did not. Deducting 2 points.");
} catch (Exception e) {
if (!(e instanceof NoSuchElementException)) {
points -= 1;
TracingFramework.printError(
"Deque.getLast() should throw a NoSuchElementException on empty deque, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Deque is empty")) {
points -= 1;
TracingFramework.printError(
"Deque.getLast() should throw a NoSuchElementException with message 'Deque is empty', but got: "
+ e.getMessage() + ". Deducting 1 point.");
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getLast throws NoSuchElementException - 2 Punkte")
public void testDequeGetLastThrowsNoSuchElementException() {
int points = 2;
try {
Method method = Deque.class.getDeclaredMethod("getLast");
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.getLast() should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.getLast() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
points -= 2;
TracingFramework.printError(
"Deque.getLast() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.getLast() not found. Class was mutated illegally.");
}
addPoints(points);
}
/**
* Checks if addFirst throws any exception when called.
*
* We assume that if any exception is thrown on valid values, it always throws
* an exception.
*
* @return True if addFirst throws any exception, false otherwise.
*/
private boolean addFirstAlwaysException() {
Deque deque = new Deque();
return adderThrowsAnyException(deque::addFirst, "A", "BCDEF", "Hallo");
}
/**
* Checks if addLast throws any exception when called.
*
* We assume that if any exception is thrown on valid values, it always throws
* an exception.
*
* @return True if addLast throws any exception, false otherwise.
*/
private boolean addLastAlwaysException() {
Deque deque = new Deque();
return adderThrowsAnyException(deque::addLast, "A", "BCDEF", "Hallo");
}
/**
* Checks if the specified adder method throws any exception when called
* with the given values.
*
* @param adder The adder method to test.
* @param values The values to add.
* @return True if the adder throws any exception, false otherwise.
*/
private boolean adderThrowsAnyException(Consumer<String> adder, String... values) {
try {
for (String value : values) {
adder.accept(value);
}
} catch (Exception e) {
return true;
}
return false;
}
/**
* Checks if getFirst throws any exception when called,
* while the corresponding poller method is called successfully.
*
* We assume that if any exception is thrown on valid values, it always throws
* an exception.
*
* @return True if the getter throws any exception, false otherwise.
*/
private boolean getFirstAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
// should be executable five times when deque is not empty
return getterAnyThrowsException(deque::getFirst, deque::pollFirst, 5);
}
/**
* Checks if getLast throws any exception when called,
* while the corresponding poller method is called successfully.
*
* We assume that if any exception is thrown on valid values, it always throws
* an exception.
*
* @return True if getLast throws any exception, false otherwise.
*/
private boolean getLastAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
// should be executable five times when deque is not empty
return getterAnyThrowsException(deque::getLast, deque::pollLast, 5);
}
/**
* Checks if the specified getter method throws any exception when called,
* while the corresponding poller method is called successfully.
*
* @param getter The getter method to test.
* @param poller The poller method to call.
* @param n The number of times to call the methods.
* @return True if the getter throws any exception, false otherwise.
*/
private boolean getterAnyThrowsException(Supplier<String> getter, Supplier<String> poller, int n) {
try {
for (int i = 0; i < n; i++) {
getter.get();
poller.get();
}
} catch (Exception e) {
return true;
}
return false;
}
/**
* Builds a deque from the given values.
*
* @param values The values to add.
* @return The built deque.
*/
public Deque buildDeque(String... values) {
Deque deque = new Deque();
for (String value : values) {
try {
// Create new Item
Item item = new Item(value);
// If deque is empty, set both front and back to this item
if (deque.peekFirst() == null) {
setFront(deque, item);
setBack(deque, item);
} else {
// Add to the end (back) of the deque
Item currentBack = getBack(deque);
// Set the links
setNext(currentBack, item);
setPrev(item, currentBack);
// Update back pointer
setBack(deque, item);
}
} catch (Exception e) {
throw new RuntimeException("Failed to build deque: " + e.getMessage(), e);
}
}
return deque;
}
/**
* Builds a binary tree from an array from top to bottom and left to right.
*
* @param values The values.
* @return The tree node representing the root.
*/
private TreeNode buildTree(double[] values) {
TreeNode root = new TreeNode(values[0]);
java.util.List<TreeNode> nodes = new ArrayList<>();
nodes.add(root);
for (int i = 1; i < values.length; i++) {
TreeNode parent = nodes.get(0);
TreeNode child = new TreeNode(values[i]);
nodes.add(child);
if (i % 2 == 1) {
parent.setLeft(child);
} else {
parent.setRight(child);
nodes.remove(0);
}
}
return root;
}
/**
* Sets the root in the tree.
*
* @param tree The tree.
* @param root The root to set in the tree.
*/
private void setRoot(Tree tree, TreeNode root) {
try {
Field field = Tree.class.getDeclaredField("root");
field.setAccessible(true);
field.set(tree, root);
} catch (Exception e) {
throw new RuntimeException("Failed to set root.");
}
}
/**
* Sets the front item in the deque using reflection.
*
* @param deque The deque.
* @param item The item to set as front.
*/
private void setFront(Deque deque, Item item) {
try {
Field field = Deque.class.getDeclaredField("front");
field.setAccessible(true);
field.set(deque, item);
} catch (Exception e) {
throw new RuntimeException("Failed to set front.");
}
}
/**
* Sets the back item in the deque using reflection.
*
* @param deque The deque.
* @param item The item to set as back.
*/
private void setBack(Deque deque, Item item) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
field.set(deque, item);
} catch (Exception e) {
throw new RuntimeException("Failed to set back.");
}
}
/**
* Gets the back item from the deque using reflection.
*
* @param deque The deque.
* @return The back item.
*/
private Item getBack(Deque deque) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
return (Item) field.get(deque);
} catch (Exception e) {
throw new RuntimeException("Failed to get back.");
}
}
/**
* Sets the next item in an Item using reflection.
*
* @param item The item.
* @param next The next item to set.
*/
private void setNext(Item item, Item next) {
try {
Field field = Item.class.getDeclaredField("next");
field.setAccessible(true);
field.set(item, next);
} catch (Exception e) {
throw new RuntimeException("Failed to set next.");
}
}
/**
* Sets the previous item in an Item using reflection.
*
* @param item The item.
* @param prev The previous item to set.
*/
private void setPrev(Item item, Item prev) {
try {
Field field = Item.class.getDeclaredField("prev");
field.setAccessible(true);
field.set(item, prev);
} catch (Exception e) {
throw new RuntimeException("Failed to set prev.");
}
}
/**
* The points of each test case.
*/
private java.util.List<Integer> points = new ArrayList<>();
/**
* This method will be called by jack after all test have been executed to get
* the resulting points.
*
* @return The points resulting from the test.
*/
public int getResult() {
int sum = 0;
for (Integer p : points) {
sum += p;
}
return sum;
}
/**
* Adds points for a test case. This class assumes that the method is called
* <b>exactly</b> once per test case.
*
* @param value The points to add.
*/
protected void addPoints(int value) {
points.add(value);
}
/**
* A utility method to execute any test driver class extending abstract test
* locally without going through Jack.
*
* @param test The test driver to execute.
* @throws Exception Thrown if something fails.
*/
public static void runAll() throws Exception {
Tests test = new Tests();
System.out.println(test.getClass().getName());
System.out.println();
for (Method method : test.getClass().getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
int size = test.points.size();
try {
method.invoke(test);
if (test.points.size() != size + 1) {
System.err.println("Der Test " + method.getAnnotation(Test.class).name()
+ " lieferte kein oder mehrere Ergebnisse.");
} else {
System.out.println("Punkte: " + test.points.get(test.points.size() - 1) + " ("
+ method.getAnnotation(Test.class).name() + ")");
}
} catch (Exception e) {
System.err.println(
"Der Test " + method.getAnnotation(Test.class).name() + " lieferte ein Exception.");
e.printStackTrace();
}
System.out.println("");
}
}
System.out.println();
System.out.println("Summe: " + test.getResult());
}
public static void main(String[] args) {
try {
runAll();
} catch (Exception e) {
e.printStackTrace();
}
}
}
+140
View File
@@ -0,0 +1,140 @@
/**
* An (inverse) ordered binary tree.
*
* @author Marcus
*/
public class Tree {
/**
* The root node of the tree.
*/
private TreeNode root;
/**
* Creates a new and empty tree.
*/
public Tree() {
super();
}
/**
* Traverses the tree and calls the visitor's
* visit(TreeNode) method in post-order.
*
* @param visitor The visitor whose visit method
* shall be called in post-order.
*/
public void traverse(TreeVisitor visitor) {
traverse(visitor, root);
}
/**
* Traverses the subtree starting at current
* and calls the visitor's visit(TreeNode)
* method in post-order.
*
* @param visitor The visitor.
* @param current The subtree to visit, may be null.
*/
private void traverse(TreeVisitor visitor, TreeNode current) {
if (current == null)
return;
// TODO: implement
}
/**
* Inserts a new value into the tree.
*
* @param value The value to insert.
*/
public void insert(double value) {
if (root == null) {
root = new TreeNode(value);
} else {
insert(value, root);
}
}
/**
* Recursively finds the right node to insert the
* value and inserts it.
*
* @param value The value to insert.
* @param current The current value.
*/
private void insert(double value, TreeNode current) {
if (value > current.getValue()) {
// larger values go left
if (current.getLeft() == null) {
current.setLeft(new TreeNode(value));
} else {
insert(value, current.getLeft());
}
} else {
// smaller or equal values go right
if (current.getRight() == null) {
current.setRight(new TreeNode(value));
} else {
insert(value, current.getRight());
}
}
}
/**
* Efficiently counts the number of nodes in the
* tree that have a particular value by considering
* the order that is defined by the tree's insert
* method.
*
* @param value The value to search from.
* @return The number of nodes with the value.
*/
public int count(double value) {
return count(value, root);
}
/**
* Efficiently counts the number of nodes in the
* subtree starting at current that have a particular
* value by considering the order that is defined
* by the tree's insert method.
*
* @param value The value to search from.
* @param current The subtree to search in, may be null.
* @return The number of nodes with the value.
*/
private int count(double value, TreeNode current) {
if (current == null)
return 0;
// TODO: implement
return -1;
}
/**
* Calculates the height of the tree total tree.
*
* @return The height of the tree, which is the
* number of edges on the longest path from the root
* to a leaf node. If the tree is empty, returns 0.
* If the tree has only one node, returns 1.
*/
public int height() {
return height(root);
}
/**
* Calculates the height of the subtree
* starting at current.
*
* @param current The subtree to calculate the height of, may be null.
* If null, the height is 0.
* @return The height of the subtree, which is the
* number of edges on the longest path from the current node
* to a leaf node.
*/
public int height(TreeNode current) {
// TODO: implement
return -42;
}
}
+81
View File
@@ -0,0 +1,81 @@
/**
* A node of a binary tree.
*
* @author Marcus
*/
public class TreeNode {
/**
* The value of the node.
*/
private double value;
/**
* The left child, or null.
*/
private TreeNode left;
/**
* The right child, or null.
*/
private TreeNode right;
/**
* Creates a new tree node with
* the specified value and no
* children.
*
* @param value The value to set.
*/
public TreeNode(double value) {
this.value = value;
}
/**
* Returns the node value.
*
* @return The value of the node.
*/
public double getValue() {
return value;
}
/**
* Returns the left child or null.
*
* @return The left child or null.
*/
public TreeNode getLeft() {
return left;
}
/**
* Returns the right child or null.
*
* @return The right child or null.
*/
public TreeNode getRight() {
return right;
}
/**
* Sets the left child.
*
* @param left The new left child.
*/
public void setLeft(TreeNode left) {
this.left = left;
}
/**
* Sets the right child.
*
* @param right The new right child.
*/
public void setRight(TreeNode right) {
this.right = right;
}
}
+76
View File
@@ -0,0 +1,76 @@
import java.util.ArrayList;
import java.util.List;
/**
* A visitor to test the implementation.
*
* @author Marcus
*/
public class TreeVisitor {
/**
* The list of visited tree nodes.
*/
private List<TreeNode> visited = new ArrayList<>();
/**
* Creates a new visitor with an empty list of nodes.
*/
public TreeVisitor() {
super();
}
/**
* Returns the list with the visited nodes.
*
* @return The visited nodes.
*/
public List<TreeNode> getVisited() {
return visited;
}
/**
* Visits the tree node and adds it to the list
* of visited nodes.
*
* @param node The node to visit.
*/
public void visit(TreeNode node) {
visited.add(node);
}
/**
* Converts the visited node list into an int
* array containing the values of the nodes.
*
* @return The array with the node values.
*/
public double[] toArray() {
double[] result = new double[visited.size()];
for (int i = 0; i < result.length; i++) {
// Added null check - otherwise Jack test crash
if (visited.get(i) == null)
result[i] = Integer.MAX_VALUE;
else
result[i] = visited.get(i).getValue();
}
return result;
}
@Override
public String toString() {
String result = "";
for (int i = 0; i < visited.size(); i++) {
// Added null check - otherwise Jack test crash
if (visited.get(i) == null)
result += "[NULL]";
else
result += visited.get(i).getValue();
if (i != visited.size() - 1) {
result += ", ";
}
}
return result;
}
}
@@ -0,0 +1,19 @@
package de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class TracingFramework {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Test {
String name();
}
public static void printError(String string) {
System.err.println("ERROR: " + string);
}
}