Generic Deque Testat 3

This commit is contained in:
2025-09-12 14:25:16 +02:00
parent 2537c0e956
commit 209ec3a75d
26 changed files with 537 additions and 1943 deletions
@@ -69,51 +69,32 @@ Die Höhe eines Baums ist wie folgt definiert:
================================================================================
Aufgabe 2 - I/O-Serialisierung von Listen - 20 Punkte
Aufgabe 2 - Enhanced Deque - 40 Punkte
Implementieren Sie folgenden Methoden in der Klasse StringListSerializer:
Diese Aufgabe baut auf der Deque Aufgabe aus dem vorherigen Testat auf. Das Ziel
ist es die Deque generisch zu machen, dafür wurden schon erste Anpassungen
gemacht.
Damit die Deque vollständig generisch wird und mit Sonderfällen besser umgehen
kann sollen Sie die Methoden zum hinzufügen und zum erhalten von Werten
anpassen.
----- a) -----
void write(Path path, List<String> list)
Passen Sie die Methoden addFirst und addLast so an, dass diese:
- Werte entsprechend der Typvariable der Klasse Deque annehmen und der Operation
entsprechend richtig in die Deque einfügen.
- für Werte welche null sind eine IllegalArgumentException mit der Nachricht
"Value cannot be null" werfen.
Diese Methode soll den Inhalt der übergebenen Liste in die Datei des übergebenen
Pfades schreiben. Dabei soll ein Element der Liste, einer Zeile der Datei
entsprechen.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse
java.nio.file.Files vorhanden sind.
Für den Fall, dass es sich bei dem übergebenen Wert um einen leeren String
handelt so soll eine IllegalArgumentException mit der Nachricht "Value cannot be
empty" geworfen werden. (Tipp: instanceof)
----- b) -----
List<String> read(Path path)
Diese Methode soll den Inhalt der Datei des übergebenen Pfades zurückgeben.
Jedes Element der zurückgegebenen Liste soll einer Zeile der Datei entsprechen.
Im Falle einer IOException, soll eine leere Liste zurückgegeben werden.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse
java.nio.file.Files vorhanden sind.
================================================================================
Aufgabe 3 - Deque Exceptions - 20 Punkte
Diese Aufgabe baut auf der Deque Aufgabe aus dem vorherigen Testat auf. In
dieser Aufgabe sollen Sie die Methoden zum hinzufügen und zum erhalten von
Werten anpassen.
----- a) -----
Passen Sie die Methoden addFirst und addList so an, dass diese eine Exception
werfen, wenn der übergebene Wert null oder leer ist.
- Falls der übergebene Wert null ist soll eine IllegalArgumentException mit der
Nachricht "Value cannot be null" geworfen werden.
- Falls der übergebene Wert leer ist soll eine IllegalArgumentException mit der
Nachricht "Value cannot be empty" geworfen werden.
----- b) -----
Passen Sie die Methoden getFirst und getLast so an, dass diese eine
NoSuchElementException werfen, wenn die Deque leer ist (Tipp: isEmpty).
- Die Nachricht der Exception soll dabei "Deque is empty" sein.
Passen Sie die Methoden getFirst und addLast so an, dass diese:
- Werte entsprechen der Typvariable der Klasse Deque zurückgeben.
- eine NoSuchElementException mit der Nachricht "Deque is empty" werfen, wenn
die Deque leer ist. (Tipp: isEmpty)
Passen Sie bei allen Methoden die eine Exception schmeißen sollen die Signatur
@@ -70,51 +70,32 @@ Die Höhe eines Baums ist wie folgt definiert:
================================================================================
Aufgabe 2 - I/O-Serialisierung von Listen - 20 Punkte
Aufgabe 2 - Enhanced Deque - 40 Punkte
Implementieren Sie folgenden Methoden in der Klasse StringListSerializer:
Diese Aufgabe baut auf der Deque Aufgabe aus dem vorherigen Testat auf. Das Ziel
ist es die Deque generisch zu machen, dafür wurden schon erste Anpassungen
gemacht.
Damit die Deque vollständig generisch wird und mit Sonderfällen besser umgehen
kann sollen Sie die Methoden zum hinzufügen und zum erhalten von Werten
anpassen.
----- a) -----
void write(Path path, List<String> list)
Passen Sie die Methoden addFirst und addLast so an, dass diese:
- Werte entsprechend der Typvariable der Klasse Deque annehmen und der Operation
entsprechend richtig in die Deque einfügen.
- für Werte welche null sind eine IllegalArgumentException mit der Nachricht
"Value cannot be null" werfen.
Diese Methode soll den Inhalt der übergebenen Liste in die Datei des übergebenen
Pfades schreiben. Dabei soll ein Element der Liste, einer Zeile der Datei
entsprechen.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse
java.nio.file.Files vorhanden sind.
Für den Fall, dass es sich bei dem übergebenen Wert um einen leeren String
handelt so soll eine IllegalArgumentException mit der Nachricht "Value cannot be
empty" geworfen werden. (Tipp: instanceof)
----- b) -----
List<String> read(Path path)
Diese Methode soll den Inhalt der Datei des übergebenen Pfades zurückgeben.
Jedes Element der zurückgegebenen Liste soll einer Zeile der Datei entsprechen.
Im Falle einer IOException, soll eine leere Liste zurückgegeben werden.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse
java.nio.file.Files vorhanden sind.
================================================================================
Aufgabe 3 - Deque Exceptions - 20 Punkte
Diese Aufgabe baut auf der Deque Aufgabe aus dem vorherigen Testat auf. In
dieser Aufgabe sollen Sie die Methoden zum hinzufügen und zum erhalten von
Werten anpassen.
----- a) -----
Passen Sie die Methoden addFirst und addList so an, dass diese eine Exception
werfen, wenn der übergebene Wert null oder leer ist.
- Falls der übergebene Wert null ist soll eine IllegalArgumentException mit der
Nachricht "Value cannot be null" geworfen werden.
- Falls der übergebene Wert leer ist soll eine IllegalArgumentException mit der
Nachricht "Value cannot be empty" geworfen werden.
----- b) -----
Passen Sie die Methoden getFirst und getLast so an, dass diese eine
NoSuchElementException werfen, wenn die Deque leer ist (Tipp: isEmpty).
- Die Nachricht der Exception soll dabei "Deque is empty" sein.
Passen Sie die Methoden getFirst und addLast so an, dass diese:
- Werte entsprechen der Typvariable der Klasse Deque zurückgeben.
- eine NoSuchElementException mit der Nachricht "Deque is empty" werfen, wenn
die Deque leer ist. (Tipp: isEmpty)
Passen Sie bei allen Methoden die eine Exception schmeißen sollen die Signatur
@@ -1,17 +1,24 @@
Aufgabe 2 - I/O-Serialisierung von Listen - 20 Punkte
Aufgabe 2 - Enhanced Deque - 40 Punkte
Implementieren Sie folgenden Methoden in der Klasse StringListSerializer:
Diese Aufgabe baut auf der Deque Aufgabe aus dem vorherigen Testat auf. Das Ziel ist es die Deque generisch zu machen, dafür wurden schon erste Anpassungen gemacht.
Damit die Deque vollständig generisch wird und mit Sonderfällen besser umgehen kann sollen Sie die Methoden zum hinzufügen und zum erhalten von Werten anpassen.
----- a) -----
void write(Path path, List<String> list)
Passen Sie die Methoden addFirst und addLast so an, dass diese:
- Werte entsprechend der Typvariable der Klasse Deque annehmen und der Operation entsprechend richtig in die Deque einfügen.
- für Werte welche null sind eine IllegalArgumentException mit der Nachricht "Value cannot be null" werfen.
Diese Methode soll den Inhalt der übergebenen Liste in die Datei des übergebenen Pfades schreiben. Dabei soll ein Element der Liste, einer Zeile der Datei entsprechen.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse java.nio.file.Files vorhanden sind.
Für den Fall, dass es sich bei dem übergebenen Wert um einen leeren String handelt so soll eine IllegalArgumentException mit der Nachricht "Value cannot be empty" geworfen werden. (Tipp: instanceof)
----- b) -----
List<String> read(Path path)
Passen Sie die Methoden getFirst und addLast so an, dass diese:
- Werte entsprechen der Typvariable der Klasse Deque zurückgeben.
- eine NoSuchElementException mit der Nachricht "Deque is empty" werfen, wenn die Deque leer ist. (Tipp: isEmpty)
Diese Methode soll den Inhalt der Datei des übergebenen Pfades zurückgeben. Jedes Element der zurückgegebenen Liste soll einer Zeile der Datei entsprechen. Im Falle einer IOException, soll eine leere Liste zurückgegeben werden.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse java.nio.file.Files vorhanden sind.
Passen Sie bei allen Methoden die eine Exception schmeißen sollen die Signatur so an, dass diese auf die Art der möglichen Exception hinweisen.
Für die volle Punktzahl müssen die Nachrichten der Exception exakt der in der Aufgabenstellung beschriebenen Nachricht entsprechen.
Passen Sie KEINE anderen Methoden in der Klasse an. Die Aufgabe ist mit allen vorliegenden Methoden lösbar.
@@ -1,20 +0,0 @@
Aufgabe 3 - Deque Exceptions - 20 Punkte
Diese Aufgabe baut auf der Deque Aufgabe aus dem vorherigen Testat auf. In dieser Aufgabe sollen Sie die Methoden zum hinzufügen und zum erhalten von Werten anpassen.
----- a) -----
Passen Sie die Methoden addFirst und addList so an, dass diese eine Exception werfen, wenn der übergebene Wert null oder leer ist.
- Falls der übergebene Wert null ist soll eine IllegalArgumentException mit der Nachricht "Value cannot be null" geworfen werden.
- Falls der übergebene Wert leer ist soll eine IllegalArgumentException mit der Nachricht "Value cannot be empty" geworfen werden.
----- b) -----
Passen Sie die Methoden getFirst und getLast so an, dass diese eine NoSuchElementException werfen, wenn die Deque leer ist (Tipp: isEmpty).
- Die Nachricht der Exception soll dabei "Deque is empty" sein.
Passen Sie bei allen Methoden die eine Exception schmeißen sollen die Signatur so an, dass diese auf die Art der möglichen Exception hinweisen.
Für die volle Punktzahl müssen die Nachrichten der Exception exakt der in der Aufgabenstellung beschriebenen Nachricht entsprechen.
Passen Sie KEINE anderen Methoden in der Klasse an. Die Aufgabe ist mit allen vorliegenden Methoden lösbar.
@@ -1,17 +1,24 @@
Aufgabe 2 - I/O-Serialisierung von Listen - 20 Punkte
Aufgabe 2 - Enhanced Deque - 40 Punkte
Implementieren Sie folgenden Methoden in der Klasse StringListSerializer:
Diese Aufgabe baut auf der Deque Aufgabe aus dem vorherigen Testat auf. Das Ziel ist es die Deque generisch zu machen, dafür wurden schon erste Anpassungen gemacht.
Damit die Deque vollständig generisch wird und mit Sonderfällen besser umgehen kann sollen Sie die Methoden zum hinzufügen und zum erhalten von Werten anpassen.
----- a) -----
void write(Path path, List<String> list)
Passen Sie die Methoden addFirst und addLast so an, dass diese:
- Werte entsprechend der Typvariable der Klasse Deque annehmen und der Operation entsprechend richtig in die Deque einfügen.
- für Werte welche null sind eine IllegalArgumentException mit der Nachricht "Value cannot be null" werfen.
Diese Methode soll den Inhalt der übergebenen Liste in die Datei des übergebenen Pfades schreiben. Dabei soll ein Element der Liste, einer Zeile der Datei entsprechen.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse java.nio.file.Files vorhanden sind.
Für den Fall, dass es sich bei dem übergebenen Wert um einen leeren String handelt so soll eine IllegalArgumentException mit der Nachricht "Value cannot be empty" geworfen werden. (Tipp: instanceof)
----- b) -----
List<String> read(Path path)
Passen Sie die Methoden getFirst und addLast so an, dass diese:
- Werte entsprechen der Typvariable der Klasse Deque zurückgeben.
- eine NoSuchElementException mit der Nachricht "Deque is empty" werfen, wenn die Deque leer ist. (Tipp: isEmpty)
Diese Methode soll den Inhalt der Datei des übergebenen Pfades zurückgeben. Jedes Element der zurückgegebenen Liste soll einer Zeile der Datei entsprechen. Im Falle einer IOException, soll eine leere Liste zurückgegeben werden.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse java.nio.file.Files vorhanden sind.
Passen Sie bei allen Methoden die eine Exception schmeißen sollen die Signatur so an, dass diese auf die Art der möglichen Exception hinweisen.
Für die volle Punktzahl müssen die Nachrichten der Exception exakt der in der Aufgabenstellung beschriebenen Nachricht entsprechen.
Passen Sie KEINE anderen Methoden in der Klasse an. Die Aufgabe ist mit allen vorliegenden Methoden lösbar.
@@ -1,20 +0,0 @@
Aufgabe 3 - Deque Exceptions - 20 Punkte
Diese Aufgabe baut auf der Deque Aufgabe aus dem vorherigen Testat auf. In dieser Aufgabe sollen Sie die Methoden zum hinzufügen und zum erhalten von Werten anpassen.
----- a) -----
Passen Sie die Methoden addFirst und addList so an, dass diese eine Exception werfen, wenn der übergebene Wert null oder leer ist.
- Falls der übergebene Wert null ist soll eine IllegalArgumentException mit der Nachricht "Value cannot be null" geworfen werden.
- Falls der übergebene Wert leer ist soll eine IllegalArgumentException mit der Nachricht "Value cannot be empty" geworfen werden.
----- b) -----
Passen Sie die Methoden getFirst und getLast so an, dass diese eine NoSuchElementException werfen, wenn die Deque leer ist (Tipp: isEmpty).
- Die Nachricht der Exception soll dabei "Deque is empty" sein.
Passen Sie bei allen Methoden die eine Exception schmeißen sollen die Signatur so an, dass diese auf die Art der möglichen Exception hinweisen.
Für die volle Punktzahl müssen die Nachrichten der Exception exakt der in der Aufgabenstellung beschriebenen Nachricht entsprechen.
Passen Sie KEINE anderen Methoden in der Klasse an. Die Aufgabe ist mit allen vorliegenden Methoden lösbar.
+21 -30
View File
@@ -4,17 +4,17 @@ import java.util.NoSuchElementException;
* Represents a double-ended queue (deque) that allows adding and removing items
* from both ends.
*/
public class Deque {
public class Deque<T> {
/**
* The front item of the deque.
*/
private Item front;
private Item<T> front;
/**
* The back item of the deque.
*/
private Item back;
private Item<T> back;
/**
* Constructs an empty deque.
@@ -29,7 +29,7 @@ public class Deque {
*
* @return The front item in the deque.
*/
private Item getFront() {
private Item<T> getFront() {
return front;
}
@@ -38,7 +38,7 @@ public class Deque {
*
* @return The back item in the deque.
*/
private Item getBack() {
private Item<T> getBack() {
return back;
}
@@ -47,7 +47,7 @@ public class Deque {
*
* @param front The item to set as the front.
*/
private void setFront(Item front) {
private void setFront(Item<T> front) {
this.front = front;
}
@@ -56,7 +56,7 @@ public class Deque {
*
* @param back The item to set as the back.
*/
private void setBack(Item back) {
private void setBack(Item<T> back) {
this.back = back;
}
@@ -65,17 +65,12 @@ public class Deque {
*
* @param value The value of the item to add.
*/
public void addFirst(String value) { // TODO: change
public void addFirst(Object value) { // TODO: change
if (value == null) {
// TODO: change
return;
}
if (value.isEmpty()) {
// TODO: change
return;
}
Item item = new Item(value);
if (isEmpty()) {
setFront(item);
@@ -92,18 +87,14 @@ public class Deque {
*
* @param value The value of the item to add.
*/
public void addLast(String value) { // TODO: change
public void addLast(Object value) { // TODO: change
if (value == null) {
// TODO: change
return;
}
if (value.isEmpty()) {
// TODO: change
return;
}
Item item = new Item(value);
// Item item = new Item(value);
Item<T> item = new Item(value);
if (isEmpty()) {
setFront(item);
setBack(item);
@@ -121,7 +112,7 @@ public class Deque {
* @return The value of the front item in the deque, or null if the deque is
* empty.
*/
public String peekFirst() {
public T peekFirst() {
if (isEmpty()) {
return null;
} else {
@@ -136,7 +127,7 @@ public class Deque {
* @return The value of the back item in the deque, or null if the deque is
* empty.
*/
public String peekLast() {
public T peekLast() {
if (isEmpty()) {
return null;
} else {
@@ -150,11 +141,11 @@ public class Deque {
*
* @return The value of the removed front item, or null if the deque is empty.
*/
public String pollFirst() {
public T pollFirst() {
if (isEmpty()) {
return null;
} else {
String value = getFront().getValue();
T value = getFront().getValue();
setFront(getFront().getNext());
if (getFront() == null) {
setBack(null);
@@ -169,11 +160,11 @@ public class Deque {
*
* @return The value of the removed back item, or null if the deque is empty.
*/
public String pollLast() {
public T pollLast() {
if (isEmpty()) {
return null;
} else {
String value = getBack().getValue();
T value = getBack().getValue();
setBack(getBack().getPrev());
if (getBack() == null) {
setFront(null);
@@ -191,7 +182,7 @@ public class Deque {
* @return The value of the first item in the deque.
* @throws NoSuchElementException if the deque is empty.
*/
public String getFirst() { // TODO: change
public Object getFirst() { // TODO: change
// TODO: add check
return getFront().getValue();
}
@@ -203,7 +194,7 @@ public class Deque {
* @return The value of the last item in the deque.
* @throws NoSuchElementException if the deque is empty.
*/
public String getLast() { // TODO: change
public Object getLast() { // TODO: change
// TODO: add check
return getBack().getValue();
}
@@ -215,7 +206,7 @@ public class Deque {
*/
public int size() {
int count = 0;
Item current = getFront();
Item<T> current = getFront();
while (current != null) {
count++;
current = current.getNext();
@@ -238,7 +229,7 @@ public class Deque {
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Item current = getFront();
Item<T> current = getFront();
sb.append("[");
while (current != null) {
sb.append(current.getValue());
-154
View File
@@ -1,154 +0,0 @@
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
@@ -1,88 +0,0 @@
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();
}
}
@@ -1,126 +0,0 @@
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");
}
}
-226
View File
@@ -1,226 +0,0 @@
import java.io.File;
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;
import java.util.Iterator;
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.length() != 0) {
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();
}
@Override
public boolean startsWith(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'startsWith'");
}
@Override
public boolean endsWith(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'endsWith'");
}
@Override
public Path resolve(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolve'");
}
@Override
public Path resolveSibling(Path other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolveSibling'");
}
@Override
public Path resolveSibling(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolveSibling'");
}
@Override
public File toFile() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'toFile'");
}
@Override
public WatchKey register(WatchService watcher, Kind<?>... events) throws IOException {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'register'");
}
@Override
public Iterator<Path> iterator() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'iterator'");
}
}
-44
View File
@@ -1,44 +0,0 @@
import java.nio.file.FileSystem;
import java.nio.file.Path;
public class InMemoryPathFactory {
private final InMemoryFileSystemProvider provider = new InMemoryFileSystemProvider();
private final InMemoryFileSystem fileSystem = new InMemoryFileSystem(provider);
/**
* Creates a new in-memory path
*
* @param path the path string
* @return a InMemoryPath that exists only in memory
*/
public Path createPath(String path) {
return new InMemoryPath(fileSystem, path);
}
/**
* Gets the in-memory file system instance
*
* @return the file system
*/
public FileSystem getFileSystem() {
return fileSystem;
}
/**
* Clears all data from the in-memory file system
*/
public 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 boolean exists(Path path) {
return InMemoryFileSystem.getStorage().containsKey(path.toString());
}
}
+11 -11
View File
@@ -1,29 +1,29 @@
/**
* Represents an item in a doubly linked deque.
*/
public class Item {
public class Item<T> {
/**
* The value of the item.
*/
private String value;
private T value;
/**
* The previous item in the deque.
*/
private Item prev;
private Item<T> prev;
/**
* The next item in the deque.
*/
private Item next;
private Item<T> next;
/**
* Constructor for creating a new item.
*
* @param value The value of the item.
*/
public Item(String value) {
public Item(T value) {
this.value = value;
this.prev = null;
this.next = null;
@@ -34,7 +34,7 @@ public class Item {
*
* @return The value of the item.
*/
public String getValue() {
public T getValue() {
return value;
}
@@ -43,7 +43,7 @@ public class Item {
*
* @param value The value of the item.
*/
public void setValue(String value) {
public void setValue(T value) {
this.value = value;
}
@@ -52,7 +52,7 @@ public class Item {
*
* @return The previous item in the deque.
*/
public Item getPrev() {
public Item<T> getPrev() {
return prev;
}
@@ -61,7 +61,7 @@ public class Item {
*
* @param prev The previous item in the deque.
*/
public void setPrev(Item prev) {
public void setPrev(Item<T> prev) {
this.prev = prev;
}
@@ -70,7 +70,7 @@ public class Item {
*
* @return The next item in the deque.
*/
public Item getNext() {
public Item<T> getNext() {
return next;
}
@@ -79,7 +79,7 @@ public class Item {
*
* @param next The next item in the deque.
*/
public void setNext(Item next) {
public void setNext(Item<T> next) {
this.next = next;
}
+2 -64
View File
@@ -1,6 +1,3 @@
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
public class Main {
@@ -33,70 +30,11 @@ public class Main {
System.out.println();
System.out.println("=========================================");
System.out.println("Aufgabe 2 - I/O-Serialisierung von Listen");
System.out.println("Aufgabe 2 - Deque");
System.out.println("=========================================");
System.out.println();
// Create a StringListSerializer to test our implementation
StringListSerializer serializer = new StringListSerializer();
InMemoryPathFactory factory = new InMemoryPathFactory();
Path erlkingPath = factory.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();
Deque<String> deque = new Deque<>();
// getFirst
System.out.println("Checking if getFirst on empty deque throws NoSuchElementException");
@@ -1,40 +0,0 @@
import java.io.IOException;
import java.nio.file.Files;
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
try {
Files.write(path, list);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 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<>();
}
}
+199 -126
View File
@@ -1,8 +1,7 @@
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.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -133,104 +132,175 @@ public class Tests {
addPoints(points);
}
// Aufgabe 2 - IO - 20 Punkte
// Aufgabe 2 - Generic Deque - 20 Punkte
@Test(name = "Aufgabe 2 - IO - write - 10 Punkte")
public void testIOWrite() {
int points = 10;
@Test(name = "Aufgabe 2 - Deque - addFirst - takes generic type - 5 Punkte")
public void testDequeAddFirstGeneric() {
int points = 5;
StringListSerializer serializer = new StringListSerializer();
InMemoryPathFactory factory = new InMemoryPathFactory();
Path path = factory.createPath("/test/write.txt");
List<String> data = Arrays.asList("Hello", "World", "This is a test");
serializer.write(path, data);
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.");
if (!isDequeAdderGeneric("addFirst")) {
points -= 5;
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - IO - read - errorless- 5 Punkte")
public void testIOReadErrorless() {
@Test(name = "Aufgabe 2 - Deque - addLast - takes generic type - 5 Punkte")
public void testDequeAddLastGeneric() {
int points = 5;
StringListSerializer serializer = new StringListSerializer();
InMemoryPathFactory factory = new InMemoryPathFactory();
Path path = factory.createPath("/test/read.txt");
List<String> data = Arrays.asList("Hello", "World", "This is a test");
try {
Files.write(path, data);
} catch (IOException e) {
if (!isDequeAdderGeneric("addLast")) {
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() {
@Test(name = "Aufgabe 2 - Deque - getFirst - returns generic type - 5 Punkte")
public void testDequeGetFirstGeneric() {
int points = 5;
if (alwaysEmptyRead()) {
TracingFramework.printError(
"Reading from non-empty file returns empty list. Assuming read always returns empty list. Deducting 5 points.");
addPoints(0);
return;
if (!isDequeGetterGeneric("getFirst")) {
points -= 5;
}
StringListSerializer serializer = new StringListSerializer();
InMemoryPathFactory factory = new InMemoryPathFactory();
Path path = factory.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.");
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - getLast - returns generic type - 5 Punkte")
public void testDequeGetLastGeneric() {
int points = 5;
if (!isDequeGetterGeneric("getLast")) {
points -= 5;
}
addPoints(points);
}
/**
* Checks if an adder method takes the generic type parameter.
*
* @param name The name of the method.
* @return true if the method takes the generic type parameter, false otherwise.
*/
@SuppressWarnings("rawtypes")
private boolean isDequeAdderGeneric(String name) {
TypeVariable<Class<Deque>> classTypeParameter = getClassTypeParameter();
if (classTypeParameter == null) {
return false;
}
Method method = findUniqueMethod(Deque.class, name);
if (method == null) {
TracingFramework.printError("Method Deque." + name + " not found. Class was mutated illegally.");
return false;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (genericParameterTypes.length != 1) {
TracingFramework.printError("Deque." + name + " should take one parameter, but takes "
+ genericParameterTypes.length + " parameters.");
return false;
}
Type paramType = genericParameterTypes[0];
if (paramType instanceof TypeVariable) {
TypeVariable<?> typeVar = (TypeVariable<?>) paramType;
if (!typeVar.getName().equals(classTypeParameter.getName())) {
TracingFramework.printError("Deque." + name + " should take the generic type parameter, but takes "
+ typeVar.getName() + " instead.");
return false;
}
} 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;
} else {
TracingFramework.printError("Deque." + name + " should take the generic type parameter, but takes "
+ paramType.getTypeName() + " instead.");
return false;
}
return true;
}
/**
* Checks if a getter method returns the generic type parameter.
*
* @param name The name of the method.
* @return true if the method returns the generic type parameter, false
* otherwise.
*/
@SuppressWarnings("rawtypes")
private boolean isDequeGetterGeneric(String name) {
TypeVariable<Class<Deque>> classTypeParameter = getClassTypeParameter();
if (classTypeParameter == null) {
return false;
}
Method method = findUniqueMethod(Deque.class, name);
if (method == null) {
TracingFramework.printError("Method Deque." + name + " not found. Class was mutated illegally.");
return false;
}
if (!returnsGenericClassType(method, classTypeParameter.getName())) {
return false;
}
return true;
}
/**
* Checks if a method returns the generic type parameter of the class.
*
* @param method The method to check.
* @param classTypeParameterName The name of the class's generic type parameter.
* @return true if the method returns the generic type parameter, false
* otherwise.
*/
private boolean returnsGenericClassType(Method method, String classTypeParameterName) {
Type returnType = method.getGenericReturnType();
String methodName = method.getName();
if (returnType instanceof TypeVariable) {
TypeVariable<?> typeVar = (TypeVariable<?>) returnType;
if (!typeVar.getName().equals(classTypeParameterName)) {
TracingFramework
.printError("Reading from /test/forcedIOException.txt path throws an unexpected exception: "
+ e.getMessage());
.printError("Deque." + methodName + " should return the generic type parameter, but returns "
+ typeVar.getName() + " instead.");
return false;
}
} else {
TracingFramework
.printError("Deque." + methodName + " should return the generic type parameter, but returns "
+ returnType.getTypeName() + " instead.");
return false;
}
addPoints(points);
return true;
}
// Aufgabe 3 - Deque - 20 Punkte
/**
* Gets the generic type parameter of the Deque class.
*
* @return The generic type parameter of the Deque class, null if not found.
*/
@SuppressWarnings("rawtypes")
private TypeVariable<Class<Deque>> getClassTypeParameter() {
Class<Deque> clazz = Deque.class;
TypeVariable<Class<Deque>>[] classTypeParameters = clazz.getTypeParameters();
if (classTypeParameters.length != 1) {
TracingFramework.printError("Deque should have one generic type parameter, but has "
+ classTypeParameters.length + " parameters.");
return null;
}
TypeVariable<Class<Deque>> classTypeParameter = classTypeParameters[0];
if (!classTypeParameter.getName().equals("T")) {
TracingFramework.printError("Deque's generic type parameter should be named T, but is named "
+ classTypeParameter.getName() + " instead.");
return null;
}
return classTypeParameter;
}
// Aufgabe 3 - Deque Exception - 20 Punkte
@Test(name = "Aufgabe 3 - Deque - addFirst null - 3 Punkte")
public void testDequeAddFirstNull() {
@@ -242,7 +312,7 @@ public class Tests {
"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 deque = new Deque();
Deque<String> deque = new Deque<>();
deque.addFirst(null);
points -= 3;
TracingFramework
@@ -276,7 +346,7 @@ public class Tests {
"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 deque = new Deque();
Deque<String> deque = new Deque<>();
deque.addFirst("");
points -= 3;
TracingFramework
@@ -304,7 +374,7 @@ public class Tests {
public void testDequeAddFirstThrowsIllegalArgumentException() {
int points = 2;
Method method = findMethod(Deque.class, "addFirst", String.class);
Method method = findUniqueMethod(Deque.class, "addFirst");
if (method == null) {
TracingFramework.printError("Method Deque.addFirst(String) not found. Class was mutated illegally.");
addPoints(0);
@@ -341,7 +411,7 @@ public class Tests {
"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();
Deque<String> deque = new Deque<>();
deque.addLast(null);
points -= 3;
TracingFramework
@@ -375,7 +445,7 @@ public class Tests {
"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();
Deque<String> deque = new Deque<>();
deque.addLast("");
points -= 3;
TracingFramework
@@ -440,7 +510,7 @@ public class Tests {
"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<String> deque = new Deque<>();
deque.getFirst();
points -= 2;
TracingFramework
@@ -507,7 +577,7 @@ public class Tests {
"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<String> deque = new Deque<>();
deque.getLast();
points -= 2;
TracingFramework
@@ -563,30 +633,6 @@ public class Tests {
addPoints(points);
}
/**
* Checks if reading from a non-empty file always returns an empty list.
*
* @return True if reading always returns an empty list, false otherwise.
*/
private boolean alwaysEmptyRead() {
InMemoryPathFactory factory = new InMemoryPathFactory();
Path path = factory.createPath("/test/foo.txt");
List<String> content = Arrays.asList("This", "is", "not", "empty");
try {
Files.write(path, content);
} catch (IOException e) {
return false;
}
StringListSerializer serializer = new StringListSerializer();
try {
List<String> readData = serializer.read(path);
return readData != null && readData.isEmpty();
} catch (Exception e) {
return false;
}
}
/**
* Builds a binary tree from an array from top to bottom and left to right.
*
@@ -643,6 +689,30 @@ public class Tests {
}
}
/**
* Finds a unique method in a class by name.
*
* @param clazz The class to search in.
* @param name The name of the method.
* @return The found method, or null if not found or more than one method with
* the same name exists.
*/
public static Method findUniqueMethod(Class<?> clazz, String name) {
Method[] methods = clazz.getDeclaredMethods();
Method found = null;
for (Method method : methods) {
if (method.getName().equals(name)) {
if (found != null) {
TracingFramework.printError("More than one method named " + name
+ " found in class " + clazz.getName() + ". Class was mutated illegally.");
return null;
}
found = method;
}
}
return found;
}
/**
* START: Deque helper methods
*/
@@ -656,7 +726,7 @@ public class Tests {
* @return True if addFirst throws any exception, false otherwise.
*/
private boolean addFirstAlwaysException() {
Deque deque = new Deque();
Deque<String> deque = new Deque<>();
return adderThrowsAnyException(deque::addFirst, "A", "BCDEF", "Hallo");
}
@@ -669,7 +739,7 @@ public class Tests {
* @return True if addLast throws any exception, false otherwise.
*/
private boolean addLastAlwaysException() {
Deque deque = new Deque();
Deque<String> deque = new Deque<>();
return adderThrowsAnyException(deque::addLast, "A", "BCDEF", "Hallo");
}
@@ -687,9 +757,9 @@ public class Tests {
adder.accept(value);
}
} catch (Exception e) {
return false;
return true;
}
return true;
return false;
}
/**
@@ -702,9 +772,10 @@ public class Tests {
* @return True if the getter throws any exception, false otherwise.
*/
private boolean getFirstAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
Deque<String> deque = buildDeque("A", "B", "C", "D", "E");
// should be executable five times when deque is not empty
return getterThrowsAnyException(deque::getFirst, deque::pollFirst, 5);
Supplier<String> getter = () -> deque.getFirst().toString();
return getterThrowsAnyException(getter, deque::pollFirst, 5);
}
/**
@@ -717,9 +788,10 @@ public class Tests {
* @return True if getLast throws any exception, false otherwise.
*/
private boolean getLastAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
Deque<String> deque = buildDeque("A", "B", "C", "D", "E");
// should be executable five times when deque is not empty
return getterThrowsAnyException(deque::getLast, deque::pollLast, 5);
Supplier<String> getter = () -> deque.getLast().toString();
return getterThrowsAnyException(getter, deque::pollLast, 5);
}
/**
@@ -749,12 +821,12 @@ public class Tests {
* @param values The values to add.
* @return The built deque.
*/
public Deque buildDeque(String... values) {
Deque deque = new Deque();
for (String value : values) {
public <T> Deque<T> buildDeque(T... values) {
Deque<T> deque = new Deque<>();
for (T value : values) {
try {
// Create new Item
Item item = new Item(value);
Item<T> item = new Item<>(value);
// If deque is empty, set both front and back to this item
if (deque.peekFirst() == null) {
@@ -762,7 +834,7 @@ public class Tests {
setBack(deque, item);
} else {
// Add to the end (back) of the deque
Item currentBack = getBack(deque);
Item<T> currentBack = getBack(deque);
// Set the links
setNext(currentBack, item);
@@ -784,11 +856,12 @@ public class Tests {
* @param deque The deque to get the back item from.
* @return The back item, or null if the deque is empty.
*/
private Item getBack(Deque deque) {
@SuppressWarnings("unchecked")
private <T> Item<T> getBack(Deque<T> deque) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
return (Item) field.get(deque);
return (Item<T>) field.get(deque);
} catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
throw new RuntimeException("Error accessing getBack method", e);
}
@@ -800,7 +873,7 @@ public class Tests {
* @param deque The deque to set the front item for.
* @param front The front item to set.
*/
private void setFront(Deque deque, Item front) {
private <T> void setFront(Deque<T> deque, Item<T> front) {
try {
Field field = Deque.class.getDeclaredField("front");
field.setAccessible(true);
@@ -816,7 +889,7 @@ public class Tests {
* @param deque The deque to set the back item for.
* @param back The back item to set.
*/
private void setBack(Deque deque, Item back) {
private <T> void setBack(Deque<T> deque, Item<T> back) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
@@ -832,7 +905,7 @@ public class Tests {
* @param item The item to set the next item for.
* @param next The next item to set.
*/
private void setNext(Item item, Item next) {
private <T> void setNext(Item<T> item, Item<T> next) {
try {
Field field = Item.class.getDeclaredField("next");
field.setAccessible(true);
@@ -848,7 +921,7 @@ public class Tests {
* @param item The item to set the previous item for.
* @param prev The previous item to set.
*/
private void setPrev(Item item, Item prev) {
private <T> void setPrev(Item<T> item, Item<T> prev) {
try {
Field field = Item.class.getDeclaredField("prev");
field.setAccessible(true);
+21 -30
View File
@@ -4,17 +4,17 @@ import java.util.NoSuchElementException;
* Represents a double-ended queue (deque) that allows adding and removing items
* from both ends.
*/
public class Deque {
public class Deque<T> {
/**
* The front item of the deque.
*/
private Item front;
private Item<T> front;
/**
* The back item of the deque.
*/
private Item back;
private Item<T> back;
/**
* Constructs an empty deque.
@@ -29,7 +29,7 @@ public class Deque {
*
* @return The front item in the deque.
*/
private Item getFront() {
private Item<T> getFront() {
return front;
}
@@ -38,7 +38,7 @@ public class Deque {
*
* @return The back item in the deque.
*/
private Item getBack() {
private Item<T> getBack() {
return back;
}
@@ -47,7 +47,7 @@ public class Deque {
*
* @param front The item to set as the front.
*/
private void setFront(Item front) {
private void setFront(Item<T> front) {
this.front = front;
}
@@ -56,7 +56,7 @@ public class Deque {
*
* @param back The item to set as the back.
*/
private void setBack(Item back) {
private void setBack(Item<T> back) {
this.back = back;
}
@@ -65,17 +65,12 @@ public class Deque {
*
* @param value The value of the item to add.
*/
public void addFirst(String value) { // TODO: change
public void addFirst(Object value) { // TODO: change
if (value == null) {
// TODO: change
return;
}
if (value.isEmpty()) {
// TODO: change
return;
}
Item item = new Item(value);
if (isEmpty()) {
setFront(item);
@@ -92,18 +87,14 @@ public class Deque {
*
* @param value The value of the item to add.
*/
public void addLast(String value) { // TODO: change
public void addLast(Object value) { // TODO: change
if (value == null) {
// TODO: change
return;
}
if (value.isEmpty()) {
// TODO: change
return;
}
Item item = new Item(value);
// Item item = new Item(value);
Item<T> item = new Item(value);
if (isEmpty()) {
setFront(item);
setBack(item);
@@ -121,7 +112,7 @@ public class Deque {
* @return The value of the front item in the deque, or null if the deque is
* empty.
*/
public String peekFirst() {
public T peekFirst() {
if (isEmpty()) {
return null;
} else {
@@ -136,7 +127,7 @@ public class Deque {
* @return The value of the back item in the deque, or null if the deque is
* empty.
*/
public String peekLast() {
public T peekLast() {
if (isEmpty()) {
return null;
} else {
@@ -150,11 +141,11 @@ public class Deque {
*
* @return The value of the removed front item, or null if the deque is empty.
*/
public String pollFirst() {
public T pollFirst() {
if (isEmpty()) {
return null;
} else {
String value = getFront().getValue();
T value = getFront().getValue();
setFront(getFront().getNext());
if (getFront() == null) {
setBack(null);
@@ -169,11 +160,11 @@ public class Deque {
*
* @return The value of the removed back item, or null if the deque is empty.
*/
public String pollLast() {
public T pollLast() {
if (isEmpty()) {
return null;
} else {
String value = getBack().getValue();
T value = getBack().getValue();
setBack(getBack().getPrev());
if (getBack() == null) {
setFront(null);
@@ -191,7 +182,7 @@ public class Deque {
* @return The value of the first item in the deque.
* @throws NoSuchElementException if the deque is empty.
*/
public String getFirst() { // TODO: change
public Object getFirst() { // TODO: change
// TODO: add check
return getFront().getValue();
}
@@ -203,7 +194,7 @@ public class Deque {
* @return The value of the last item in the deque.
* @throws NoSuchElementException if the deque is empty.
*/
public String getLast() { // TODO: change
public Object getLast() { // TODO: change
// TODO: add check
return getBack().getValue();
}
@@ -215,7 +206,7 @@ public class Deque {
*/
public int size() {
int count = 0;
Item current = getFront();
Item<T> current = getFront();
while (current != null) {
count++;
current = current.getNext();
@@ -238,7 +229,7 @@ public class Deque {
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Item current = getFront();
Item<T> current = getFront();
sb.append("[");
while (current != null) {
sb.append(current.getValue());
-154
View File
@@ -1,154 +0,0 @@
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
@@ -1,88 +0,0 @@
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();
}
}
@@ -1,126 +0,0 @@
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");
}
}
-226
View File
@@ -1,226 +0,0 @@
import java.io.File;
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;
import java.util.Iterator;
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.length() != 0) {
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();
}
@Override
public boolean startsWith(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'startsWith'");
}
@Override
public boolean endsWith(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'endsWith'");
}
@Override
public Path resolve(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolve'");
}
@Override
public Path resolveSibling(Path other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolveSibling'");
}
@Override
public Path resolveSibling(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolveSibling'");
}
@Override
public File toFile() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'toFile'");
}
@Override
public WatchKey register(WatchService watcher, Kind<?>... events) throws IOException {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'register'");
}
@Override
public Iterator<Path> iterator() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'iterator'");
}
}
-44
View File
@@ -1,44 +0,0 @@
import java.nio.file.FileSystem;
import java.nio.file.Path;
public class InMemoryPathFactory {
private final InMemoryFileSystemProvider provider = new InMemoryFileSystemProvider();
private final InMemoryFileSystem fileSystem = new InMemoryFileSystem(provider);
/**
* Creates a new in-memory path
*
* @param path the path string
* @return a InMemoryPath that exists only in memory
*/
public Path createPath(String path) {
return new InMemoryPath(fileSystem, path);
}
/**
* Gets the in-memory file system instance
*
* @return the file system
*/
public FileSystem getFileSystem() {
return fileSystem;
}
/**
* Clears all data from the in-memory file system
*/
public 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 boolean exists(Path path) {
return InMemoryFileSystem.getStorage().containsKey(path.toString());
}
}
+11 -11
View File
@@ -1,29 +1,29 @@
/**
* Represents an item in a doubly linked deque.
*/
public class Item {
public class Item<T> {
/**
* The value of the item.
*/
private String value;
private T value;
/**
* The previous item in the deque.
*/
private Item prev;
private Item<T> prev;
/**
* The next item in the deque.
*/
private Item next;
private Item<T> next;
/**
* Constructor for creating a new item.
*
* @param value The value of the item.
*/
public Item(String value) {
public Item(T value) {
this.value = value;
this.prev = null;
this.next = null;
@@ -34,7 +34,7 @@ public class Item {
*
* @return The value of the item.
*/
public String getValue() {
public T getValue() {
return value;
}
@@ -43,7 +43,7 @@ public class Item {
*
* @param value The value of the item.
*/
public void setValue(String value) {
public void setValue(T value) {
this.value = value;
}
@@ -52,7 +52,7 @@ public class Item {
*
* @return The previous item in the deque.
*/
public Item getPrev() {
public Item<T> getPrev() {
return prev;
}
@@ -61,7 +61,7 @@ public class Item {
*
* @param prev The previous item in the deque.
*/
public void setPrev(Item prev) {
public void setPrev(Item<T> prev) {
this.prev = prev;
}
@@ -70,7 +70,7 @@ public class Item {
*
* @return The next item in the deque.
*/
public Item getNext() {
public Item<T> getNext() {
return next;
}
@@ -79,7 +79,7 @@ public class Item {
*
* @param next The next item in the deque.
*/
public void setNext(Item next) {
public void setNext(Item<T> next) {
this.next = next;
}
+1 -60
View File
@@ -33,66 +33,7 @@ public class Main {
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();
InMemoryPathFactory factory = new InMemoryPathFactory();
Path erlkingPath = factory.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("Aufgabe 2 - Deque");
System.out.println("=========================================");
System.out.println();
@@ -1,33 +0,0 @@
import java.nio.file.Path;
import java.util.ArrayList;
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 new ArrayList<>();
}
}
+199 -126
View File
@@ -1,8 +1,7 @@
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.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -133,104 +132,175 @@ public class Tests {
addPoints(points);
}
// Aufgabe 2 - IO - 20 Punkte
// Aufgabe 2 - Generic Deque - 20 Punkte
@Test(name = "Aufgabe 2 - IO - write - 10 Punkte")
public void testIOWrite() {
int points = 10;
@Test(name = "Aufgabe 2 - Deque - addFirst - takes generic type - 5 Punkte")
public void testDequeAddFirstGeneric() {
int points = 5;
StringListSerializer serializer = new StringListSerializer();
InMemoryPathFactory factory = new InMemoryPathFactory();
Path path = factory.createPath("/test/write.txt");
List<String> data = Arrays.asList("Hello", "World", "This is a test");
serializer.write(path, data);
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.");
if (!isDequeAdderGeneric("addFirst")) {
points -= 5;
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - IO - read - errorless- 5 Punkte")
public void testIOReadErrorless() {
@Test(name = "Aufgabe 2 - Deque - addLast - takes generic type - 5 Punkte")
public void testDequeAddLastGeneric() {
int points = 5;
StringListSerializer serializer = new StringListSerializer();
InMemoryPathFactory factory = new InMemoryPathFactory();
Path path = factory.createPath("/test/read.txt");
List<String> data = Arrays.asList("Hello", "World", "This is a test");
try {
Files.write(path, data);
} catch (IOException e) {
if (!isDequeAdderGeneric("addLast")) {
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() {
@Test(name = "Aufgabe 2 - Deque - getFirst - returns generic type - 5 Punkte")
public void testDequeGetFirstGeneric() {
int points = 5;
if (alwaysEmptyRead()) {
TracingFramework.printError(
"Reading from non-empty file returns empty list. Assuming read always returns empty list. Deducting 5 points.");
addPoints(0);
return;
if (!isDequeGetterGeneric("getFirst")) {
points -= 5;
}
StringListSerializer serializer = new StringListSerializer();
InMemoryPathFactory factory = new InMemoryPathFactory();
Path path = factory.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.");
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - getLast - returns generic type - 5 Punkte")
public void testDequeGetLastGeneric() {
int points = 5;
if (!isDequeGetterGeneric("getLast")) {
points -= 5;
}
addPoints(points);
}
/**
* Checks if an adder method takes the generic type parameter.
*
* @param name The name of the method.
* @return true if the method takes the generic type parameter, false otherwise.
*/
@SuppressWarnings("rawtypes")
private boolean isDequeAdderGeneric(String name) {
TypeVariable<Class<Deque>> classTypeParameter = getClassTypeParameter();
if (classTypeParameter == null) {
return false;
}
Method method = findUniqueMethod(Deque.class, name);
if (method == null) {
TracingFramework.printError("Method Deque." + name + " not found. Class was mutated illegally.");
return false;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (genericParameterTypes.length != 1) {
TracingFramework.printError("Deque." + name + " should take one parameter, but takes "
+ genericParameterTypes.length + " parameters.");
return false;
}
Type paramType = genericParameterTypes[0];
if (paramType instanceof TypeVariable) {
TypeVariable<?> typeVar = (TypeVariable<?>) paramType;
if (!typeVar.getName().equals(classTypeParameter.getName())) {
TracingFramework.printError("Deque." + name + " should take the generic type parameter, but takes "
+ typeVar.getName() + " instead.");
return false;
}
} 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;
} else {
TracingFramework.printError("Deque." + name + " should take the generic type parameter, but takes "
+ paramType.getTypeName() + " instead.");
return false;
}
return true;
}
/**
* Checks if a getter method returns the generic type parameter.
*
* @param name The name of the method.
* @return true if the method returns the generic type parameter, false
* otherwise.
*/
@SuppressWarnings("rawtypes")
private boolean isDequeGetterGeneric(String name) {
TypeVariable<Class<Deque>> classTypeParameter = getClassTypeParameter();
if (classTypeParameter == null) {
return false;
}
Method method = findUniqueMethod(Deque.class, name);
if (method == null) {
TracingFramework.printError("Method Deque." + name + " not found. Class was mutated illegally.");
return false;
}
if (!returnsGenericClassType(method, classTypeParameter.getName())) {
return false;
}
return true;
}
/**
* Checks if a method returns the generic type parameter of the class.
*
* @param method The method to check.
* @param classTypeParameterName The name of the class's generic type parameter.
* @return true if the method returns the generic type parameter, false
* otherwise.
*/
private boolean returnsGenericClassType(Method method, String classTypeParameterName) {
Type returnType = method.getGenericReturnType();
String methodName = method.getName();
if (returnType instanceof TypeVariable) {
TypeVariable<?> typeVar = (TypeVariable<?>) returnType;
if (!typeVar.getName().equals(classTypeParameterName)) {
TracingFramework
.printError("Reading from /test/forcedIOException.txt path throws an unexpected exception: "
+ e.getMessage());
.printError("Deque." + methodName + " should return the generic type parameter, but returns "
+ typeVar.getName() + " instead.");
return false;
}
} else {
TracingFramework
.printError("Deque." + methodName + " should return the generic type parameter, but returns "
+ returnType.getTypeName() + " instead.");
return false;
}
addPoints(points);
return true;
}
// Aufgabe 3 - Deque - 20 Punkte
/**
* Gets the generic type parameter of the Deque class.
*
* @return The generic type parameter of the Deque class, null if not found.
*/
@SuppressWarnings("rawtypes")
private TypeVariable<Class<Deque>> getClassTypeParameter() {
Class<Deque> clazz = Deque.class;
TypeVariable<Class<Deque>>[] classTypeParameters = clazz.getTypeParameters();
if (classTypeParameters.length != 1) {
TracingFramework.printError("Deque should have one generic type parameter, but has "
+ classTypeParameters.length + " parameters.");
return null;
}
TypeVariable<Class<Deque>> classTypeParameter = classTypeParameters[0];
if (!classTypeParameter.getName().equals("T")) {
TracingFramework.printError("Deque's generic type parameter should be named T, but is named "
+ classTypeParameter.getName() + " instead.");
return null;
}
return classTypeParameter;
}
// Aufgabe 3 - Deque Exception - 20 Punkte
@Test(name = "Aufgabe 3 - Deque - addFirst null - 3 Punkte")
public void testDequeAddFirstNull() {
@@ -242,7 +312,7 @@ public class Tests {
"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 deque = new Deque();
Deque<String> deque = new Deque<>();
deque.addFirst(null);
points -= 3;
TracingFramework
@@ -276,7 +346,7 @@ public class Tests {
"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 deque = new Deque();
Deque<String> deque = new Deque<>();
deque.addFirst("");
points -= 3;
TracingFramework
@@ -304,7 +374,7 @@ public class Tests {
public void testDequeAddFirstThrowsIllegalArgumentException() {
int points = 2;
Method method = findMethod(Deque.class, "addFirst", String.class);
Method method = findUniqueMethod(Deque.class, "addFirst");
if (method == null) {
TracingFramework.printError("Method Deque.addFirst(String) not found. Class was mutated illegally.");
addPoints(0);
@@ -341,7 +411,7 @@ public class Tests {
"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();
Deque<String> deque = new Deque<>();
deque.addLast(null);
points -= 3;
TracingFramework
@@ -375,7 +445,7 @@ public class Tests {
"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();
Deque<String> deque = new Deque<>();
deque.addLast("");
points -= 3;
TracingFramework
@@ -440,7 +510,7 @@ public class Tests {
"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<String> deque = new Deque<>();
deque.getFirst();
points -= 2;
TracingFramework
@@ -507,7 +577,7 @@ public class Tests {
"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<String> deque = new Deque<>();
deque.getLast();
points -= 2;
TracingFramework
@@ -563,30 +633,6 @@ public class Tests {
addPoints(points);
}
/**
* Checks if reading from a non-empty file always returns an empty list.
*
* @return True if reading always returns an empty list, false otherwise.
*/
private boolean alwaysEmptyRead() {
InMemoryPathFactory factory = new InMemoryPathFactory();
Path path = factory.createPath("/test/foo.txt");
List<String> content = Arrays.asList("This", "is", "not", "empty");
try {
Files.write(path, content);
} catch (IOException e) {
return false;
}
StringListSerializer serializer = new StringListSerializer();
try {
List<String> readData = serializer.read(path);
return readData != null && readData.isEmpty();
} catch (Exception e) {
return false;
}
}
/**
* Builds a binary tree from an array from top to bottom and left to right.
*
@@ -643,6 +689,30 @@ public class Tests {
}
}
/**
* Finds a unique method in a class by name.
*
* @param clazz The class to search in.
* @param name The name of the method.
* @return The found method, or null if not found or more than one method with
* the same name exists.
*/
public static Method findUniqueMethod(Class<?> clazz, String name) {
Method[] methods = clazz.getDeclaredMethods();
Method found = null;
for (Method method : methods) {
if (method.getName().equals(name)) {
if (found != null) {
TracingFramework.printError("More than one method named " + name
+ " found in class " + clazz.getName() + ". Class was mutated illegally.");
return null;
}
found = method;
}
}
return found;
}
/**
* START: Deque helper methods
*/
@@ -656,7 +726,7 @@ public class Tests {
* @return True if addFirst throws any exception, false otherwise.
*/
private boolean addFirstAlwaysException() {
Deque deque = new Deque();
Deque<String> deque = new Deque<>();
return adderThrowsAnyException(deque::addFirst, "A", "BCDEF", "Hallo");
}
@@ -669,7 +739,7 @@ public class Tests {
* @return True if addLast throws any exception, false otherwise.
*/
private boolean addLastAlwaysException() {
Deque deque = new Deque();
Deque<String> deque = new Deque<>();
return adderThrowsAnyException(deque::addLast, "A", "BCDEF", "Hallo");
}
@@ -687,9 +757,9 @@ public class Tests {
adder.accept(value);
}
} catch (Exception e) {
return false;
return true;
}
return true;
return false;
}
/**
@@ -702,9 +772,10 @@ public class Tests {
* @return True if the getter throws any exception, false otherwise.
*/
private boolean getFirstAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
Deque<String> deque = buildDeque("A", "B", "C", "D", "E");
// should be executable five times when deque is not empty
return getterThrowsAnyException(deque::getFirst, deque::pollFirst, 5);
Supplier<String> getter = () -> deque.getFirst().toString();
return getterThrowsAnyException(getter, deque::pollFirst, 5);
}
/**
@@ -717,9 +788,10 @@ public class Tests {
* @return True if getLast throws any exception, false otherwise.
*/
private boolean getLastAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
Deque<String> deque = buildDeque("A", "B", "C", "D", "E");
// should be executable five times when deque is not empty
return getterThrowsAnyException(deque::getLast, deque::pollLast, 5);
Supplier<String> getter = () -> deque.getLast().toString();
return getterThrowsAnyException(getter, deque::pollLast, 5);
}
/**
@@ -749,12 +821,12 @@ public class Tests {
* @param values The values to add.
* @return The built deque.
*/
public Deque buildDeque(String... values) {
Deque deque = new Deque();
for (String value : values) {
public <T> Deque<T> buildDeque(T... values) {
Deque<T> deque = new Deque<>();
for (T value : values) {
try {
// Create new Item
Item item = new Item(value);
Item<T> item = new Item<>(value);
// If deque is empty, set both front and back to this item
if (deque.peekFirst() == null) {
@@ -762,7 +834,7 @@ public class Tests {
setBack(deque, item);
} else {
// Add to the end (back) of the deque
Item currentBack = getBack(deque);
Item<T> currentBack = getBack(deque);
// Set the links
setNext(currentBack, item);
@@ -784,11 +856,12 @@ public class Tests {
* @param deque The deque to get the back item from.
* @return The back item, or null if the deque is empty.
*/
private Item getBack(Deque deque) {
@SuppressWarnings("unchecked")
private <T> Item<T> getBack(Deque<T> deque) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
return (Item) field.get(deque);
return (Item<T>) field.get(deque);
} catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
throw new RuntimeException("Error accessing getBack method", e);
}
@@ -800,7 +873,7 @@ public class Tests {
* @param deque The deque to set the front item for.
* @param front The front item to set.
*/
private void setFront(Deque deque, Item front) {
private <T> void setFront(Deque<T> deque, Item<T> front) {
try {
Field field = Deque.class.getDeclaredField("front");
field.setAccessible(true);
@@ -816,7 +889,7 @@ public class Tests {
* @param deque The deque to set the back item for.
* @param back The back item to set.
*/
private void setBack(Deque deque, Item back) {
private <T> void setBack(Deque<T> deque, Item<T> back) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
@@ -832,7 +905,7 @@ public class Tests {
* @param item The item to set the next item for.
* @param next The next item to set.
*/
private void setNext(Item item, Item next) {
private <T> void setNext(Item<T> item, Item<T> next) {
try {
Field field = Item.class.getDeclaredField("next");
field.setAccessible(true);
@@ -848,7 +921,7 @@ public class Tests {
* @param item The item to set the previous item for.
* @param prev The previous item to set.
*/
private void setPrev(Item item, Item prev) {
private <T> void setPrev(Item<T> item, Item<T> prev) {
try {
Field field = Item.class.getDeclaredField("prev");
field.setAccessible(true);