Storage was replaced by FileSystem

This commit is contained in:
Robert Vokac 2024-10-12 09:09:28 +02:00
parent 21aff3602f
commit ac7eb2e78b
Signed by: robertvokac
GPG Key ID: FB9CE8E20AADA55F
33 changed files with 564 additions and 539 deletions

View File

@ -25,7 +25,7 @@ import java.util.List;
* *
* @author robertvokac * @author robertvokac
*/ */
public interface FileHandle { public interface File {
FileType type(); FileType type();
@ -37,7 +37,7 @@ public interface FileHandle {
String nameWithoutExtension(); String nameWithoutExtension();
List<FileHandle> list(); List<File> list();
default boolean isDirectory() { default boolean isDirectory() {
return type() == FileType.DIRECTORY; return type() == FileType.DIRECTORY;
@ -47,11 +47,11 @@ public interface FileHandle {
return type() == FileType.FILE; return type() == FileType.FILE;
} }
FileHandle child(String name); File child(String name);
FileHandle sibling(String name); File sibling(String name);
FileHandle parent(); File parent();
boolean mkdir(); boolean mkdir();
@ -65,15 +65,15 @@ public interface FileHandle {
boolean emptyDirectory(); boolean emptyDirectory();
boolean copyTo(FileHandle destination); boolean copyTo(File destination);
boolean moveTo(FileHandle destination); boolean moveTo(File destination);
long length(); long length();
FileHandle tempFile(String prefix); File tempFile(String prefix);
FileHandle tempDirectory(String prefix); File tempDirectory(String prefix);
int depth(); int depth();
@ -89,5 +89,5 @@ public interface FileHandle {
void flush(); void flush();
Storage getStorage(); FileSystem getFileSystem();
} }

View File

@ -22,19 +22,19 @@ package com.pixelgamelibrary.api.files;
import com.pixelgamelibrary.api.PixelException; import com.pixelgamelibrary.api.PixelException;
/** /**
* StorageException is a custom exception class that extends {@link PixelException}. * FileException is a custom exception class that extends {@link PixelException}.
* It represents exceptions that occur within the storage system of the Pixel Game Library. * It represents exceptions that occur within the file system of the Pixel Game Library.
* *
* @author robertvokac * @author robertvokac
*/ */
public class StorageException extends PixelException { public class FileException extends PixelException {
/** /**
* Constructs a new StorageException with the specified detail message. * Constructs a new FileException with the specified detail message.
* *
* @param string the detail message for this exception. * @param string the detail message for this exception.
*/ */
public StorageException(String string) { public FileException(String string) {
super(string); super(string);
} }

View File

@ -27,15 +27,15 @@ import java.util.List;
* *
* @author robertvokac * @author robertvokac
*/ */
public class FileHandleImpl implements FileHandle { public class FileImpl implements File {
private final Storage storage; private final FileSystem fs;
private final String path; private final String path;
private String name; private String name;
public FileHandleImpl(Storage storage, String path) { public FileImpl(FileSystem fsIn, String path) {
this.storage = storage; this.fs = fsIn;
this.path = path.equals(".") ? storage.printWorkingDirectory() : path; this.path = path.equals(".") ? fsIn.printWorkingDirectory() : path;
{ {
if (path.equals("/")) { if (path.equals("/")) {
name = path; name = path;
@ -48,7 +48,7 @@ public class FileHandleImpl implements FileHandle {
@Override @Override
public FileType type() { public FileType type() {
return storage.type(path); return fs.type(path);
} }
@Override @Override
@ -78,36 +78,36 @@ public class FileHandleImpl implements FileHandle {
} }
@Override @Override
public List<FileHandle> list() { public List<File> list() {
List<String> list = storage.list(path); List<String> list = fs.list(path);
List<FileHandle> files = new ArrayList<>(); List<File> files = new ArrayList<>();
for(String s:list) { for(String s:list) {
files.add(new FileHandleImpl(storage, s)); files.add(new FileImpl(fs, s));
} }
return files; return files;
} }
@Override @Override
public FileHandle child(String name) { public File child(String name) {
return new FileHandleImpl(storage, path + "/" + name); return new FileImpl(fs, path + "/" + name);
} }
@Override @Override
public FileHandle sibling(String siblingName) { public File sibling(String siblingName) {
int nameLength = name.length(); int nameLength = name.length();
String f = path.substring(0, path.length() - nameLength - 1) + "/" + siblingName; String f = path.substring(0, path.length() - nameLength - 1) + "/" + siblingName;
return new FileHandleImpl(storage, f); return new FileImpl(fs, f);
} }
@Override @Override
public FileHandle parent() { public File parent() {
return new FileHandleImpl(storage, path.substring(0, path.length() - name.length() - 1)); return new FileImpl(fs, path.substring(0, path.length() - name.length() - 1));
} }
@Override @Override
public boolean mkdir() { public boolean mkdir() {
return storage.createDirectory(path).isEmpty(); return fs.createDirectory(path).isEmpty();
} }
@Override @Override
@ -117,17 +117,17 @@ public class FileHandleImpl implements FileHandle {
@Override @Override
public boolean exists() { public boolean exists() {
return storage.exists(path); return fs.exists(path);
} }
@Override @Override
public boolean delete() { public boolean delete() {
return storage.remove(path); return fs.remove(path);
} }
@Override @Override
public boolean deleteDirectory() { public boolean deleteDirectory() {
return storage.removeDirectory(path); return fs.removeDirectory(path);
} }
@Override @Override
@ -136,13 +136,13 @@ public class FileHandleImpl implements FileHandle {
} }
@Override @Override
public boolean copyTo(FileHandle destination) { public boolean copyTo(File destination) {
return storage.copy(path, destination.path()).isEmpty(); return fs.copy(path, destination.path()).isEmpty();
} }
@Override @Override
public boolean moveTo(FileHandle destination) { public boolean moveTo(File destination) {
return storage.move(path, destination.path()).isEmpty(); return fs.move(path, destination.path()).isEmpty();
} }
@Override @Override
@ -150,7 +150,7 @@ public class FileHandleImpl implements FileHandle {
if(isDirectory()) { if(isDirectory()) {
return 0; return 0;
} }
RegularFileType rft = storage.getRegularFileType(path); RegularFileType rft = fs.getRegularFileType(path);
switch(rft){ switch(rft){
case TEXT: return readString().length(); case TEXT: return readString().length();
case BINARY: return readBytes().length; case BINARY: return readBytes().length;
@ -159,11 +159,11 @@ public class FileHandleImpl implements FileHandle {
} }
@Override @Override
public FileHandle tempFile(String prefix) { public File tempFile(String prefix) {
createTmpDirectoryIfDoesNotYetExist(); createTmpDirectoryIfDoesNotYetExist();
String r = createRandomName(); String r = createRandomName();
storage.touch(r); fs.touch(r);
return new FileHandleImpl(storage, "/tmp/"+r); return new FileImpl(fs, "/tmp/"+r);
} }
private String createRandomName() { private String createRandomName() {
@ -174,51 +174,51 @@ public class FileHandleImpl implements FileHandle {
} }
private void createTmpDirectoryIfDoesNotYetExist() { private void createTmpDirectoryIfDoesNotYetExist() {
if(!storage.exists("/tmp")) { if(!fs.exists("/tmp")) {
storage.createDirectory("/tmp"); fs.createDirectory("/tmp");
} }
} }
@Override @Override
public FileHandle tempDirectory(String prefix) { public File tempDirectory(String prefix) {
createTmpDirectoryIfDoesNotYetExist(); createTmpDirectoryIfDoesNotYetExist();
String r = createRandomName(); String r = createRandomName();
storage.createDirectory(r); fs.createDirectory(r);
return new FileHandleImpl(storage, "/tmp/"+r); return new FileImpl(fs, "/tmp/"+r);
} }
@Override @Override
public int depth() { public int depth() {
return storage.depth(path); return fs.depth(path);
} }
@Override @Override
public boolean writeString(String text) { public boolean writeString(String text) {
return storage.writeString(path, text).isEmpty(); return fs.writeString(path, text).isEmpty();
} }
@Override @Override
public boolean appendString(String text public boolean appendString(String text
) { ) {
String textCurrent = readString(); String textCurrent = readString();
return storage.writeString(path, textCurrent + text).isEmpty(); return fs.writeString(path, textCurrent + text).isEmpty();
} }
@Override @Override
public String readString() { public String readString() {
return storage.readString(path); return fs.readString(path);
} }
@Override @Override
public boolean writeBytes(byte[] data public boolean writeBytes(byte[] data
) { ) {
return storage.writeBytes(path, data).isEmpty(); return fs.writeBytes(path, data).isEmpty();
} }
@Override @Override
public byte[] readBytes() { public byte[] readBytes() {
return storage.readBytes(path); return fs.readBytes(path);
} }
@Override @Override
@ -227,7 +227,7 @@ public class FileHandleImpl implements FileHandle {
} }
@Override @Override
public Storage getStorage() { public FileSystem getFileSystem() {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
} }

View File

@ -23,18 +23,18 @@ import com.pixelgamelibrary.api.Platform;
import java.util.List; import java.util.List;
/** /**
* This interface provides the methods to interact with the underlying storage * This interface provides the methods to interact with the underlying file system
* system. It supports basic file system operations such as navigating * system. It supports basic file system operations such as navigating
* directories, creating files and directories, and reading/writing data. * directories, creating files and directories, and reading/writing data.
* *
* @author robertvokac * @author robertvokac
*/ */
public interface Storage { public interface FileSystem {
public String SLASH = "/"; public String SLASH = "/";
/** /**
* Returns the platform associated with this storage. * Returns the platform associated with this file system.
* *
* @return the platform object. * @return the platform object.
*/ */
@ -55,11 +55,11 @@ public interface Storage {
* @return a result message or an empty string if successful. * @return a result message or an empty string if successful.
*/ */
default String changeDirectory() { default String changeDirectory() {
Storage.this.changeDirectory("/"); FileSystem.this.changeDirectory("/");
createDirectory("home"); createDirectory("home");
Storage.this.changeDirectory("home"); FileSystem.this.changeDirectory("home");
createDirectory(getUserName()); createDirectory(getUserName());
Storage.this.changeDirectory(getUserName()); FileSystem.this.changeDirectory(getUserName());
return ""; return "";
} }
@ -242,19 +242,19 @@ public interface Storage {
/** /**
* Returns a debug string with information about the current state of the * Returns a debug string with information about the current state of the
* storage. * file system.
* *
* @return a debug string. * @return a debug string.
*/ */
public String debug(); public String debug();
/** /**
* Flushes any pending writes to the storage. * Flushes any pending writes to the file system.
*/ */
public void flush(); public void flush();
/** /**
* Returns the username associated with this storage. * Returns the username associated with this file system.
* *
* @return the username. * @return the username.
*/ */
@ -263,7 +263,7 @@ public interface Storage {
} }
/** /**
* If the size of this storage is limited, returns the number of bytes it is * If the size of this file system is limited, returns the number of bytes it is
* limited to. Otherwise, returns 0. * limited to. Otherwise, returns 0.
* *
* @return the size limit in bytes, or 0 if there is no limit. * @return the size limit in bytes, or 0 if there is no limit.
@ -273,16 +273,16 @@ public interface Storage {
} }
/** /**
* The default username for the storage. * The default username for the file system.
*/ */
static final String USER = "user"; static final String USER = "user";
default FileHandle file(String path) { default File file(String path) {
path = convertToAbsolutePathIfNeeded(path); path = convertToAbsolutePathIfNeeded(path);
return new FileHandleImpl(this, path); return new FileImpl(this, path);
} }
default FileHandle file() { default File file() {
return file(printWorkingDirectory()); return file(printWorkingDirectory());
} }
@ -322,7 +322,7 @@ public interface Storage {
} }
/** /**
* Saves and returns the current state of the storage. * Saves and returns the current state of the file system.
* *
* @param methodName * @param methodName
* @return * @return
@ -330,7 +330,7 @@ public interface Storage {
byte[] backup(String methodName); byte[] backup(String methodName);
/** /**
* Replaces the current content of the storage. * Replaces the current content of the file system.
* @param methodName * @param methodName
* @param data * @param data
*/ */
@ -339,12 +339,12 @@ public interface Storage {
boolean isReadonly(); boolean isReadonly();
/** /**
* Returns the maximum size in count of bytes of the storage. If the maximum * Returns the maximum size in count of bytes of the file system. If the maximum
* size is not defined for this storage, then 0 is returned. default long * size is not defined for this file system, then 0 is returned. default long
* getMaxSize() { return 0; } * getMaxSize() { return 0; }
* *
* /** * /**
* Deletes all the content in the storage. * Deletes all the content in the file system.
*/ */
void clear(); void clear();
@ -352,5 +352,5 @@ public interface Storage {
long size(); long size();
StorageType getStorageType(); FileSystemType getFileSystemType();
} }

View File

@ -23,7 +23,7 @@ package com.pixelgamelibrary.api.files;
* *
* @author robertvokac * @author robertvokac
*/ */
public enum StorageType { public enum FileSystemType {
ASSETS, ASSETS,
LOCAL, LOCAL,
EXTERNAL, EXTERNAL,

View File

@ -23,48 +23,48 @@ import com.pixelgamelibrary.api.Pixel;
import com.pixelgamelibrary.api.Platform; import com.pixelgamelibrary.api.Platform;
import com.pixelgamelibrary.api.files.FileType; import com.pixelgamelibrary.api.files.FileType;
import com.pixelgamelibrary.api.files.RegularFileType; import com.pixelgamelibrary.api.files.RegularFileType;
import com.pixelgamelibrary.api.files.StorageException; import com.pixelgamelibrary.api.files.FileException;
import com.pixelgamelibrary.api.files.Storage; import com.pixelgamelibrary.api.files.FileSystemType;
import com.pixelgamelibrary.api.files.StorageType;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.pixelgamelibrary.api.files.FileSystem;
/** /**
* Implementation of the Storage interface for managing a map-based file system. * Implementation of the FileSystem interface for managing a map-based file system.
* Provides methods to interact with files and directories stored in a map. * Provides methods to interact with files and directories stored in a map.
* *
* @author robertvokac * @author robertvokac
*/ */
public class MapStorage implements Storage { public class MapFileSystem implements FileSystem {
private final SimpleMap map; private final SimpleMap map;
private final MapStorageCompression mapStorageCompression; private final MapFileSystemCompression mapFileSystemCompression;
/** /**
* Constructs a MapStorage instance with the specified map and default * Constructs a MapFileSystem instance with the specified map and default
* compression. * compression.
* *
* @param mapIn the map to be used for storage * @param mapIn the map to be used for file system
*/ */
public MapStorage(SimpleMap mapIn) { public MapFileSystem(SimpleMap mapIn) {
this(mapIn, MapStorageCompression.LZMA); this(mapIn, MapFileSystemCompression.LZMA);
} }
/** /**
* Constructs a MapStorage instance with the specified map and compression. * Constructs a MapFileSystem instance with the specified map and compression.
* *
* @param mapIn the map to be used for storage * @param mapIn the map to be used for file system
* @param mapStorageCompressionIn the compression method to be used * @param mapFileSystemCompressionIn the compression method to be used
*/ */
public MapStorage(SimpleMap mapIn, MapStorageCompression mapStorageCompressionIn) { public MapFileSystem(SimpleMap mapIn, MapFileSystemCompression mapFileSystemCompressionIn) {
this.map = mapIn; this.map = mapIn;
this.mapStorageCompression = mapStorageCompressionIn; this.mapFileSystemCompression = mapFileSystemCompressionIn;
if (map.contains("system.compression")) { if (map.contains("system.compression")) {
if (!map.getString("system.compression").equals(this.mapStorageCompression.name())) { if (!map.getString("system.compression").equals(this.mapFileSystemCompression.name())) {
throw new StorageException("Fatal error, compression method passed to the constructor is different, than the compression method in the map (key system.compression)."); throw new FileException("Fatal error, compression method passed to the constructor is different, than the compression method in the map (key system.compression).");
} }
} else { } else {
map.putString("system.compression", mapStorageCompression.name()); map.putString("system.compression", mapFileSystemCompression.name());
} }
createDirectory("/"); // Initialize the root directory createDirectory("/"); // Initialize the root directory
} }
@ -141,14 +141,14 @@ public class MapStorage implements Storage {
* *
* @param path the path to get the parent of * @param path the path to get the parent of
* @return the parent path * @return the parent path
* @throws StorageException if the path is null or empty * @throws FileException if the path is null or empty
*/ */
private static String getParentPath(String path) { private static String getParentPath(String path) {
if (path == null) { if (path == null) {
throw new StorageException("Path is null"); throw new FileException("Path is null");
} }
if (path.trim().isEmpty()) { if (path.trim().isEmpty()) {
throw new StorageException("Path is empty"); throw new FileException("Path is empty");
} }
if (path.equals("/")) { if (path.equals("/")) {
@ -247,10 +247,10 @@ public class MapStorage implements Storage {
*/ */
private String moveOrCp(String source, String target, boolean move, boolean cp) { private String moveOrCp(String source, String target, boolean move, boolean cp) {
if (move && cp) { if (move && cp) {
throw new StorageException("move == true && cp == true"); throw new FileException("move == true && cp == true");
} }
if (!move && !cp) { if (!move && !cp) {
throw new StorageException("move != true && cp != true"); throw new FileException("move != true && cp != true");
} }
String absolutePathSource = convertToAbsolutePathIfNeeded(source); String absolutePathSource = convertToAbsolutePathIfNeeded(source);
String absolutePathTarget = convertToAbsolutePathIfNeeded(target); String absolutePathTarget = convertToAbsolutePathIfNeeded(target);
@ -318,8 +318,8 @@ public class MapStorage implements Storage {
} }
text = text.substring(BINARYFILE.length()); text = text.substring(BINARYFILE.length());
byte[] data = Pixel.utils().decodeBase64AsByteArray(text); byte[] data = Pixel.utils().decodeBase64AsByteArray(text);
if (this.mapStorageCompression != MapStorageCompression.NONE) { if (this.mapFileSystemCompression != MapFileSystemCompression.NONE) {
data = Pixel.utils().decompress(data, mapStorageCompression.name()); data = Pixel.utils().decompress(data, mapFileSystemCompression.name());
} }
return data; return data;
} }
@ -331,8 +331,8 @@ public class MapStorage implements Storage {
@Override @Override
public String writeBytes(String name, byte[] data) { public String writeBytes(String name, byte[] data) {
if (this.mapStorageCompression != MapStorageCompression.NONE) { if (this.mapFileSystemCompression != MapFileSystemCompression.NONE) {
data = Pixel.utils().compress(data, mapStorageCompression.name()); data = Pixel.utils().compress(data, mapFileSystemCompression.name());
} }
return writeString(name, BINARYFILE + Pixel.utils().encodeToBase64(data)); return writeString(name, BINARYFILE + Pixel.utils().encodeToBase64(data));
} }
@ -440,7 +440,7 @@ public class MapStorage implements Storage {
} }
@Override @Override
public StorageType getStorageType() { public FileSystemType getFileSystemType() {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
} }
} }

View File

@ -23,6 +23,6 @@ package com.pixelgamelibrary.api.files.map;
* *
* @author robertvokac * @author robertvokac
*/ */
public enum MapStorageCompression { public enum MapFileSystemCompression {
NONE, LZMA; NONE, LZMA;
} }

View File

@ -21,7 +21,7 @@
package com.pixelgamelibrary.api.files.map; package com.pixelgamelibrary.api.files.map;
import com.pixelgamelibrary.api.files.FileType; import com.pixelgamelibrary.api.files.FileType;
import com.pixelgamelibrary.api.files.StorageException; import com.pixelgamelibrary.api.files.FileException;
import static com.pixelgamelibrary.api.files.FileType.DIRECTORY; import static com.pixelgamelibrary.api.files.FileType.DIRECTORY;
import static com.pixelgamelibrary.api.files.FileType.FILE; import static com.pixelgamelibrary.api.files.FileType.FILE;
@ -36,22 +36,22 @@ public class MapFileType {
/** /**
* Determines the MapFileType based on the value associated with the specified key in the map. * Determines the MapFileType based on the value associated with the specified key in the map.
* Throws a StorageException if the key is not found or if the value does not match any known type. * Throws a FileException if the key is not found or if the value does not match any known type.
* *
* @param key the key whose associated value determines the file type * @param key the key whose associated value determines the file type
* @param map the map from which to retrieve the value * @param map the map from which to retrieve the value
* @return the MapFileType corresponding to the value in the map * @return the MapFileType corresponding to the value in the map
* @throws StorageException if the key is not present in the map or if the value does not match FILE or DIRECTORY * @throws FileException if the key is not present in the map or if the value does not match FILE or DIRECTORY
*/ */
public static FileType ofKey(String key, SimpleMap map) { public static FileType ofKey(String key, SimpleMap map) {
// Check if the map contains the specified key // Check if the map contains the specified key
if (!map.contains(key)) { if (!map.contains(key)) {
throw new StorageException("Map does not contain key: " + key); throw new FileException("Map does not contain key: " + key);
} }
// Retrieve the value associated with the key // Retrieve the value associated with the key
String value = map.getString(key); String value = map.getString(key);
if(value == null) { if(value == null) {
throw new StorageException("Value is null for key: " + key); throw new FileException("Value is null for key: " + key);
} }
// Determine the MapFileType based on the value // Determine the MapFileType based on the value
if (value.startsWith(FILE.name())) { if (value.startsWith(FILE.name())) {
@ -61,6 +61,6 @@ public class MapFileType {
return DIRECTORY; return DIRECTORY;
} }
// Throw an exception if the value does not match known types // Throw an exception if the value does not match known types
throw new StorageException("Unsupported MapFileType for key in the map: " + key); throw new FileException("Unsupported MapFileType for key in the map: " + key);
} }
} }

View File

@ -23,21 +23,21 @@ package com.pixelgamelibrary.api.files.map;
import com.pixelgamelibrary.api.Platform; import com.pixelgamelibrary.api.Platform;
/** /**
* Implementation of Storage that uses an in-memory map for storing data. * Implementation of FileSystem that uses an in-memory map for storing data.
* Extends the MapStorage class to utilize a SimpleJavaMap for internal storage. * Extends the MapFileSystem class to utilize a SimpleJavaMap for internal file system.
* *
* This class is used when you need a temporary storage solution that * This class is used when you need a temporary file system solution that
* does not persist data beyond the runtime of the application. * does not persist data beyond the runtime of the application.
* *
* @author robertvokac * @author robertvokac
*/ */
public class MemoryStorage extends MapStorage { public class MemoryFileSystem extends MapFileSystem {
/** /**
* Constructs a MemoryStorage instance using a SimpleJavaMap. * Constructs a MemoryFileSystem instance using a SimpleJavaMap.
* Initializes the parent MapStorage with an in-memory map implementation. * Initializes the parent MapFileSystem with an in-memory map implementation.
*/ */
public MemoryStorage() { public MemoryFileSystem() {
super(new SimpleJavaMap()); super(new SimpleJavaMap());
} }

View File

@ -27,7 +27,7 @@ import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* An implementation of SimpleMap using a HashMap for internal storage. * An implementation of SimpleMap using a HashMap for internal file system.
* This class provides basic operations for storing and retrieving key-value pairs. * This class provides basic operations for storing and retrieving key-value pairs.
* It implements the SimpleMap interface. * It implements the SimpleMap interface.
* *
@ -48,7 +48,7 @@ public class SimpleJavaMap implements SimpleMap {
/** /**
* Constructs a SimpleJavaMap instance with a provided map. * Constructs a SimpleJavaMap instance with a provided map.
* *
* @param mapIn Initial map to use for storage * @param mapIn Initial map to use for file system
*/ */
public SimpleJavaMap(Map<String, String> mapIn) { public SimpleJavaMap(Map<String, String> mapIn) {
this.map = mapIn; this.map = mapIn;

View File

@ -17,23 +17,23 @@
// <https://www.gnu.org/licenses/> or write to the Free Software // <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
/////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command; package com.pixelgamelibrary.api.files.shell;
import java.util.function.Function; import java.util.function.Function;
/** /**
* The {@code BaseStorageCommand} class provides a basic implementation of the {@link StorageCommand} interface. * The {@code BaseShellCommand} class provides a basic implementation of the {@link ShellCommand} interface.
* It defines a command that can be executed within a storage command-line context using a function * It defines a command that can be executed within a file system command-line context using a function
* that processes the command and its arguments. * that processes the command and its arguments.
* *
* @author robertvokac * @author robertvokac
*/ */
public class BaseStorageCommand implements StorageCommand { public class BaseShellCommand implements ShellCommand {
/** /**
* The command-line interface this command is associated with. * The command-line interface this command is associated with.
*/ */
private StorageCommandLine storageCommandLine = null; private ShellCommandLine shellCommandLine = null;
/** /**
* The name of the command. * The name of the command.
@ -43,41 +43,41 @@ public class BaseStorageCommand implements StorageCommand {
/** /**
* The function that will be applied to execute the command with its arguments. * The function that will be applied to execute the command with its arguments.
*/ */
private final Function<String, StorageCommandResult> function; private final Function<String, ShellCommandResult> function;
/** /**
* Constructs a new {@code BaseStorageCommand} with the specified command-line interface, name, and execution function. * Constructs a new {@code BaseShellCommand} with the specified command-line interface, name, and execution function.
* *
* @param storageCommandLineIn the command-line interface associated with this command. * @param shellCommandLineIn the command-line interface associated with this command.
* @param nameIn the name of the command. * @param nameIn the name of the command.
* @param functionIn the function that defines the command's behavior when executed. * @param functionIn the function that defines the command's behavior when executed.
*/ */
public BaseStorageCommand( public BaseShellCommand(
StorageCommandLine storageCommandLineIn, String nameIn, Function<String, StorageCommandResult> functionIn ShellCommandLine shellCommandLineIn, String nameIn, Function<String, ShellCommandResult> functionIn
) { ) {
setStorageCommandLine(storageCommandLineIn); setShellCommandLine(shellCommandLineIn);
this.name = nameIn; this.name = nameIn;
this.function = functionIn; this.function = functionIn;
} }
/** /**
* Sets the {@link StorageCommandLine} for this command. * Sets the {@link ShellCommandLine} for this command.
* *
* @param storageCommandLineIn the command-line interface to set. * @param shellCommandLineIn the command-line interface to set.
*/ */
@Override @Override
public final void setStorageCommandLine(StorageCommandLine storageCommandLineIn) { public final void setShellCommandLine(ShellCommandLine shellCommandLineIn) {
storageCommandLine = storageCommandLineIn; shellCommandLine = shellCommandLineIn;
} }
/** /**
* Returns the {@link StorageCommandLine} associated with this command. * Returns the {@link ShellCommandLine} associated with this command.
* *
* @return the command-line interface. * @return the command-line interface.
*/ */
@Override @Override
public final StorageCommandLine getStorageCommandLine() { public final ShellCommandLine getShellCommandLine() {
return storageCommandLine; return shellCommandLine;
} }
/** /**
@ -97,7 +97,7 @@ public class BaseStorageCommand implements StorageCommand {
* @return the result of executing the command. * @return the result of executing the command.
*/ */
@Override @Override
public StorageCommandResult execute(String commandWithArguments) { public ShellCommandResult execute(String commandWithArguments) {
return function.apply(commandWithArguments); return function.apply(commandWithArguments);
} }

View File

@ -17,16 +17,16 @@
// <https://www.gnu.org/licenses/> or write to the Free Software // <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
/////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command; package com.pixelgamelibrary.api.files.shell;
/** /**
* The {@code StorageCommand} interface defines the contract for commands that can be executed within * The {@code ShellCommand} interface defines the contract for commands that can be executed within
* a storage command-line environment. It provides methods for getting the command's name, executing * a file system command-line environment. It provides methods for getting the command's name, executing
* the command with arguments, and managing the command-line context. * the command with arguments, and managing the command-line context.
* *
* @author robertvokac * @author robertvokac
*/ */
public interface StorageCommand { public interface ShellCommand {
/** /**
* Returns the name of the command. * Returns the name of the command.
@ -39,30 +39,30 @@ public interface StorageCommand {
* Executes the command with the specified arguments and returns the result. * Executes the command with the specified arguments and returns the result.
* *
* @param arguments the arguments to be passed to the command. * @param arguments the arguments to be passed to the command.
* @return the result of executing the command as a {@link StorageCommandResult}. * @return the result of executing the command as a {@link ShellCommandResult}.
*/ */
StorageCommandResult execute(String arguments); ShellCommandResult execute(String arguments);
/** /**
* Returns the {@link StorageCommandLine} associated with this command. * Returns the {@link ShellCommandLine} associated with this command.
* *
* @return the command-line interface associated with this command. * @return the command-line interface associated with this command.
*/ */
StorageCommandLine getStorageCommandLine(); ShellCommandLine getShellCommandLine();
/** /**
* Sets the {@link StorageCommandLine} for this command. * Sets the {@link ShellCommandLine} for this command.
* *
* @param storageCommandLine the command-line interface to set. * @param shellCommandLine the command-line interface to set.
*/ */
void setStorageCommandLine(StorageCommandLine storageCommandLine); void setShellCommandLine(ShellCommandLine shellCommandLine);
/** /**
* Creates and returns a new, empty {@link StorageCommandResult}. * Creates and returns a new, empty {@link ShellCommandResult}.
* *
* @return a new {@link StorageCommandResult} instance. * @return a new {@link ShellCommandResult} instance.
*/ */
static StorageCommandResult emptyNewResult() { static ShellCommandResult emptyNewResult() {
return new StorageCommandResult(); return new ShellCommandResult();
} }
} }

View File

@ -18,9 +18,8 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
/////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command; package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.Storage;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
@ -29,18 +28,19 @@ import java.util.Optional;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.pixelgamelibrary.api.files.FileSystem;
/** /**
* The StorageCommandLine class represents a command-line interface for interacting with storage. * The ShellCommandLine class represents a command-line interface for interacting with file system.
* It provides methods to execute various commands that manipulate or retrieve information from the storage. * It provides methods to execute various commands that manipulate or retrieve information from the file system.
* *
* @author robertvokac * @author robertvokac
*/ */
public class StorageCommandLine { public class ShellCommandLine {
private String user; // User for the command line private String user; // User for the command line
private String hostname; // Hostname for the command line private String hostname; // Hostname for the command line
private Storage storage; // Storage object for interacting with files private FileSystem fs; // File system object for interacting with files
private boolean exited = false; // Indicates if the command line session has been exited private boolean exited = false; // Indicates if the command line session has been exited
long startNanoTime = System.nanoTime(); // Start time of the session in nanoseconds long startNanoTime = System.nanoTime(); // Start time of the session in nanoseconds
@ -50,7 +50,7 @@ public class StorageCommandLine {
* @return the command line prompt string * @return the command line prompt string
*/ */
public String getCommandLineStart() { public String getCommandLineStart() {
return user + "@" + hostname + ":" + storage.printWorkingDirectory() + "$ "; return user + "@" + hostname + ":" + fs.printWorkingDirectory() + "$ ";
} }
/** /**
@ -72,17 +72,17 @@ public class StorageCommandLine {
} }
/** /**
* Constructs a StorageCommandLine instance with the specified user, hostname, and storage. * Constructs a ShellCommandLine instance with the specified user, hostname, and file system.
* Initializes commands for the command line interface. * Initializes commands for the command line interface.
* *
* @param userIn the user for the command line * @param userIn the user for the command line
* @param hostnameIn the hostname for the command line * @param hostnameIn the hostname for the command line
* @param storageIn the storage object for interacting with files * @param fsIn the file system object for interacting with files
*/ */
public StorageCommandLine(String userIn, String hostnameIn, Storage storageIn) { public ShellCommandLine(String userIn, String hostnameIn, FileSystem fsIn) {
this.user = userIn; this.user = userIn;
this.hostname = hostnameIn; this.hostname = hostnameIn;
this.storage = storageIn; this.fs = fsIn;
// Initialize commands // Initialize commands
addCommand("date", arguments -> provideOutput(result -> result.setOutput(new Date().toString()))); addCommand("date", arguments -> provideOutput(result -> result.setOutput(new Date().toString())));
@ -105,7 +105,7 @@ public class StorageCommandLine {
: "") : "")
))); )));
addCommand("ls", arguments -> provideOutput(result -> result.setOutput(storage addCommand("ls", arguments -> provideOutput(result -> result.setOutput(fsIn
.list() .list()
.stream() .stream()
.map(l -> { .map(l -> {
@ -114,12 +114,12 @@ public class StorageCommandLine {
}) })
.collect(Collectors.joining("\n"))))); .collect(Collectors.joining("\n")))));
addCommand("pwd", arguments -> provideOutput(result -> result.setOutput(storage.printWorkingDirectory()))); addCommand("pwd", arguments -> provideOutput(result -> result.setOutput(fsIn.printWorkingDirectory())));
addCommand("depth", arguments -> provideOutput(result -> result.setOutput(storage.depth()))); addCommand("depth", arguments -> provideOutput(result -> result.setOutput(fsIn.depth())));
addCommand("mkdir", arguments -> provideOutput(result addCommand("mkdir", arguments -> provideOutput(result
-> { -> {
String string = storage.createDirectories(extractArguments(arguments)); String string = fsIn.createDirectories(extractArguments(arguments));
if (string.isEmpty()) { if (string.isEmpty()) {
result.setOutput("New directory was successfully created"); result.setOutput("New directory was successfully created");
} else { } else {
@ -127,8 +127,8 @@ public class StorageCommandLine {
} }
})); }));
// Set the StorageCommandLine instance for each command // Set the ShellCommandLine instance for each command
commands.keySet().stream().map(k -> commands.get(k)).forEach(c -> c.setStorageCommandLine(this)); commands.keySet().stream().map(k -> commands.get(k)).forEach(c -> c.setShellCommandLine(this));
} }
/** /**
@ -149,8 +149,8 @@ public class StorageCommandLine {
* @param consumer the function to modify the result * @param consumer the function to modify the result
* @return the modified result * @return the modified result
*/ */
private StorageCommandResult provideOutput(Consumer<StorageCommandResult> consumer) { private ShellCommandResult provideOutput(Consumer<ShellCommandResult> consumer) {
StorageCommandResult result = StorageCommand.emptyNewResult(); ShellCommandResult result = ShellCommand.emptyNewResult();
consumer.accept(result); consumer.accept(result);
return result; return result;
} }
@ -161,12 +161,12 @@ public class StorageCommandLine {
* @param nameIn the name of the command * @param nameIn the name of the command
* @param functionIn the function to execute for the command * @param functionIn the function to execute for the command
*/ */
private void addCommand(String nameIn, Function<String, StorageCommandResult> functionIn) { private void addCommand(String nameIn, Function<String, ShellCommandResult> functionIn) {
StorageCommand storageCommand = new BaseStorageCommand(this, nameIn, functionIn); ShellCommand shellCommand = new BaseShellCommand(this, nameIn, functionIn);
commands.put(storageCommand.getName(), storageCommand); commands.put(shellCommand.getName(), shellCommand);
} }
private final Map<String, StorageCommand> commands = new HashMap<>(); private final Map<String, ShellCommand> commands = new HashMap<>();
public String getUser() { public String getUser() {
return user; return user;
@ -176,8 +176,8 @@ public class StorageCommandLine {
return hostname; return hostname;
} }
public Storage getStorage() { public FileSystem getFileSystem() {
return storage; return fs;
} }
public boolean isExited() { public boolean isExited() {
@ -190,23 +190,23 @@ public class StorageCommandLine {
* @param commandWithArguments the command and its arguments * @param commandWithArguments the command and its arguments
* @return the result of the command execution * @return the result of the command execution
*/ */
public StorageCommandResult execute(String commandWithArguments) { public ShellCommandResult execute(String commandWithArguments) {
String[] arguments = commandWithArguments.split(" "); String[] arguments = commandWithArguments.split(" ");
String command = arguments.length == 0 ? "" : arguments[0]; String command = arguments.length == 0 ? "" : arguments[0];
StorageCommand storageCommand = commands.get(command); ShellCommand shellCommand = commands.get(command);
if (storageCommand != null) { if (shellCommand != null) {
return storageCommand.execute(commandWithArguments.substring(command.length())); return shellCommand.execute(commandWithArguments.substring(command.length()));
} }
int argumentCount = arguments.length - 1; int argumentCount = arguments.length - 1;
Optional<String> argument1 = Optional.ofNullable(argumentCount >= 1 ? arguments[1] : null); Optional<String> argument1 = Optional.ofNullable(argumentCount >= 1 ? arguments[1] : null);
Optional<String> argument2 = Optional.ofNullable(argumentCount >= 2 ? arguments[2] : null); Optional<String> argument2 = Optional.ofNullable(argumentCount >= 2 ? arguments[2] : null);
StorageCommandResult finalResult = new StorageCommandResult(); ShellCommandResult finalResult = new ShellCommandResult();
switch (command) { switch (command) {
case "touch": case "touch":
String r = storage.touch(argument1.get()); String r = fs.touch(argument1.get());
if (r.isEmpty()) { if (r.isEmpty()) {
finalResult.setOutput("New file was successfully created"); finalResult.setOutput("New file was successfully created");
} else { } else {
@ -214,7 +214,7 @@ public class StorageCommandLine {
} }
break; break;
case "readtext": case "readtext":
String rr = storage.readString(argument1.get()); String rr = fs.readString(argument1.get());
if (rr != null) { if (rr != null) {
finalResult.setOutput("Text file was successfully loaded" + "\n\n" + rr); finalResult.setOutput("Text file was successfully loaded" + "\n\n" + rr);
} else { } else {
@ -222,7 +222,7 @@ public class StorageCommandLine {
} }
break; break;
case "savetext": case "savetext":
String result = storage.writeString(argument1.get(), argument2.get()); String result = fs.writeString(argument1.get(), argument2.get());
if (result.isEmpty()) { if (result.isEmpty()) {
finalResult.setOutput("Text file was successfully saved"); finalResult.setOutput("Text file was successfully saved");
} else { } else {
@ -230,7 +230,7 @@ public class StorageCommandLine {
} }
break; break;
case "cd": case "cd":
String rrr = argument1.isEmpty() ? storage.changeDirectory() : storage.changeDirectory(argument1.get()); String rrr = argument1.isEmpty() ? fs.changeDirectory() : fs.changeDirectory(argument1.get());
if (rrr.isEmpty()) { if (rrr.isEmpty()) {
finalResult.setOutput("Changing working directory was successfully created"); finalResult.setOutput("Changing working directory was successfully created");
} else { } else {
@ -238,7 +238,7 @@ public class StorageCommandLine {
} }
break; break;
case "debug": case "debug":
finalResult.setOutput(storage.debug()); finalResult.setOutput(fs.debug());
break; break;
case "exit": case "exit":
exited = true; exited = true;

View File

@ -18,34 +18,34 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
/////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command; package com.pixelgamelibrary.api.files.shell;
/** /**
* The StorageCommandLineScanner class provides a command-line interface for interacting with * The ShellCommandLineScanner class provides a command-line interface for interacting with
* the StorageCommandLine instance. It reads user input and executes commands in a loop until * the ShellCommandLine instance. It reads user input and executes commands in a loop until
* the exit command is issued. * the exit command is issued.
* *
* @author robertvokac * @author robertvokac
*/ */
public class StorageCommandLineScanner { public class ShellCommandLineScanner {
/** /**
* Constructs a StorageCommandLineScanner instance that continuously reads input from the * Constructs a ShellCommandLineScanner instance that continuously reads input from the
* user and executes commands until the exit command is issued. * user and executes commands until the exit command is issued.
* *
* @param storageCommandLine the StorageCommandLine instance to interact with * @param shellCommandLine the ShellCommandLine instance to interact with
* @param scanner the Scanner object for reading user input * @param scanner the Scanner object for reading user input
*/ */
public StorageCommandLineScanner(StorageCommandLine storageCommandLine, CommandLineScanner scanner) { public ShellCommandLineScanner(ShellCommandLine shellCommandLine, ShellScanner scanner) {
while (true) { while (true) {
// Print the command line prompt // Print the command line prompt
System.out.print(storageCommandLine.getCommandLineStart()); System.out.print(shellCommandLine.getCommandLineStart());
// Read user input // Read user input
String argument = scanner.nextLine(); String argument = scanner.nextLine();
// Execute the command and get the result // Execute the command and get the result
StorageCommandResult result = storageCommandLine.execute(argument); ShellCommandResult result = shellCommandLine.execute(argument);
// Print error or output based on the result // Print error or output based on the result
if (result.isError()) { if (result.isError()) {
printError(result.getOutput()); printError(result.getOutput());
@ -53,7 +53,7 @@ public class StorageCommandLineScanner {
print(result.getOutput()); print(result.getOutput());
} }
// Exit if the command line session is marked as exited // Exit if the command line session is marked as exited
if (storageCommandLine.isExited()) { if (shellCommandLine.isExited()) {
break; break;
} }
} }

View File

@ -18,20 +18,20 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
/////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command; package com.pixelgamelibrary.api.files.shell;
/** /**
* The StorageCommandResult class encapsulates the result of executing a storage command. * The ShellCommandResult class encapsulates the result of executing a file system command.
* It holds the output of the command and a flag indicating whether an error occurred. * It holds the output of the command and a flag indicating whether an error occurred.
* *
* @author robertvokac * @author robertvokac
*/ */
public class StorageCommandResult { public class ShellCommandResult {
/** /**
* Default constructor that initializes an empty result. * Default constructor that initializes an empty result.
*/ */
public StorageCommandResult() { public ShellCommandResult() {
this(""); this("");
} }
@ -40,7 +40,7 @@ public class StorageCommandResult {
* *
* @param output the output of the command * @param output the output of the command
*/ */
public StorageCommandResult(String output) { public ShellCommandResult(String output) {
this(output, false); this(output, false);
} }
@ -50,7 +50,7 @@ public class StorageCommandResult {
* @param output the output of the command * @param output the output of the command
* @param error true if an error occurred, false otherwise * @param error true if an error occurred, false otherwise
*/ */
public StorageCommandResult(String output, boolean error) { public ShellCommandResult(String output, boolean error) {
this.output = output; this.output = output;
this.error = error; this.error = error;
} }

View File

@ -17,7 +17,7 @@
// <https://www.gnu.org/licenses/> or write to the Free Software // <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
/////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command; package com.pixelgamelibrary.api.files.shell;
/** /**
* The {@code CommandLineScanner} interface defines a contract for scanning input from a command line. * The {@code CommandLineScanner} interface defines a contract for scanning input from a command line.
@ -25,7 +25,7 @@ package com.pixelgamelibrary.api.files.command;
* *
* @author robertvokac * @author robertvokac
*/ */
public interface CommandLineScanner { public interface ShellScanner {
/** /**
* Reads the next line of input from the command line. * Reads the next line of input from the command line.

View File

@ -19,7 +19,7 @@
/////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.graphics; package com.pixelgamelibrary.api.graphics;
import com.pixelgamelibrary.api.files.FileHandle; import com.pixelgamelibrary.api.files.File;
/** /**
* *
@ -35,24 +35,24 @@ public interface BitmapFontFactory {
return create(FLIP_DEFAULT); return create(FLIP_DEFAULT);
} }
BitmapFont create(FileHandle fontFile, TextureRegion region, boolean flip); BitmapFont create(File fontFile, TextureRegion region, boolean flip);
default BitmapFont create(FileHandle fontFile, TextureRegion region) { default BitmapFont create(File fontFile, TextureRegion region) {
return create(fontFile, region, FLIP_DEFAULT); return create(fontFile, region, FLIP_DEFAULT);
} }
BitmapFont create(FileHandle fontFile, boolean flip); BitmapFont create(File fontFile, boolean flip);
default BitmapFont create(FileHandle fontFile) { default BitmapFont create(File fontFile) {
return create(fontFile, FLIP_DEFAULT); return create(fontFile, FLIP_DEFAULT);
} }
// Pixel.files().assets("com/badlogic/gdx/utils/lsans-15.fnt"), Pixel.files().assets("com/badlogic/gdx/utils/lsans-15.png"), // Pixel.files().assets("com/badlogic/gdx/utils/lsans-15.fnt"), Pixel.files().assets("com/badlogic/gdx/utils/lsans-15.png"),
// false, true // false, true
// ); // );
BitmapFont create(FileHandle fontFile, FileHandle imageFile, boolean flip); BitmapFont create(File fontFile, File imageFile, boolean flip);
default BitmapFont create(FileHandle fontFile, FileHandle imageFile) { default BitmapFont create(File fontFile, File imageFile) {
return create(fontFile, imageFile, FLIP_DEFAULT); return create(fontFile, imageFile, FLIP_DEFAULT);
} }

View File

@ -20,7 +20,7 @@
package com.pixelgamelibrary.api.graphics; package com.pixelgamelibrary.api.graphics;
import com.pixelgamelibrary.api.files.FileHandle; import com.pixelgamelibrary.api.files.File;
/** /**
* *
@ -28,6 +28,6 @@ import com.pixelgamelibrary.api.files.FileHandle;
*/ */
public interface PixMapFactory { public interface PixMapFactory {
Pixmap create(int width, int height); Pixmap create(int width, int height);
Pixmap create(FileHandle fileHandle); Pixmap create(File fileHandle);
} }

View File

@ -20,7 +20,7 @@
package com.pixelgamelibrary.api.graphics; package com.pixelgamelibrary.api.graphics;
import com.pixelgamelibrary.api.files.FileHandle; import com.pixelgamelibrary.api.files.File;
/** /**
* *
@ -28,7 +28,7 @@ import com.pixelgamelibrary.api.files.FileHandle;
*/ */
public interface TextureFactory { public interface TextureFactory {
Texture create(String assetPath); Texture create(String assetPath);
Texture create(FileHandle fileHandle); Texture create(File fileHandle);
Texture create(Pixmap pixmap); Texture create(Pixmap pixmap);
Texture create(int width, int height); Texture create(int width, int height);
} }

View File

@ -21,7 +21,7 @@ package com.pixelgamelibrary.api.interfaces;
import com.pixelgamelibrary.api.audio.Music; import com.pixelgamelibrary.api.audio.Music;
import com.pixelgamelibrary.api.audio.Sound; import com.pixelgamelibrary.api.audio.Sound;
import com.pixelgamelibrary.api.files.FileHandle; import com.pixelgamelibrary.api.files.File;
/** /**
* *
@ -29,6 +29,6 @@ import com.pixelgamelibrary.api.files.FileHandle;
*/ */
public interface Audio { public interface Audio {
//Add MIDI support - todo //Add MIDI support - todo
Sound newSound(FileHandle fileHandle); Sound newSound(File fileHandle);
Music newMusic(FileHandle fileHandle); Music newMusic(File fileHandle);
} }

View File

@ -19,12 +19,18 @@
/////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.interfaces; package com.pixelgamelibrary.api.interfaces;
import com.pixelgamelibrary.api.files.FileHandle; import com.pixelgamelibrary.api.files.FileException;
import com.pixelgamelibrary.api.files.Storage; import com.pixelgamelibrary.api.files.FileSystemType;
import com.pixelgamelibrary.api.files.StorageException; import static com.pixelgamelibrary.api.files.FileSystemType.ASSETS;
import com.pixelgamelibrary.api.files.StorageType; import static com.pixelgamelibrary.api.files.FileSystemType.EXTERNAL;
import static com.pixelgamelibrary.api.files.StorageType.ASSETS; import com.pixelgamelibrary.api.files.FileSystem;
import static com.pixelgamelibrary.api.files.StorageType.EXTERNAL; import com.pixelgamelibrary.api.files.File;
import static com.pixelgamelibrary.api.files.FileSystemType.ABSOLUTE;
import static com.pixelgamelibrary.api.files.FileSystemType.ASSETS;
import static com.pixelgamelibrary.api.files.FileSystemType.EXTERNAL;
import static com.pixelgamelibrary.api.files.FileSystemType.LOCAL;
import static com.pixelgamelibrary.api.files.FileSystemType.RELATIVE;
import static com.pixelgamelibrary.api.files.FileSystemType.TMP;
/** /**
* *
@ -32,57 +38,76 @@ import static com.pixelgamelibrary.api.files.StorageType.EXTERNAL;
*/ */
public interface Files { public interface Files {
Storage assetsStorage(); FileSystem assetsFileSystem();
Storage localStorage(); FileSystem localFileSystem();
Storage externalStorage(); FileSystem externalFileSystem();
Storage relativeStorage(); FileSystem relativeFileSystem();
Storage absoluteStorage(); FileSystem absoluteFileSystem();
Storage tmpStorage(); FileSystem tmpFileSystem();
default FileHandle assets(String path) { default File assets(String path) {
return assetsStorage().file(path); return assetsFileSystem().file(path);
} }
default FileHandle local(String path) { default File local(String path) {
return localStorage().file(path); return localFileSystem().file(path);
} }
default FileHandle external(String path) { default File external(String path) {
return externalStorage().file(path); return externalFileSystem().file(path);
} }
default FileHandle relative(String path) { default File relative(String path) {
return relativeStorage().file(path); return relativeFileSystem().file(path);
} }
default FileHandle absolute(String path) { default File absolute(String path) {
return absoluteStorage().file(path); return absoluteFileSystem().file(path);
} }
default FileHandle tmp(String path) { default File tmp(String path) {
return tmpStorage().file(path); return tmpFileSystem().file(path);
} }
default FileSystem fileSystem(FileSystemType type) {
default FileHandle file(java.lang.String path, StorageType type) {
switch (type) { switch (type) {
case ASSETS: case ASSETS:
return assetsStorage().file(path); return assetsFileSystem();
case LOCAL: case LOCAL:
return localStorage().file(path); return localFileSystem();
case EXTERNAL: case EXTERNAL:
return externalStorage().file(path); return externalFileSystem();
case RELATIVE: case RELATIVE:
return relativeStorage().file(path); return relativeFileSystem();
case ABSOLUTE: case ABSOLUTE:
return absoluteStorage().file(path); return absoluteFileSystem();
case TMP: case TMP:
return tmpStorage().file(path); return tmpFileSystem();
default: default:
throw new StorageException("Unsupported StorageType: " + type); throw new FileException("Unsupported FileSystemType: " + type);
} }
} }
default File file(java.lang.String path, FileSystemType type) {
//return fileSystem(type).file(path);
switch (type) {
case ASSETS:
return assetsFileSystem().file(path);
case LOCAL:
return localFileSystem().file(path);
case EXTERNAL:
return externalFileSystem().file(path);
case RELATIVE:
return relativeFileSystem().file(path);
case ABSOLUTE:
return absoluteFileSystem().file(path);
case TMP:
return tmpFileSystem().file(path);
default:
throw new FileException("Unsupported FileSystemType: " + type);
}
}
boolean isExternalStorageAvailable(); boolean isExternalStorageAvailable();

View File

@ -30,7 +30,7 @@ import com.pixelgamelibrary.api.graphics.SpriteBatchFactory;
import com.pixelgamelibrary.api.graphics.Texture; import com.pixelgamelibrary.api.graphics.Texture;
import com.pixelgamelibrary.api.graphics.TextureFactory; import com.pixelgamelibrary.api.graphics.TextureFactory;
import com.pixelgamelibrary.api.graphics.TextureRegion; import com.pixelgamelibrary.api.graphics.TextureRegion;
import com.pixelgamelibrary.api.files.FileHandle; import com.pixelgamelibrary.api.files.File;
/** /**
* *
@ -69,7 +69,7 @@ public interface Graphics {
return getTextureFactory().create(assetPath); return getTextureFactory().create(assetPath);
} }
default Texture newTexture(FileHandle fileHandle) { default Texture newTexture(File fileHandle) {
return getTextureFactory().create(fileHandle); return getTextureFactory().create(fileHandle);
} }
@ -97,23 +97,23 @@ public interface Graphics {
return newBitmapFontFactory().create(flip); return newBitmapFontFactory().create(flip);
} }
default BitmapFont newBitmapFont(FileHandle fontFile, TextureRegion region) { default BitmapFont newBitmapFont(File fontFile, TextureRegion region) {
return newBitmapFontFactory().create(fontFile, region); return newBitmapFontFactory().create(fontFile, region);
} }
default BitmapFont newBitmapFont(FileHandle fontFile, TextureRegion region, boolean flip) { default BitmapFont newBitmapFont(File fontFile, TextureRegion region, boolean flip) {
return newBitmapFontFactory().create(fontFile, region, flip); return newBitmapFontFactory().create(fontFile, region, flip);
} }
default BitmapFont newBitmapFont(FileHandle fontFile) { default BitmapFont newBitmapFont(File fontFile) {
return newBitmapFontFactory().create(fontFile); return newBitmapFontFactory().create(fontFile);
} }
default BitmapFont newBitmapFont(FileHandle fontFile, boolean flip) { default BitmapFont newBitmapFont(File fontFile, boolean flip) {
return newBitmapFontFactory().create(fontFile, flip); return newBitmapFontFactory().create(fontFile, flip);
} }
default BitmapFont newBitmapFont(FileHandle fontFile, FileHandle imageFile, boolean flip) { default BitmapFont newBitmapFont(File fontFile, File imageFile, boolean flip) {
return newBitmapFontFactory().create(fontFile, imageFile, flip); return newBitmapFontFactory().create(fontFile, imageFile, flip);
} }

View File

@ -20,7 +20,7 @@
package com.pixelgamelibrary.api.utils; package com.pixelgamelibrary.api.utils;
import com.pixelgamelibrary.api.Pixel; import com.pixelgamelibrary.api.Pixel;
import com.pixelgamelibrary.api.files.StorageException; import com.pixelgamelibrary.api.files.FileException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
@ -106,7 +106,7 @@ public class AssetsTxt {
public List<String> list(String pathToDirectory, boolean directoryType, boolean fileType) { public List<String> list(String pathToDirectory, boolean directoryType, boolean fileType) {
// System.out.println("Calling: AssetsTxt.list( " + pathToDirectory + " ...)"); // System.out.println("Calling: AssetsTxt.list( " + pathToDirectory + " ...)");
if (!directoryType && !fileType) { if (!directoryType && !fileType) {
throw new StorageException("Invalid arguments, both arguments are false: directoryType, fileType"); throw new FileException("Invalid arguments, both arguments are false: directoryType, fileType");
} }
if (pathToDirectory.equals(".")) { if (pathToDirectory.equals(".")) {
@ -126,7 +126,7 @@ public class AssetsTxt {
return result; return result;
} }
if (!directoriesSet.contains(pathToDirectory)) { if (!directoriesSet.contains(pathToDirectory)) {
throw new StorageException("There is no such directory in assets: " + pathToDirectory); throw new FileException("There is no such directory in assets: " + pathToDirectory);
} }
var directoryArray = pathToDirectory.split("/"); var directoryArray = pathToDirectory.split("/");

View File

@ -1,10 +1,8 @@
package com.pixelgamelibrary.api.files; package com.pixelgamelibrary.api.files;
import com.pixelgamelibrary.api.files.Storage; import com.pixelgamelibrary.api.files.FileImpl;
import com.pixelgamelibrary.api.files.FileHandleImpl;
import com.pixelgamelibrary.api.files.RegularFileType; import com.pixelgamelibrary.api.files.RegularFileType;
import com.pixelgamelibrary.api.files.FileType; import com.pixelgamelibrary.api.files.FileType;
import com.pixelgamelibrary.api.files.FileHandle;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
@ -13,22 +11,24 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import com.pixelgamelibrary.api.files.FileSystem;
import com.pixelgamelibrary.api.files.File;
public class FileHandleImplTest { public class FileImplTest {
private Storage mockStorage; private FileSystem mockFileSystem;
private FileHandleImpl fileHandle; private FileImpl fileHandle;
@BeforeEach @BeforeEach
public void setUp() { public void setUp() {
mockStorage = mock(Storage.class); mockFileSystem = mock(FileSystem.class);
fileHandle = new FileHandleImpl(mockStorage, "/example/path/file.txt"); fileHandle = new FileImpl(mockFileSystem, "/example/path/file.txt");
} }
@Test @Test
public void testType() { public void testType() {
// Arrange // Arrange
when(mockStorage.type("/example/path/file.txt")).thenReturn(FileType.FILE); when(mockFileSystem.type("/example/path/file.txt")).thenReturn(FileType.FILE);
// Act // Act
FileType result = fileHandle.type(); FileType result = fileHandle.type();
@ -60,10 +60,10 @@ public class FileHandleImplTest {
@Test @Test
public void testList() { public void testList() {
// Arrange // Arrange
when(mockStorage.list("/example/path/file.txt")).thenReturn(Arrays.asList("child1", "child2")); when(mockFileSystem.list("/example/path/file.txt")).thenReturn(Arrays.asList("child1", "child2"));
// Act // Act
List<FileHandle> files = fileHandle.list(); List<File> files = fileHandle.list();
// Assert // Assert
assertEquals(2, files.size()); assertEquals(2, files.size());
@ -74,7 +74,7 @@ public class FileHandleImplTest {
@Test @Test
public void testChild() { public void testChild() {
// Act // Act
FileHandle child = fileHandle.child("child.txt"); File child = fileHandle.child("child.txt");
// Assert // Assert
assertEquals("/example/path/file.txt/child.txt", child.path()); assertEquals("/example/path/file.txt/child.txt", child.path());
@ -83,7 +83,7 @@ public class FileHandleImplTest {
@Test @Test
public void testSibling() { public void testSibling() {
// Act // Act
FileHandle sibling = fileHandle.sibling("sibling.txt"); File sibling = fileHandle.sibling("sibling.txt");
// Assert // Assert
assertEquals("/example/path/sibling.txt", sibling.path()); assertEquals("/example/path/sibling.txt", sibling.path());
@ -92,7 +92,7 @@ public class FileHandleImplTest {
@Test @Test
public void testParent() { public void testParent() {
// Act // Act
FileHandle parent = fileHandle.parent(); File parent = fileHandle.parent();
// Assert // Assert
assertEquals("/example/path", parent.path()); assertEquals("/example/path", parent.path());
@ -101,7 +101,7 @@ public class FileHandleImplTest {
@Test @Test
public void testMkdir() { public void testMkdir() {
// Arrange // Arrange
when(mockStorage.createDirectory("/example/path/file.txt")).thenReturn(""); when(mockFileSystem.createDirectory("/example/path/file.txt")).thenReturn("");
// Act // Act
boolean result = fileHandle.mkdir(); boolean result = fileHandle.mkdir();
@ -113,7 +113,7 @@ public class FileHandleImplTest {
@Test @Test
public void testExists() { public void testExists() {
// Arrange // Arrange
when(mockStorage.exists("/example/path/file.txt")).thenReturn(true); when(mockFileSystem.exists("/example/path/file.txt")).thenReturn(true);
// Act // Act
boolean result = fileHandle.exists(); boolean result = fileHandle.exists();
@ -125,7 +125,7 @@ public class FileHandleImplTest {
@Test @Test
public void testDelete() { public void testDelete() {
// Arrange // Arrange
when(mockStorage.remove("/example/path/file.txt")).thenReturn(true); when(mockFileSystem.remove("/example/path/file.txt")).thenReturn(true);
// Act // Act
boolean result = fileHandle.delete(); boolean result = fileHandle.delete();
@ -137,8 +137,8 @@ public class FileHandleImplTest {
@Test @Test
public void testCopyTo() { public void testCopyTo() {
// Arrange // Arrange
FileHandleImpl destination = new FileHandleImpl(mockStorage, "/destination/path"); FileImpl destination = new FileImpl(mockFileSystem, "/destination/path");
when(mockStorage.copy("/example/path/file.txt", "/destination/path")).thenReturn(""); when(mockFileSystem.copy("/example/path/file.txt", "/destination/path")).thenReturn("");
// Act // Act
boolean result = fileHandle.copyTo(destination); boolean result = fileHandle.copyTo(destination);
@ -150,8 +150,8 @@ public class FileHandleImplTest {
@Test @Test
public void testMoveTo() { public void testMoveTo() {
// Arrange // Arrange
FileHandleImpl destination = new FileHandleImpl(mockStorage, "/destination/path"); FileImpl destination = new FileImpl(mockFileSystem, "/destination/path");
when(mockStorage.move("/example/path/file.txt", "/destination/path")).thenReturn(""); when(mockFileSystem.move("/example/path/file.txt", "/destination/path")).thenReturn("");
// Act // Act
boolean result = fileHandle.moveTo(destination); boolean result = fileHandle.moveTo(destination);
@ -163,8 +163,8 @@ public class FileHandleImplTest {
@Test @Test
public void testLength() { public void testLength() {
// Arrange // Arrange
when(mockStorage.getRegularFileType("/example/path/file.txt")).thenReturn(RegularFileType.TEXT); when(mockFileSystem.getRegularFileType("/example/path/file.txt")).thenReturn(RegularFileType.TEXT);
when(mockStorage.readString("/example/path/file.txt")).thenReturn("Hello, World!"); when(mockFileSystem.readString("/example/path/file.txt")).thenReturn("Hello, World!");
// Act // Act
long length = fileHandle.length(); long length = fileHandle.length();

View File

@ -1,58 +0,0 @@
package com.pixelgamelibrary.api.files.command;
import com.pixelgamelibrary.api.files.command.StorageCommandResult;
import com.pixelgamelibrary.api.files.command.StorageCommandLine;
import com.pixelgamelibrary.api.files.command.BaseStorageCommand;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class BaseStorageCommandTest {
private StorageCommandLine mockCommandLine;
private StorageCommandResult mockCommandResult;
private Function<String, StorageCommandResult> mockFunction;
private BaseStorageCommand command;
@BeforeEach
void setUp() {
mockCommandLine = mock(StorageCommandLine.class);
mockCommandResult = mock(StorageCommandResult.class);
mockFunction = mock(Function.class);
// When the function is applied, return the mock result
when(mockFunction.apply(anyString())).thenReturn(mockCommandResult);
// Create an instance of BaseStorageCommand with mocks
command = new BaseStorageCommand(mockCommandLine, "testCommand", mockFunction);
}
@Test
void testGetName() {
assertEquals("testCommand", command.getName());
}
@Test
void testGetStorageCommandLine() {
assertEquals(mockCommandLine, command.getStorageCommandLine());
}
@Test
void testExecute() {
StorageCommandResult result = command.execute("testCommand arg1");
assertEquals(mockCommandResult, result);
verify(mockFunction).apply("testCommand arg1");
}
@Test
void testSetStorageCommandLine() {
StorageCommandLine newCommandLine = mock(StorageCommandLine.class);
command.setStorageCommandLine(newCommandLine);
assertEquals(newCommandLine, command.getStorageCommandLine());
}
}

View File

@ -1,64 +0,0 @@
package com.pixelgamelibrary.api.files.command;
import com.pixelgamelibrary.api.files.command.StorageCommandResult;
import com.pixelgamelibrary.api.files.command.StorageCommandLineScanner;
import com.pixelgamelibrary.api.files.command.StorageCommandLine;
import com.pixelgamelibrary.api.files.command.CommandLineScanner;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
class StorageCommandLineScannerTest {
@Mock
private StorageCommandLine mockStorageCommandLine; // Mocking StorageCommandLine
@Mock
private CommandLineScanner mockCommandLineScanner; // Mocking CommandLineScanner
private StorageCommandLineScanner storageCommandLineScanner; // Manually creating the instance
@BeforeEach
void setUp() {
// Initialize mock objects before each test
MockitoAnnotations.openMocks(this);
}
@Test
void testExecuteSimpleCommand() {
// Arrange
when(mockStorageCommandLine.getCommandLineStart()).thenReturn(">");
when(mockCommandLineScanner.nextLine()).thenReturn("someCommand");
StorageCommandResult mockResult = new StorageCommandResult("Command Executed");
when(mockStorageCommandLine.execute("someCommand")).thenReturn(mockResult);
when(mockStorageCommandLine.isExited()).thenReturn(true);
// Manually create the instance of StorageCommandLineScanner with mocks
storageCommandLineScanner = new StorageCommandLineScanner(mockStorageCommandLine, mockCommandLineScanner);
// Assert: Verify that the expected methods were called
verify(mockStorageCommandLine).getCommandLineStart();
verify(mockStorageCommandLine).execute("someCommand");
}
@Test
void testErrorOutput() {
// Arrange
when(mockStorageCommandLine.getCommandLineStart()).thenReturn(">");
when(mockCommandLineScanner.nextLine()).thenReturn("invalidCommand");
StorageCommandResult errorResult = new StorageCommandResult("Error occurred", true);
when(mockStorageCommandLine.execute("invalidCommand")).thenReturn(errorResult);
when(mockStorageCommandLine.isExited()).thenReturn(true);
// Manually create the instance of StorageCommandLineScanner with mocks
storageCommandLineScanner = new StorageCommandLineScanner(mockStorageCommandLine, mockCommandLineScanner);
// Assert: Verify the error output
verify(mockStorageCommandLine).execute("invalidCommand");
assertTrue(errorResult.isError(), "The result should indicate an error");
}
}

View File

@ -1,65 +0,0 @@
package com.pixelgamelibrary.api.files.command;
import com.pixelgamelibrary.api.files.command.StorageCommandResult;
import com.pixelgamelibrary.api.files.command.StorageCommandLine;
import com.pixelgamelibrary.api.files.command.BaseStorageCommand;
import com.pixelgamelibrary.api.files.command.StorageCommand;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class StorageCommandTest {
private StorageCommand mockCommand;
private StorageCommandLine mockCommandLine;
private StorageCommandResult mockCommandResult;
private Function<String, StorageCommandResult> mockFunction;
@BeforeEach
void setUp() {
mockCommandLine = mock(StorageCommandLine.class);
mockCommandResult = mock(StorageCommandResult.class);
mockFunction = mock(Function.class);
// Mock the behavior of execute method
when(mockFunction.apply(anyString())).thenReturn(mockCommandResult);
// Create an instance of BaseStorageCommand with mocks
mockCommand = new BaseStorageCommand(mockCommandLine, "testCommand", mockFunction);
}
@Test
void testGetName() {
assertEquals("testCommand", mockCommand.getName());
}
@Test
void testGetStorageCommandLine() {
assertEquals(mockCommandLine, mockCommand.getStorageCommandLine());
}
@Test
void testSetStorageCommandLine() {
StorageCommandLine newCommandLine = mock(StorageCommandLine.class);
mockCommand.setStorageCommandLine(newCommandLine);
assertEquals(newCommandLine, mockCommand.getStorageCommandLine());
}
@Test
void testExecute() {
StorageCommandResult result = mockCommand.execute("testCommand arg1");
assertEquals(mockCommandResult, result);
verify(mockFunction).apply("testCommand arg1");
}
@Test
void testEmptyNewResult() {
StorageCommandResult result = StorageCommand.emptyNewResult();
assertNotNull(result);
assertTrue(result instanceof StorageCommandResult);
}
}

View File

@ -1,6 +1,6 @@
package com.pixelgamelibrary.api.files.map; package com.pixelgamelibrary.api.files.map;
import com.pixelgamelibrary.api.files.map.MapStorage; import com.pixelgamelibrary.api.files.map.MapFileSystem;
import com.pixelgamelibrary.api.files.map.SimpleMap; import com.pixelgamelibrary.api.files.map.SimpleMap;
import com.pixelgamelibrary.api.Pixel; import com.pixelgamelibrary.api.Pixel;
import com.pixelgamelibrary.api.Platform; import com.pixelgamelibrary.api.Platform;
@ -27,11 +27,11 @@ import com.pixelgamelibrary.api.app.ClipBoard;
import com.pixelgamelibrary.api.app.LogLevel; import com.pixelgamelibrary.api.app.LogLevel;
import com.pixelgamelibrary.api.app.Preferences; import com.pixelgamelibrary.api.app.Preferences;
// Tests for MapStorage class // Tests for MapFileSystem class
public class MapStorageTest { public class MapFileSystemTest {
private SimpleMap mockMap; private SimpleMap mockMap;
private MapStorage mapStorage; private MapFileSystem fs;
@org.junit.jupiter.api.BeforeAll public static void setupStart() { @org.junit.jupiter.api.BeforeAll public static void setupStart() {
@ -201,7 +201,7 @@ public class MapStorageTest {
@BeforeEach @BeforeEach
public void setup() { public void setup() {
mockMap = Mockito.mock(SimpleMap.class); // Mocking the SimpleMap class mockMap = Mockito.mock(SimpleMap.class); // Mocking the SimpleMap class
mapStorage = new MapStorage(mockMap); // Initialize MapStorage with the mocked map fs = new MapFileSystem(mockMap); // Initialize MapFileSystem with the mocked map
} }
@Test @Test
@ -209,7 +209,7 @@ public class MapStorageTest {
when(mockMap.contains("/")).thenReturn(true); // Simulate no directory exists when(mockMap.contains("/")).thenReturn(true); // Simulate no directory exists
when(mockMap.contains("/newDir")).thenReturn(false); // Simulate no directory exists when(mockMap.contains("/newDir")).thenReturn(false); // Simulate no directory exists
String result = mapStorage.createDirectory("/newDir"); String result = fs.createDirectory("/newDir");
assertEquals("", result); // Success should return an empty string assertEquals("", result); // Success should return an empty string
verify(mockMap).putString("/newDir", "DIRECTORY::::::::"); verify(mockMap).putString("/newDir", "DIRECTORY::::::::");
@ -220,7 +220,7 @@ public class MapStorageTest {
when(mockMap.contains("/")).thenReturn(true); // Root irectory already exists when(mockMap.contains("/")).thenReturn(true); // Root irectory already exists
when(mockMap.contains("/newDir")).thenReturn(true); // Directory already exists when(mockMap.contains("/newDir")).thenReturn(true); // Directory already exists
String result = mapStorage.createDirectory("/newDir"); String result = fs.createDirectory("/newDir");
assertEquals("Cannot create new directory, because path already exists: /newDir", result); assertEquals("Cannot create new directory, because path already exists: /newDir", result);
} }
@ -232,7 +232,7 @@ public class MapStorageTest {
when(mockMap.getString("/")).thenReturn("DIRECTORY::::::::"); when(mockMap.getString("/")).thenReturn("DIRECTORY::::::::");
when(mockMap.getString("/newDir")).thenReturn("DIRECTORY::::::::"); when(mockMap.getString("/newDir")).thenReturn("DIRECTORY::::::::");
String result = mapStorage.changeDirectory("/newDir"); String result = fs.changeDirectory("/newDir");
assertEquals("", result); // Success should return an empty string assertEquals("", result); // Success should return an empty string
} }
@ -241,7 +241,7 @@ public class MapStorageTest {
public void testCdPathDoesNotExist() { public void testCdPathDoesNotExist() {
when(mockMap.contains("/nonExistent")).thenReturn(false); when(mockMap.contains("/nonExistent")).thenReturn(false);
String result = mapStorage.changeDirectory("/nonExistent"); String result = fs.changeDirectory("/nonExistent");
assertEquals("Path does not exist: /nonExistent", result); assertEquals("Path does not exist: /nonExistent", result);
} }
@ -251,7 +251,7 @@ public class MapStorageTest {
when(mockMap.contains("/")).thenReturn(true); // Root exists when(mockMap.contains("/")).thenReturn(true); // Root exists
when(mockMap.getString("/")).thenReturn("DIRECTORY::::::::"); when(mockMap.getString("/")).thenReturn("DIRECTORY::::::::");
String result = mapStorage.touch("/newFile.txt", "Test content"); String result = fs.touch("/newFile.txt", "Test content");
assertEquals("", result); // Success should return an empty string assertEquals("", result); // Success should return an empty string
verify(mockMap).putString("/newFile.txt", "FILE::::::::Test content"); verify(mockMap).putString("/newFile.txt", "FILE::::::::Test content");
@ -262,7 +262,7 @@ public class MapStorageTest {
when(mockMap.contains("/")).thenReturn(true); // File already exists when(mockMap.contains("/")).thenReturn(true); // File already exists
when(mockMap.contains("/newFile.txt")).thenReturn(true); // File already exists when(mockMap.contains("/newFile.txt")).thenReturn(true); // File already exists
String result = mapStorage.touch("/newFile.txt", "Test content"); String result = fs.touch("/newFile.txt", "Test content");
assertEquals("Cannot create new file, because path already exists: /newFile.txt", result); assertEquals("Cannot create new file, because path already exists: /newFile.txt", result);
} }
@ -272,7 +272,7 @@ public class MapStorageTest {
when(mockMap.contains("/file.txt")).thenReturn(true); when(mockMap.contains("/file.txt")).thenReturn(true);
when(mockMap.getString("/file.txt")).thenReturn("FILE::::::::Hello World"); when(mockMap.getString("/file.txt")).thenReturn("FILE::::::::Hello World");
String content = mapStorage.readString("/file.txt"); String content = fs.readString("/file.txt");
assertEquals("Hello World", content); assertEquals("Hello World", content);
} }
@ -281,7 +281,7 @@ public class MapStorageTest {
public void testReadTextFileDoesNotExist() { public void testReadTextFileDoesNotExist() {
when(mockMap.contains("/file.txt")).thenReturn(false); when(mockMap.contains("/file.txt")).thenReturn(false);
String content = mapStorage.readString("/file.txt"); String content = fs.readString("/file.txt");
assertNull(content); assertNull(content);
} }
@ -291,7 +291,7 @@ public class MapStorageTest {
when(mockMap.contains("/file.txt")).thenReturn(true); when(mockMap.contains("/file.txt")).thenReturn(true);
when(mockMap.getString("/file.txt")).thenReturn("FILE::::::::Hello World"); when(mockMap.getString("/file.txt")).thenReturn("FILE::::::::Hello World");
boolean result = mapStorage.remove("/file.txt"); boolean result = fs.remove("/file.txt");
assertTrue(result); // File successfully removed assertTrue(result); // File successfully removed
verify(mockMap).remove("/file.txt"); verify(mockMap).remove("/file.txt");
@ -301,23 +301,23 @@ public class MapStorageTest {
public void testRmFileDoesNotExist() { public void testRmFileDoesNotExist() {
when(mockMap.contains("/file.txt")).thenReturn(false); when(mockMap.contains("/file.txt")).thenReturn(false);
boolean result = mapStorage.remove("/file.txt"); boolean result = fs.remove("/file.txt");
assertFalse(result); // File does not exist, so removal fails assertFalse(result); // File does not exist, so removal fails
} }
@Test @Test
public void testDepth() { public void testDepth() {
assertEquals(0, mapStorage.depth("/")); assertEquals(0, fs.depth("/"));
assertEquals(1, mapStorage.depth("/dir")); assertEquals(1, fs.depth("/dir"));
assertEquals(2, mapStorage.depth("/dir/subdir")); assertEquals(2, fs.depth("/dir/subdir"));
} }
@Test @Test
public void testLs() { public void testLs() {
when(mockMap.keyList()).thenReturn(List.of("/dir/file1", "/dir/file2", "/dir/subdir/file3")); when(mockMap.keyList()).thenReturn(List.of("/dir/file1", "/dir/file2", "/dir/subdir/file3"));
List<String> files = mapStorage.list("/dir"); List<String> files = fs.list("/dir");
assertEquals(2, files.size()); assertEquals(2, files.size());
assertTrue(files.contains("/dir/file1")); assertTrue(files.contains("/dir/file1"));

View File

@ -0,0 +1,58 @@
package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.shell.ShellCommandResult;
import com.pixelgamelibrary.api.files.shell.ShellCommandLine;
import com.pixelgamelibrary.api.files.shell.BaseShellCommand;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class BaseShellCommandTest {
private ShellCommandLine mockCommandLine;
private ShellCommandResult mockCommandResult;
private Function<String, ShellCommandResult> mockFunction;
private BaseShellCommand command;
@BeforeEach
void setUp() {
mockCommandLine = mock(ShellCommandLine.class);
mockCommandResult = mock(ShellCommandResult.class);
mockFunction = mock(Function.class);
// When the function is applied, return the mock result
when(mockFunction.apply(anyString())).thenReturn(mockCommandResult);
// Create an instance of BaseShellCommand with mocks
command = new BaseShellCommand(mockCommandLine, "testCommand", mockFunction);
}
@Test
void testGetName() {
assertEquals("testCommand", command.getName());
}
@Test
void testGetShellCommandLine() {
assertEquals(mockCommandLine, command.getShellCommandLine());
}
@Test
void testExecute() {
ShellCommandResult result = command.execute("testCommand arg1");
assertEquals(mockCommandResult, result);
verify(mockFunction).apply("testCommand arg1");
}
@Test
void testSetShellCommandLine() {
ShellCommandLine newCommandLine = mock(ShellCommandLine.class);
command.setShellCommandLine(newCommandLine);
assertEquals(newCommandLine, command.getShellCommandLine());
}
}

View File

@ -0,0 +1,64 @@
package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.shell.ShellCommandResult;
import com.pixelgamelibrary.api.files.shell.ShellCommandLineScanner;
import com.pixelgamelibrary.api.files.shell.ShellCommandLine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import com.pixelgamelibrary.api.files.shell.ShellScanner;
class ShellCommandLineScannerTest {
@Mock
private ShellCommandLine mockShellCommandLine; // Mocking ShellCommandLine
@Mock
private ShellScanner mockCommandLineScanner; // Mocking CommandLineScanner
private ShellCommandLineScanner shellCommandLineScanner; // Manually creating the instance
@BeforeEach
void setUp() {
// Initialize mock objects before each test
MockitoAnnotations.openMocks(this);
}
@Test
void testExecuteSimpleCommand() {
// Arrange
when(mockShellCommandLine.getCommandLineStart()).thenReturn(">");
when(mockCommandLineScanner.nextLine()).thenReturn("someCommand");
ShellCommandResult mockResult = new ShellCommandResult("Command Executed");
when(mockShellCommandLine.execute("someCommand")).thenReturn(mockResult);
when(mockShellCommandLine.isExited()).thenReturn(true);
// Manually create the instance of ShellCommandLineScanner with mocks
shellCommandLineScanner = new ShellCommandLineScanner(mockShellCommandLine, mockCommandLineScanner);
// Assert: Verify that the expected methods were called
verify(mockShellCommandLine).getCommandLineStart();
verify(mockShellCommandLine).execute("someCommand");
}
@Test
void testErrorOutput() {
// Arrange
when(mockShellCommandLine.getCommandLineStart()).thenReturn(">");
when(mockCommandLineScanner.nextLine()).thenReturn("invalidCommand");
ShellCommandResult errorResult = new ShellCommandResult("Error occurred", true);
when(mockShellCommandLine.execute("invalidCommand")).thenReturn(errorResult);
when(mockShellCommandLine.isExited()).thenReturn(true);
// Manually create the instance of ShellCommandLineScanner with mocks
shellCommandLineScanner = new ShellCommandLineScanner(mockShellCommandLine, mockCommandLineScanner);
// Assert: Verify the error output
verify(mockShellCommandLine).execute("invalidCommand");
assertTrue(errorResult.isError(), "The result should indicate an error");
}
}

View File

@ -1,8 +1,7 @@
package com.pixelgamelibrary.api.files.command; package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.command.StorageCommandResult; import com.pixelgamelibrary.api.files.shell.ShellCommandResult;
import com.pixelgamelibrary.api.files.command.StorageCommandLine; import com.pixelgamelibrary.api.files.shell.ShellCommandLine;
import com.pixelgamelibrary.api.files.Storage;
import java.util.Arrays; import java.util.Arrays;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -12,18 +11,19 @@ import java.util.Date;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import com.pixelgamelibrary.api.files.FileSystem;
class StorageCommandLineTest { class ShellCommandLineTest {
private StorageCommandLine commandLine; private ShellCommandLine commandLine;
private Storage mockStorage; private FileSystem mockFileSystem;
@BeforeEach @BeforeEach
void setUp() { void setUp() {
mockStorage = mock(Storage.class); mockFileSystem = mock(FileSystem.class);
when(mockStorage.printWorkingDirectory()).thenReturn("/mock/path"); when(mockFileSystem.printWorkingDirectory()).thenReturn("/mock/path");
when(mockStorage.list()).thenReturn(Arrays.asList("file1.txt", "file2.txt")); when(mockFileSystem.list()).thenReturn(Arrays.asList("file1.txt", "file2.txt"));
commandLine = new StorageCommandLine("user", "hostname", mockStorage); commandLine = new ShellCommandLine("user", "hostname", mockFileSystem);
} }
@Test @Test
@ -39,13 +39,13 @@ class StorageCommandLineTest {
@Test @Test
void testExecuteDateCommand() { void testExecuteDateCommand() {
StorageCommandResult result = commandLine.execute("date"); ShellCommandResult result = commandLine.execute("date");
assertEquals(new Date().toString(), result.getOutput().trim()); assertEquals(new Date().toString(), result.getOutput().trim());
} }
@Test @Test
void testExecuteWhoamiCommand() { void testExecuteWhoamiCommand() {
StorageCommandResult result = commandLine.execute("whoami"); ShellCommandResult result = commandLine.execute("whoami");
assertEquals("user", result.getOutput().trim()); assertEquals("user", result.getOutput().trim());
} }
@ -55,100 +55,100 @@ class StorageCommandLineTest {
String expectedOutput = new Date().toString().substring(11, 19) + " up " String expectedOutput = new Date().toString().substring(11, 19) + " up "
+ (System.nanoTime() - commandLine.startNanoTime) / 1000000000L / 60L + (System.nanoTime() - commandLine.startNanoTime) / 1000000000L / 60L
+ " minutes, 1 user"; + " minutes, 1 user";
StorageCommandResult result = commandLine.execute("uptime"); ShellCommandResult result = commandLine.execute("uptime");
assertEquals(expectedOutput, result.getOutput().trim()); assertEquals(expectedOutput, result.getOutput().trim());
} }
@Test @Test
void testExecuteHostnameCommand() { void testExecuteHostnameCommand() {
StorageCommandResult result = commandLine.execute("hostname"); ShellCommandResult result = commandLine.execute("hostname");
assertEquals("hostname", result.getOutput().trim()); assertEquals("hostname", result.getOutput().trim());
} }
@Test @Test
void testExecuteTestCommand() { void testExecuteTestCommand() {
StorageCommandResult result = commandLine.execute("test arg1"); ShellCommandResult result = commandLine.execute("test arg1");
assertEquals("arg1", result.getOutput().trim()); assertEquals("arg1", result.getOutput().trim());
} }
@Test @Test
void testExecuteUnameCommand() { void testExecuteUnameCommand() {
StorageCommandResult result = commandLine.execute("uname -a"); ShellCommandResult result = commandLine.execute("uname -a");
assertEquals("LinuxBashCommandLinePartialEmulation hostname 0.0.0 (" assertEquals("LinuxBashCommandLinePartialEmulation hostname 0.0.0 ("
+ new Date().toString() + ")", result.getOutput().trim()); + new Date().toString() + ")", result.getOutput().trim());
} }
@Test @Test
void testExecuteLsCommand() { void testExecuteLsCommand() {
StorageCommandResult result = commandLine.execute("ls"); ShellCommandResult result = commandLine.execute("ls");
assertEquals("file1.txt\nfile2.txt", result.getOutput().trim()); assertEquals("file1.txt\nfile2.txt", result.getOutput().trim());
} }
@Test @Test
void testExecutePwdCommand() { void testExecutePwdCommand() {
StorageCommandResult result = commandLine.execute("pwd"); ShellCommandResult result = commandLine.execute("pwd");
assertEquals("/mock/path", result.getOutput().trim()); assertEquals("/mock/path", result.getOutput().trim());
} }
@Test @Test
void testExecuteDepthCommand() { void testExecuteDepthCommand() {
when(mockStorage.depth()).thenReturn(4); when(mockFileSystem.depth()).thenReturn(4);
StorageCommandResult result = commandLine.execute("depth"); ShellCommandResult result = commandLine.execute("depth");
assertEquals(4, Integer.valueOf(result.getOutput().trim())); assertEquals(4, Integer.valueOf(result.getOutput().trim()));
} }
@Test @Test
void testExecuteMkdirCommand() { void testExecuteMkdirCommand() {
when(mockStorage.createDirectories(any())).thenReturn(""); when(mockFileSystem.createDirectories(any())).thenReturn("");
StorageCommandResult result = commandLine.execute("mkdir newDir"); ShellCommandResult result = commandLine.execute("mkdir newDir");
assertEquals("New directory was successfully created", result.getOutput().trim()); assertEquals("New directory was successfully created", result.getOutput().trim());
} }
@Test @Test
void testExecuteCdCommand() { void testExecuteCdCommand() {
when(mockStorage.changeDirectory(any())).thenReturn(""); when(mockFileSystem.changeDirectory(any())).thenReturn("");
StorageCommandResult result = commandLine.execute("cd newDir"); ShellCommandResult result = commandLine.execute("cd newDir");
assertEquals("Changing working directory was successfully created", result.getOutput().trim()); assertEquals("Changing working directory was successfully created", result.getOutput().trim());
} }
@Test @Test
void testExecuteTouchCommand() { void testExecuteTouchCommand() {
when(mockStorage.touch(any())).thenReturn(""); when(mockFileSystem.touch(any())).thenReturn("");
StorageCommandResult result = commandLine.execute("touch newFile.txt"); ShellCommandResult result = commandLine.execute("touch newFile.txt");
assertEquals("New file was successfully created", result.getOutput().trim()); assertEquals("New file was successfully created", result.getOutput().trim());
} }
@Test @Test
void testExecuteReadtextCommand() { void testExecuteReadtextCommand() {
when(mockStorage.readString(any())).thenReturn("file content"); when(mockFileSystem.readString(any())).thenReturn("file content");
StorageCommandResult result = commandLine.execute("readtext file.txt"); ShellCommandResult result = commandLine.execute("readtext file.txt");
assertEquals("Text file was successfully loaded\n\nfile content", result.getOutput().trim()); assertEquals("Text file was successfully loaded\n\nfile content", result.getOutput().trim());
} }
@Test @Test
void testExecuteSavetextCommand() { void testExecuteSavetextCommand() {
when(mockStorage.writeString(any(), any())).thenReturn(""); when(mockFileSystem.writeString(any(), any())).thenReturn("");
StorageCommandResult result = commandLine.execute("savetext file.txt content"); ShellCommandResult result = commandLine.execute("savetext file.txt content");
assertEquals("Text file was successfully saved", result.getOutput().trim()); assertEquals("Text file was successfully saved", result.getOutput().trim());
} }
@Test @Test
void testExecuteDebugCommand() { void testExecuteDebugCommand() {
when(mockStorage.debug()).thenReturn("debug info"); when(mockFileSystem.debug()).thenReturn("debug info");
StorageCommandResult result = commandLine.execute("debug"); ShellCommandResult result = commandLine.execute("debug");
assertEquals("debug info", result.getOutput().trim()); assertEquals("debug info", result.getOutput().trim());
} }
@Test @Test
void testExecuteExitCommand() { void testExecuteExitCommand() {
StorageCommandResult result = commandLine.execute("exit"); ShellCommandResult result = commandLine.execute("exit");
assertTrue(commandLine.isExited()); assertTrue(commandLine.isExited());
assertEquals("Exited", result.getOutput().trim()); assertEquals("Exited", result.getOutput().trim());
} }
@Test @Test
void testExecuteUnsupportedCommand() { void testExecuteUnsupportedCommand() {
StorageCommandResult result = commandLine.execute("unsupported"); ShellCommandResult result = commandLine.execute("unsupported");
assertEquals("Unsupported command: unsupported", result.getOutput().trim()); assertEquals("Unsupported command: unsupported", result.getOutput().trim());
} }
} }

View File

@ -1,15 +1,15 @@
package com.pixelgamelibrary.api.files.command; package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.command.StorageCommandResult; import com.pixelgamelibrary.api.files.shell.ShellCommandResult;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
class StorageCommandResultTest { class ShellCommandResultTest {
@Test @Test
void testDefaultConstructor() { void testDefaultConstructor() {
// Test default constructor which initializes an empty result // Test default constructor which initializes an empty result
StorageCommandResult result = new StorageCommandResult(); ShellCommandResult result = new ShellCommandResult();
assertNotNull(result.getOutput(), "Output should not be null"); assertNotNull(result.getOutput(), "Output should not be null");
assertEquals("", result.getOutput(), "Default output should be empty"); assertEquals("", result.getOutput(), "Default output should be empty");
@ -20,7 +20,7 @@ class StorageCommandResultTest {
void testConstructorWithOutput() { void testConstructorWithOutput() {
// Test constructor that initializes with an output string // Test constructor that initializes with an output string
String expectedOutput = "Test Output"; String expectedOutput = "Test Output";
StorageCommandResult result = new StorageCommandResult(expectedOutput); ShellCommandResult result = new ShellCommandResult(expectedOutput);
assertEquals(expectedOutput, result.getOutput(), "Output should match the provided string"); assertEquals(expectedOutput, result.getOutput(), "Output should match the provided string");
assertFalse(result.isError(), "Result should not indicate an error by default"); assertFalse(result.isError(), "Result should not indicate an error by default");
@ -30,7 +30,7 @@ class StorageCommandResultTest {
void testConstructorWithOutputAndErrorFlag() { void testConstructorWithOutputAndErrorFlag() {
// Test constructor that initializes with output and error flag // Test constructor that initializes with output and error flag
String expectedOutput = "Error Output"; String expectedOutput = "Error Output";
StorageCommandResult result = new StorageCommandResult(expectedOutput, true); ShellCommandResult result = new ShellCommandResult(expectedOutput, true);
assertEquals(expectedOutput, result.getOutput(), "Output should match the provided string"); assertEquals(expectedOutput, result.getOutput(), "Output should match the provided string");
assertTrue(result.isError(), "Error flag should be set to true"); assertTrue(result.isError(), "Error flag should be set to true");
@ -39,7 +39,7 @@ class StorageCommandResultTest {
@Test @Test
void testSetOutputString() { void testSetOutputString() {
// Test setting the output using a string // Test setting the output using a string
StorageCommandResult result = new StorageCommandResult(); ShellCommandResult result = new ShellCommandResult();
String expectedOutput = "New Output"; String expectedOutput = "New Output";
result.setOutput(expectedOutput); result.setOutput(expectedOutput);
@ -49,7 +49,7 @@ class StorageCommandResultTest {
@Test @Test
void testSetOutputInt() { void testSetOutputInt() {
// Test setting the output using an integer // Test setting the output using an integer
StorageCommandResult result = new StorageCommandResult(); ShellCommandResult result = new ShellCommandResult();
int expectedOutput = 12345; int expectedOutput = 12345;
result.setOutput(expectedOutput); result.setOutput(expectedOutput);
@ -59,7 +59,7 @@ class StorageCommandResultTest {
@Test @Test
void testSetErrorOutput() { void testSetErrorOutput() {
// Test setting an error output and marking the result as an error // Test setting an error output and marking the result as an error
StorageCommandResult result = new StorageCommandResult(); ShellCommandResult result = new ShellCommandResult();
String errorOutput = "Error occurred"; String errorOutput = "Error occurred";
result.setErrorOutput(errorOutput); result.setErrorOutput(errorOutput);
@ -70,7 +70,7 @@ class StorageCommandResultTest {
@Test @Test
void testSetErrorFlag() { void testSetErrorFlag() {
// Test setting the error flag directly // Test setting the error flag directly
StorageCommandResult result = new StorageCommandResult(); ShellCommandResult result = new ShellCommandResult();
result.setError(true); result.setError(true);
assertTrue(result.isError(), "Error flag should be set to true"); assertTrue(result.isError(), "Error flag should be set to true");

View File

@ -0,0 +1,65 @@
package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.shell.ShellCommandResult;
import com.pixelgamelibrary.api.files.shell.ShellCommandLine;
import com.pixelgamelibrary.api.files.shell.BaseShellCommand;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.pixelgamelibrary.api.files.shell.ShellCommand;
class ShellCommandTest {
private ShellCommand mockCommand;
private ShellCommandLine mockCommandLine;
private ShellCommandResult mockCommandResult;
private Function<String, ShellCommandResult> mockFunction;
@BeforeEach
void setUp() {
mockCommandLine = mock(ShellCommandLine.class);
mockCommandResult = mock(ShellCommandResult.class);
mockFunction = mock(Function.class);
// Mock the behavior of execute method
when(mockFunction.apply(anyString())).thenReturn(mockCommandResult);
// Create an instance of BaseShellCommand with mocks
mockCommand = new BaseShellCommand(mockCommandLine, "testCommand", mockFunction);
}
@Test
void testGetName() {
assertEquals("testCommand", mockCommand.getName());
}
@Test
void testGetShellCommandLine() {
assertEquals(mockCommandLine, mockCommand.getShellCommandLine());
}
@Test
void testSetShellCommandLine() {
ShellCommandLine newCommandLine = mock(ShellCommandLine.class);
mockCommand.setShellCommandLine(newCommandLine);
assertEquals(newCommandLine, mockCommand.getShellCommandLine());
}
@Test
void testExecute() {
ShellCommandResult result = mockCommand.execute("testCommand arg1");
assertEquals(mockCommandResult, result);
verify(mockFunction).apply("testCommand arg1");
}
@Test
void testEmptyNewResult() {
ShellCommandResult result = ShellCommand.emptyNewResult();
assertNotNull(result);
assertTrue(result instanceof ShellCommandResult);
}
}