From 7aafe31bebface0546a52e08f5725f4f4a0035ab Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Sat, 11 Oct 2014 23:57:46 +0400 Subject: [PATCH 01/14] First FileMap commit Can't wait to fix all checkstyle errors --- .../NikolaiKrivchanskii/Shell/Commands.java | 11 ++ .../NikolaiKrivchanskii/Shell/Parser.java | 45 +++++ .../NikolaiKrivchanskii/Shell/Shell.java | 112 +++++++++++ .../NikolaiKrivchanskii/Shell/ShellState.java | 14 ++ .../Shell/SomeCommand.java | 4 + .../Shell/SomethingIsWrongException.java | 20 ++ .../Shell/UtilMethods.java | 100 ++++++++++ .../filemap/CommitCommand.java | 23 +++ .../filemap/ExitCommand.java | 24 +++ .../filemap/FileMapMain.java | 20 ++ .../filemap/FileMapReadingUtils.java | 112 +++++++++++ .../filemap/FileMapShellState.java | 6 + .../filemap/FileMapShellStateInterface.java | 26 +++ .../filemap/FileMapWritingUtils.java | 66 +++++++ .../filemap/GetCommand.java | 31 +++ .../filemap/GlobalUtils.java | 152 +++++++++++++++ .../NikolaiKrivchanskii/filemap/MyTable.java | 15 ++ .../filemap/PutCommand.java | 29 +++ .../filemap/ReadingUtils.java | 137 +++++++++++++ .../filemap/RemoveKeyCommand.java | 27 +++ .../filemap/RollbackCommand.java | 23 +++ .../filemap/SingleFileTable.java | 39 ++++ .../filemap/SizeCommand.java | 25 +++ .../filemap/SomeTable.java | 180 ++++++++++++++++++ .../NikolaiKrivchanskii/filemap/Table.java | 11 ++ .../filemap/TableBuilder.java | 16 ++ .../filemap/WritingUtils.java | 59 ++++++ .../multifilemap/CreateCommand.java | 24 +++ .../multifilemap/Database.java | 68 +++++++ .../multifilemap/DatabaseFactory.java | 14 ++ .../multifilemap/DatabaseTest.java | 88 +++++++++ .../multifilemap/DropCommand.java | 25 +++ .../MultiFileMapReadingUtils.java | 34 ++++ .../multifilemap/MultiFileMapShellState.java | 7 + .../MultiFileMapTableBuilder.java | 27 +++ .../MultiFileMapWritingUtils.java | 57 ++++++ .../multifilemap/MultifileMapMain.java | 32 ++++ .../MultifileMapShellStateInterface.java | 15 ++ .../multifilemap/MultifileTable.java | 99 ++++++++++ .../multifilemap/MultifileTableTest.java | 173 +++++++++++++++++ .../multifilemap/TableProvider.java | 10 + .../multifilemap/TableProviderFactory.java | 5 + .../multifilemap/UseCommand.java | 24 +++ 43 files changed, 2029 insertions(+) create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Parser.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/ShellState.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/SomeCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/SomethingIsWrongException.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/UtilMethods.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapReadingUtils.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapWritingUtils.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GlobalUtils.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableBuilder.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/WritingUtils.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProvider.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProviderFactory.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java new file mode 100644 index 000000000..0285523d1 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java @@ -0,0 +1,11 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell; + + +public interface Commands { + + public String getCommandName(); + + public int getArgumentQuantity(); + + abstract public void implement(String[] args, State state) throws SomethingIsWrongException; +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Parser.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Parser.java new file mode 100644 index 000000000..cc3c5c144 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Parser.java @@ -0,0 +1,45 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell; + +import java.util.ArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Parser { + + + public static ArrayList parseCommandArgs(String params) { + ArrayList matchList = new ArrayList(); + Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'"); + Matcher regexMatcher = regex.matcher(params); + while (regexMatcher.find()) { + String param = regexMatcher.group().replaceAll("\"?([~\"]*)\"?", "$1"); + matchList.add(param); + } + return matchList; + } + + public static String getName(String command) { + int spiltIndex = command.indexOf(' '); + if (spiltIndex == -1) { + return command; + } else { + return command.substring(0, spiltIndex); + } + } + + public static String[] parseFullCommand(String commands) { + String[] commandArray = commands.split(";"); + for (int i = 0; i < commandArray.length; ++i) { + commandArray[i] = commandArray[i].trim(); + } + return commandArray; + } + public static String getParameters(String command) { + int spiltIndex = command.indexOf(' '); + if (spiltIndex == -1) { + return ""; + } else { + return command.substring(spiltIndex + 1); + } + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java new file mode 100644 index 000000000..34b2e7ab9 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java @@ -0,0 +1,112 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Scanner; +import java.util.Set; + + +public class Shell { + private final Map availableCommands; + private static final String greeting = "$ "; + State state; + + + public Shell (Set commands) { + Map tempCommands = new HashMap(); + for (Commands temp : commands) { + tempCommands.put(temp.getCommandName(), temp); + } + availableCommands = Collections.unmodifiableMap(tempCommands); + } + + public void setShellState(State state) { + this.state = state; + } + + private void runCommand(String[] data, State state) throws SomethingIsWrongException { + if (data[0].length() == 0) { + throw new SomethingIsWrongException ("Empty string."); + } + Commands usedOne = availableCommands.get(data[0]); + if (usedOne == null) { + throw new SomethingIsWrongException ("Unknown command."); + } else if (data.length - 1 != usedOne.getArgumentQuantity() ) { + if(!(usedOne.getCommandName().equals("rm") && data.length - 1 == usedOne.getArgumentQuantity() + 1) + && !(usedOne.getCommandName().equals("cp") && data.length - 1 == usedOne.getArgumentQuantity() + 1)) { + throw new SomethingIsWrongException ("Wrong number of arguments. Correct argument quantity = " + (data.length-1) + + "\nTo correctly run this command use " + usedOne.getArgumentQuantity() + " arguments."); + } + } + String[] commandArguments = Arrays.copyOfRange(data, 1, data.length); + usedOne.implement(commandArguments, state); + } + + private String[] splitLine(String str) { + str = str.trim(); + String[] toReturn = str.split("\\s*;\\s*", -2); + return toReturn; + } + private void runLine(String line, State state) throws SomethingIsWrongException { + String[] splitted = splitLine(line); + int count = splitted.length - 1; + for (String temp : splitted) { + --count; + if (count >= 0) { + runCommand(temp.split("\\s+"), state); //This thing is needed to check if after last ";" + } else if (count < 0) { //situated a command or an empty string. So it + if (temp.length() != 0) { //won't throw a "Wrong command" exception when it + runCommand(temp.split("\\s+"), state); //looks like: "dir; cd ..; dir;" neither it will + } //loose a "dir" in: "dir; cd ..; dir; dir". + } //So it does nothing if it is the end, but performs + } //if there is a command after last ";". + } + + public void consoleWay(State state) { + Scanner forInput = new Scanner(System.in); + while (!Thread.currentThread().isInterrupted()) { + System.out.print(greeting); + try { + runLine(forInput.nextLine(), state); + } catch (SomethingIsWrongException exc) { + if (exc.getMessage().equals("EXIT")) { + forInput.close(); + System.exit(0); + } else { + System.err.println(exc.getMessage()); + } + } + } + forInput.close(); + } + + /* public static void notmain(String[] args) { + ShellState state = new ShellState(System.getProperty("user.dir")); + Set commands = new HashSet() {{ /*add(new WhereAreWeCommand()); add(new CopyCommand()); add(new DirectoryInfoCommand()); + add(new ExitCommand()); add(new MakeDirectoryCommand()); add(new MoveCommand()); add(new RemoveCommand()); }};*/ + /* Shell shell = new Shell(commands); + + if (args.length != 0) { + String arg = UtilMethods.uniteItems(Arrays.asList(args), " "); + try { + shell.runLine(arg, state); + } catch (SomethingIsWrongException exc) { + if (exc.getMessage().equals("EXIT")) { + System.exit(0); + } else { + System.err.println(exc.getMessage()); + System.exit(-1); + } + } + } else { + shell.consoleWay(state); + } + System.exit(0); + }*/ + + + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/ShellState.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/ShellState.java new file mode 100644 index 000000000..51e8abbc3 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/ShellState.java @@ -0,0 +1,14 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell; + +public class ShellState { + private String currentDirectory; + public ShellState(String currentDirectory) { + this.currentDirectory = currentDirectory; + } + public String getCurDir() { + return currentDirectory; + } + void changeCurDir(String newCurDir) { + currentDirectory = newCurDir; + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/SomeCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/SomeCommand.java new file mode 100644 index 000000000..8e1592e66 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/SomeCommand.java @@ -0,0 +1,4 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell; + +public abstract class SomeCommand implements Commands { +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/SomethingIsWrongException.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/SomethingIsWrongException.java new file mode 100644 index 000000000..cfe244972 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/SomethingIsWrongException.java @@ -0,0 +1,20 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell; + + +public final class SomethingIsWrongException extends Exception { + public SomethingIsWrongException() { + super(); + } + + public SomethingIsWrongException(String message) { + super(message); + } + + public SomethingIsWrongException(String message, Throwable cause) { + super(message, cause); + } + + public SomethingIsWrongException(Throwable cause) { + super(cause); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/UtilMethods.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/UtilMethods.java new file mode 100644 index 000000000..c37a18629 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/UtilMethods.java @@ -0,0 +1,100 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell; + +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Collection; + +public class UtilMethods { + public static final String ENCODING = "UTF-8"; + public static String uniteItems(Collection items, String separator) { + boolean isFirstIteration = true; + StringBuilder joinBuilder = new StringBuilder(); + for (Object item: items) { + if(isFirstIteration) { + isFirstIteration = false; + } else { + joinBuilder.append(separator); + } + joinBuilder.append(item.toString()); + } + return joinBuilder.toString(); + } + + public static void closeCalm(Closeable something) { + try { + if (something != null) { + something.close(); + } + } catch (IOException e) { + System.err.println("Error aquired while trying to close " + e.getMessage()); + } + } + + public static void copyFile(File source, File dirDestination) throws SomethingIsWrongException { + File copy = new File(dirDestination, source.getName()); + FileInputStream ofOriginal = null; + FileOutputStream ofCopy = null; + try { + copy.createNewFile(); + ofOriginal = new FileInputStream(source); + ofCopy = new FileOutputStream(copy); + byte[] buf = new byte[4096]; //size of reading = 4kB + int read = ofOriginal.read(buf); + while(read > 0) { + ofCopy.write(buf, 0, read); + read = ofOriginal.read(buf); + } + } catch (FileNotFoundException e) { + throw new SomethingIsWrongException ("This file or directory doesn't exist yet. " + e.getMessage()); + } catch (IOException e) { + throw new SomethingIsWrongException ("Error while writing/reading file. " + e.getMessage()); + } finally { + closeCalm(ofOriginal); + closeCalm(ofCopy); + } + } + + public static File getAbsoluteName(String fileName, ShellState state) { + File file = new File(fileName); + + if (!file.isAbsolute()){ + file = new File(state.getCurDir(), fileName); + } + return file; + } + public static byte[] getBytes(String string, String encoding) throws SomethingIsWrongException { + byte[] bytes = null; + try { + bytes = string.getBytes(encoding); + } catch (UnsupportedEncodingException e) { + throw new SomethingIsWrongException("Unable to convert string to bytes of this type: " + e.getMessage()); + } + return bytes; + } + + public static byte[] bytesToArray(ByteArrayOutputStream bytes) { + byte[] result = new byte[bytes.size()]; + result = bytes.toByteArray(); + return result; + } + + public static boolean doesExist(String path) { + File file = new File(path); + return file.exists(); + } + + public static int countBytes(String string, String encoding) { + try { + byte[] bytes = string.getBytes(encoding); + return bytes.length; + } catch(Exception e) { + return 0; + } + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java new file mode 100644 index 000000000..d57e63661 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java @@ -0,0 +1,23 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +public class CommitCommand implements Commands{ + + public String getCommandName() { + return "commit"; + } + + public int getArgumentQuantity() { + return 0; + } + + public void implement(String[] args, FileMapShellState state) + throws SomethingIsWrongException { + if (state.table == null) { + throw new SomethingIsWrongException ("Table not found."); + } + state.table.commit(); + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java new file mode 100644 index 000000000..84965470f --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java @@ -0,0 +1,24 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +public class ExitCommand implements Commands { + + public String getCommandName() { + return "exit"; + } + + public int getArgumentQuantity() { + return 0; + } + public void implement(String[] args, FileMapShellState state) throws SomethingIsWrongException { + MyTable temp = (MyTable) state.table; + if (state.table != null && !temp.getAutoCommit()) { + temp.rollback(); + } else if (temp.getAutoCommit() && state.table != null) { + temp.commit(); + } + throw new SomethingIsWrongException("EXIT"); + } + +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java new file mode 100644 index 000000000..402513438 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java @@ -0,0 +1,20 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + + +import java.util.HashSet; +import java.util.Set; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +public class FileMapMain { + public static void main(String[] args) { + FileMapShellState state = new FileMapShellState(); + Set com = new HashSet() {{ add(new ExitCommand()); add(new RollbackCommand()); add(new CommitCommand()); + add(new PutCommand()); add(new GetCommand()); add(new RemoveKeyCommand());}}; + Shell shell = new Shell(com); + String dbDirectory = System.getProperty("fizteh.db.dir"); + state.table = new SingleFileTable(dbDirectory, "master"); + shell.setShellState(state); + shell.consoleWay(state); + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapReadingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapReadingUtils.java new file mode 100644 index 000000000..31f88128a --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapReadingUtils.java @@ -0,0 +1,112 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.EOFException; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; + + +public class FileMapReadingUtils implements Closeable{ + + protected static RandomAccessFile tempFile; + private static int valueShift = -1; + + public FileMapReadingUtils(String pathToFile) throws IOException { + try { + tempFile = new RandomAccessFile(pathToFile, "r"); + } catch (FileNotFoundException e) { + tempFile = null; + valueShift = 0; + return; + } + if (tempFile.length() == 0) { + throw new IOException("empty file"); + } + skipKey(); + valueShift = readOffset(); + tempFile.seek(0); + } + + public String readKey() throws IOException { + if (tempFile.getFilePointer() >= valueShift) { + return null; + } + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte b = tempFile.readByte(); + while(b != 0) { + bytes.write(b); + b = tempFile.readByte(); + } + return new String(bytes.toByteArray(), GlobalUtils.ENCODING); + } + + public String readValue() throws IOException { + int offset = readOffset(); + int nextOffset = readNextOffset(); + long currentOffset; + currentOffset = tempFile.getFilePointer(); + tempFile.seek(offset); + int valueLength = nextOffset-offset; + byte[] bytes = new byte[valueLength]; + tempFile.read(bytes, 0, valueLength); + tempFile.seek(currentOffset); + return new String(bytes, GlobalUtils.ENCODING); + + } + + public static void scanFromDisk(String file, TableBuilder builder) throws IOException { + if (!GlobalUtils.doesExist(file)) { + throw new IOException("didn't exist"); + } + FileMapReadingUtils read = new FileMapReadingUtils(file); + while (!read.endOfFile()) { + String key = read.readKey(); + String value = read.readValue(); + builder.put(key, value); + } + read.close(); + } + + public boolean endOfFile() throws IOException { + if (tempFile == null) { + return true; + } + boolean result = true; + try { + result = (tempFile.getFilePointer() == valueShift); + } catch (EOFException e) { + + } + return result; + } + + + private int readNextOffset() throws IOException { + int nextOffset = 0; + long currentOffset = tempFile.getFilePointer(); + if (readKey() == null) { + nextOffset = (int)tempFile.length(); + } else { + nextOffset = readOffset(); + } + tempFile.seek(currentOffset); + return nextOffset; + } + + private void skipKey() throws IOException { + byte b; + do { + b = tempFile.readByte(); + } while(b != 0); + } + + private int readOffset() throws IOException { + return tempFile.readInt(); + } + + public void close () { + GlobalUtils.closeCalm(tempFile); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java new file mode 100644 index 000000000..9cd0ba04d --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java @@ -0,0 +1,6 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + + +public class FileMapShellState { + public Table table = null; + } \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java new file mode 100644 index 000000000..1697958d4 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java @@ -0,0 +1,26 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +public interface FileMapShellStateInterface { + + public Value put (Key key, Value value); + + public Value get (Key key); + + public int commit(); + + public int rollback(); + + public int size(); + + public Value remove(Key key); + + public Table getTable(); + + public String keyToString(Key key); + + public String valueToString(Value value); + + public Key parseKey(String key); + + public Value parseValue(String value); +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapWritingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapWritingUtils.java new file mode 100644 index 000000000..32b314377 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapWritingUtils.java @@ -0,0 +1,66 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import java.io.Closeable; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.io.UnsupportedEncodingException; +import java.util.Set; + + + +public class FileMapWritingUtils implements Closeable { + + protected static RandomAccessFile dataFile; + public FileMapWritingUtils(String filePath) throws IOException { + try { + dataFile = new RandomAccessFile(filePath, "rw"); + } + catch (FileNotFoundException e) { + throw new IOException(String.format("error while creating file: '%s'", filePath)); + } + try { + dataFile.setLength(0); + } catch (IOException e) { + throw new IOException("Error aqcuired while resizing a file " + e.getMessage()); + } + } + + public void writeKey(String key) throws IOException { + byte[] bytes = GlobalUtils.getBytes(key, GlobalUtils.ENCODING); + dataFile.write(bytes); + dataFile.writeByte(0); + } + + public static void writeOnDisk(Set keys, String file, TableBuilder builder) throws IOException { + FileMapWritingUtils write = new FileMapWritingUtils(file); + int shift = GlobalUtils.getKeysLength(keys, GlobalUtils.ENCODING); + for (String key : keys) { + write.writeKey(key); + write.writeOffset(shift); + shift += GlobalUtils.countBytes(builder.get(key), GlobalUtils.ENCODING); + } + for (String key : keys) { + write.writeValue(builder.get(key)); + } + write.close(); + } + + public void writeOffset(int offset) throws IOException { + dataFile.writeInt(offset); + } + + public void writeValue(String value) throws IOException { + try { + byte[] bytes = value.getBytes(GlobalUtils.ENCODING); + dataFile.write(bytes); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException("Unrecognized encoding"); + } + } + + public void close() { + GlobalUtils.closeCalm(dataFile); + } + +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java new file mode 100644 index 000000000..9e706382c --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java @@ -0,0 +1,31 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; +import java.util.ArrayList; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +public class GetCommand implements Commands{ + + public String getCommandName() { + return "get"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String[] args, FileMapShellState state) + throws SomethingIsWrongException { + if(state.table == null) { + throw new SomethingIsWrongException ("Table not found."); + } + String value = state.table.get(args[0]); + if (value == null) { + System.out.println("Not found\n"); + } else { + System.out.println("Found:\n" + value); + } + + } + + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GlobalUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GlobalUtils.java new file mode 100644 index 000000000..236b87a55 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GlobalUtils.java @@ -0,0 +1,152 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Collection; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.ShellState; + +public class GlobalUtils { + public static final Charset ENCODING = StandardCharsets.UTF_8; + public static final int DIR_QUANTITY = 16; + public static final int FILES_PER_DIR = 16; + private static final Pattern DIR_PATTERN = Pattern.compile("([^\\.]+).dir"); + private static final Pattern FILE_PATTERN = Pattern.compile("([^\\.]+).dat"); + + public static String uniteItems(Collection items, String separator) { + boolean isFirstIteration = true; + StringBuilder joinBuilder = new StringBuilder(); + for (Object item: items) { + if(isFirstIteration) { + isFirstIteration = false; + } else { + joinBuilder.append(separator); + } + joinBuilder.append(item.toString()); + } + return joinBuilder.toString(); + } + + public static void closeCalm(Closeable something) { + try { + if (something != null) { + something.close(); + } + } catch (IOException e) { + System.err.println("Error aqcuired while trying to close " + e.getMessage()); + } + } + + public static File getAbsoluteName(String fileName, ShellState state) { + File file = new File(fileName); + + if (!file.isAbsolute()){ + file = new File(state.getCurDir(), fileName); + } + return file; + } + public static byte[] getBytes(String string, Charset encoding) { + byte[] bytes = null; + bytes = string.getBytes(encoding); + return bytes; + } + + public static byte[] bytesToArray(ByteArrayOutputStream bytes) { + byte[] result = new byte[bytes.size()]; + result = bytes.toByteArray(); + return result; + } + + public static boolean doesExist(String path) { + File file = new File(path); + return file.exists(); + } + + public static int countBytes(String string, Charset encoding) { + byte[] bytes = string.getBytes(encoding); + return bytes.length; + } + + public static int getKeysLength(Set keys, Charset charset) { + int keysLength = 0; + for (final String key : keys) { + int keyLength = countBytes(key, charset); + keysLength += keyLength + 5; + } + return keysLength; + } + + public static boolean compare(Object key1, Object key2) { + if (key1 == null && key2 == null) { + return true; + } else if (key1 == null || key2 == null) { + return false; + } else { + return key1.equals(key2); + } + } + + public static void deleteFile(File fileToDelete) { + if (!fileToDelete.exists()) { + return; + } + if (fileToDelete.isDirectory()) { + for (final File file : fileToDelete.listFiles()) { + deleteFile(file); + } + } + fileToDelete.delete(); + } + + public static int parseDirNumber(File dir) { + String name = dir.getName(); + Matcher matcher = DIR_PATTERN.matcher(name); + if (matcher.matches()) { + return Integer.parseInt(matcher.group(1)); + } + throw new IllegalArgumentException("incorrect dir name"); + } + + public static int parseFileNumber(File file) { + String name = file.getName(); + Matcher matcher = FILE_PATTERN.matcher(name); + if (matcher.matches()) { + return Integer.parseInt(matcher.group(1)); + } + throw new IllegalArgumentException("incorrect file name"); + } + + public static void checkKeyPlacement(String key, int currentDir, int currentFile) + { + if (currentDir != getDirNumber(key) || currentFile != getFileNumber(key)) { + throw new IllegalArgumentException("invalid key placement"); + } + } + + public static String parseTableName(String params) + { + int index = params.indexOf(' '); + if (index == -1) + { + return params; + } + return params.substring(0, index); + } + + public static int getDirNumber(String key) { + byte[] bytes = GlobalUtils.getBytes(key, GlobalUtils.ENCODING); + return Math.abs(bytes[0] % DIR_QUANTITY); + } + + public static int getFileNumber(String key) { + byte[] bytes = GlobalUtils.getBytes(key, GlobalUtils.ENCODING); + return Math.abs(bytes[0] / DIR_QUANTITY % FILES_PER_DIR); + } + +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java new file mode 100644 index 000000000..ae2354d1a --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java @@ -0,0 +1,15 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + + +public interface MyTable extends Table { + String getName(); + void setAutoCommit(boolean status); + boolean getAutoCommit(); + int getChangesCounter(); + String get(String a); + String put(String key, String value); + String remove(String a); + int size(); + int commit(); + int rollback(); +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java new file mode 100644 index 000000000..98ba4c4f8 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java @@ -0,0 +1,29 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; +import java.util.ArrayList; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +public class PutCommand implements Commands { + + public String getCommandName() { + return "put"; + } + + public int getArgumentQuantity() { + return 2; + } + + public void implement(String[] args, FileMapShellState state) + throws SomethingIsWrongException { + if (state.table == null) { + throw new SomethingIsWrongException("No table chosen"); + } + String temp = state.table.put(args[0], args[1]); + if (temp != null) { + System.out.println("overwrite\n" + temp); + } else { + System.out.println("new"); + } + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java new file mode 100644 index 000000000..4836869f6 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java @@ -0,0 +1,137 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +import java.io.ByteArrayOutputStream; +import java.io.EOFException; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.io.UnsupportedEncodingException; + + +public class ReadingUtils { + + protected RandomAccessFile tempFile; + private static int valueShift = -1; + + public ReadingUtils(String pathToFile) throws SomethingIsWrongException { + try { + tempFile = new RandomAccessFile(pathToFile, "r"); + } catch (FileNotFoundException e) { + tempFile = null; + valueShift = 0; + return; + } + skipKey(); + valueShift = readOffset(); + try { + tempFile.seek(0); + } catch (IOException e) { + throw new SomethingIsWrongException("Error aqcuired while seeking through file: " + e.getMessage()); + } + } + + public String readKey() throws SomethingIsWrongException { + byte[] array; + try { + if (tempFile.getFilePointer() >= valueShift) { + return null; + } + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte b = tempFile.readByte(); + while(b != 0) { + bytes.write(b); + b = tempFile.readByte(); + } + array = UtilMethods.bytesToArray(bytes); + } catch (IOException e) { + throw new SomethingIsWrongException("Error acquired: " + e.getMessage()); + } + String returnKey; + try { + returnKey = new String(array, UtilMethods.ENCODING); + } catch (UnsupportedEncodingException e) { + throw new SomethingIsWrongException("Error acquired: " + e.getMessage()); + } + return returnKey; + } + + public String readValue() throws SomethingIsWrongException { + int offset = readOffset(); + int nextOffset = readNextOffset(); + long currentOffset; + try { + currentOffset = tempFile.getFilePointer(); + tempFile.seek(offset); + int valueLength = nextOffset-offset; + byte[] bytes = new byte[valueLength]; + tempFile.read(bytes, 0, valueLength); + tempFile.seek(currentOffset); + return new String(bytes, UtilMethods.ENCODING); + } catch (IOException e) { + throw new SomethingIsWrongException("Error acquired: " + e.getMessage()); + } + + } + + public boolean endOfFile() throws SomethingIsWrongException { + if (tempFile == null) { + return true; + } + + boolean result = true; + try { + result = (tempFile.getFilePointer() == valueShift); + } catch (EOFException ee) { + return result; + } catch (IOException e) { + if (e.getMessage() != null) { + throw new SomethingIsWrongException("Error aqcuired while reading a file " + e.getMessage()); + } + } + return result; + } + + + private int readNextOffset() throws SomethingIsWrongException { + int nextOffset = 0; + try { + int currentOffset = (int) tempFile.getFilePointer(); + if (readKey() == null) { + nextOffset = (int)tempFile.length(); + } else { + nextOffset = readOffset(); + } + tempFile.seek(currentOffset); + } catch (IOException e) { + if (e.getMessage() != null) { + if (e.getMessage() != null) { + throw new SomethingIsWrongException("Error aqcuired while reading a file " + e.getMessage()); + } + } + } + return nextOffset; + } + + private void skipKey() throws SomethingIsWrongException { + byte b = 0; + do { + try { + b = tempFile.readByte(); + } catch (IOException e) { + if (e.getMessage() != null) { + throw new SomethingIsWrongException("Error aqcuired while reading a file " + e.getMessage()); + } + } + } while(b != 0); + } + + private int readOffset() throws SomethingIsWrongException { + try { + return tempFile.readInt(); + } catch (IOException e) { + throw new SomethingIsWrongException("Error aqcuired while reading a file " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java new file mode 100644 index 000000000..6e0a70010 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java @@ -0,0 +1,27 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; +import java.util.ArrayList; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Commands; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; + +public class RemoveKeyCommand implements Commands { + + public String getCommandName() { + return "remove"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String[] args, FileMapShellState state) + throws SomethingIsWrongException { + String a = state.table.remove(args[0]); + if (a.isEmpty()) { + System.out.println("not found"); + } else { + System.out.println("found\n" + a); + } + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java new file mode 100644 index 000000000..f14d29f1a --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java @@ -0,0 +1,23 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +public class RollbackCommand implements Commands { + + public String getCommandName() { + return "rollback"; + } + + public int getArgumentQuantity() { + return 0; + } + + public void implement(String[] args, FileMapShellState state) + throws SomethingIsWrongException { + if (state.table == null) { + throw new SomethingIsWrongException ("No table chosen"); + } + state.table.rollback(); + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java new file mode 100644 index 000000000..0683adead --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java @@ -0,0 +1,39 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + + +import java.io.File; +import java.io.IOException; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; + + +public class SingleFileTable extends SomeTable { + + public static final String DATABASENAME = "db.dat"; + + public SingleFileTable(String dir, String name) { + super(dir, name); + } + + protected void load() throws SomethingIsWrongException { + scanFromDisk(getPathToDatabase()); + } + + protected void save() throws SomethingIsWrongException { + writeOnDisk(unchangedOldData.keySet(), getPathToDatabase()); + } + + private String getPathToDatabase() { + File curDir = new File(new File(".").getAbsolutePath()); + File databaseFile; + try { + databaseFile = new File (curDir.getCanonicalPath(), DATABASENAME); + return databaseFile.getAbsolutePath(); + } catch (IOException e) { + e.getMessage(); + } + return ""; + } + + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java new file mode 100644 index 000000000..17965d6e6 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java @@ -0,0 +1,25 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; + +public class SizeCommand> extends SomeCommand { + + public String getCommandName() { + return "size"; + } + + public int getArgumentQuantity() { + return 0; + } + + public void implement(String[] args, State state) + throws SomethingIsWrongException { + if (state.getTable() == null) { + throw new SomethingIsWrongException("no table"); + } + System.out.println(state.size()); + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java new file mode 100644 index 000000000..6e6175e71 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java @@ -0,0 +1,180 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + + +public abstract class SomeTable implements MyTable { + protected static HashMap unchangedOldData; + protected static HashMap currentData; + protected static HashSet deletedKeys; + private String name; + private String parentDirectory; + private static int size; + public static int unsavedChangesCounter; + protected boolean autoCommit = true; //to block JUnit functional for a filemap + protected abstract void load() throws SomethingIsWrongException; + protected abstract void save() throws SomethingIsWrongException; + + + public void setAutoCommit(boolean status) { + autoCommit = status; + } + + public boolean getAutoCommit() { + return autoCommit; + } + + public int getChangesCounter() { + return unsavedChangesCounter; + } + + public String getParentDirectory() { + return parentDirectory; + } + + public String getName() { + return name; + } + public int size() { + return size; + } + + public int getChangesCount() { + return unsavedChangesCounter; + } + + public SomeTable(String dir, String name) { + this.parentDirectory = dir; + this.name = name; + unchangedOldData = new HashMap(); + currentData = new HashMap(); + deletedKeys = new HashSet(); + unsavedChangesCounter = 0; + try { + load(); + } catch (SomethingIsWrongException e) { + System.err.println("Error aqcuired while opening a table. Message: " + e.getMessage()); + } + + } + + public String get(String key) { + if (currentData.containsKey(key)) { + return currentData.get(key); + } else if (deletedKeys.contains(key)) { + return null; + } + return unchangedOldData.get(key); + } + + public String put(String key, String Value) { + String value = oldValue(key); + currentData.put(key, Value); + if (value == null) { + ++size; + } + ++unsavedChangesCounter; + return value; + } + + public String remove(String key) { + String value = oldValue(key); + if (currentData.containsKey(key)) { + currentData.remove(key); + if (unchangedOldData.containsKey(key)) { + deletedKeys.add(key); + } + } else { + deletedKeys.add(key); + } + if (value != null) { + --size; + } + ++unsavedChangesCounter; + return value; + } + + private static String oldValue(String key) { + String oldValue = currentData.get(key); + if (oldValue == null && !deletedKeys.contains(key)) { + oldValue = unchangedOldData.get(key); + } + return oldValue; + } + + private int keySize(Set keys) { + int keysSize = 0; + for (String key : keys) { + keysSize += UtilMethods.countBytes(key, UtilMethods.ENCODING) + 5; + } + return keysSize; + } + + public void writeOnDisk(Set keys, String file) throws SomethingIsWrongException { + WritingUtils write = new WritingUtils(file); + int temp = keySize(keys); + for(String key : keys) { + write.writeKey(key); + write.writeOffset(temp); + temp += UtilMethods.countBytes(unchangedOldData.get(key), UtilMethods.ENCODING); + } + for(String key : keys) { + String tempCheck = unchangedOldData.get(key); + if (tempCheck != null) { + write.writeValue(tempCheck); + } + } + UtilMethods.closeCalm(write.dataFile); + } + + public void scanFromDisk(String file) throws SomethingIsWrongException { + if (!UtilMethods.doesExist(file)) { + throw new SomethingIsWrongException("Unable to scan from disc."); + } + ReadingUtils read = new ReadingUtils(file); + while(!read.endOfFile()) { + String key = read.readKey(); + String value = read.readValue(); + unchangedOldData.put(key, value); + } + UtilMethods.closeCalm(read.tempFile); + } + + public int rollback() { + int deletedOrAdded = Math.abs(unchangedOldData.size() - size); + deletedKeys.clear(); + currentData.clear(); + size = unchangedOldData.size(); + unsavedChangesCounter = 0; + return deletedOrAdded; + } + + public int commit() { + int commitCount = Math.abs(unchangedOldData.size() - size); + for (final String toDelete : deletedKeys) { + unchangedOldData.remove(toDelete); + } + for (String toAdd : currentData.keySet()) { + unchangedOldData.put(toAdd, currentData.get(toAdd)); + } + size = unchangedOldData.size(); + try { + save(); + } catch (SomethingIsWrongException e) { + System.out.println("Error aqcuired while commiting changes. Message: " + e.getMessage()); + } + unsavedChangesCounter = 0; + deletedKeys.clear(); + currentData.clear(); + return commitCount; + } + + + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java new file mode 100644 index 000000000..819a12d49 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java @@ -0,0 +1,11 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +public interface Table { + String getName(); + String get(String a); + String put(String a, String b); + String remove(String a); + int size(); + int commit(); + int rollback(); +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableBuilder.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableBuilder.java new file mode 100644 index 000000000..260f91bf4 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableBuilder.java @@ -0,0 +1,16 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import java.io.File; +import java.util.Set; + +public interface TableBuilder { + public String get(String key); + + public void put(String key, String value); + + public Set getKeys(); + + public File getTableDirectory(); + + public void setCurrentFile(File currentFile); +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/WritingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/WritingUtils.java new file mode 100644 index 000000000..4bfd33ab8 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/WritingUtils.java @@ -0,0 +1,59 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.io.UnsupportedEncodingException; + + + +public class WritingUtils { + + protected RandomAccessFile dataFile; + public WritingUtils(String filePath) throws SomethingIsWrongException { + try { + dataFile = new RandomAccessFile(filePath, "rw"); + } + catch (FileNotFoundException e) { + throw new SomethingIsWrongException (String.format("error while creating file: '%s'", filePath)); + } + try { + dataFile.setLength(0); + } catch (IOException e) { + throw new SomethingIsWrongException("Error aqcuired while resizing a file " + e.getMessage()); + } + } + + public void writeKey(String key) throws SomethingIsWrongException { + byte[] bytes = UtilMethods.getBytes(key, UtilMethods.ENCODING); + try { + dataFile.write(bytes); + dataFile.writeByte(0); + } catch (IOException e) { + throw new SomethingIsWrongException("Error acquired while writing to file: " + e.getMessage()); + } + } + + public void writeOffset(int offset) throws SomethingIsWrongException { + try { + dataFile.writeInt(offset); + } catch (IOException e) { + throw new SomethingIsWrongException("Error acquired while writing to file: " + e.getMessage()); + } + } + + public void writeValue(String value) throws SomethingIsWrongException { + try { + byte[] bytes = value.getBytes(UtilMethods.ENCODING); + dataFile.write(bytes); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException("Unrecognized encoding"); + } catch (IOException e) { + throw new SomethingIsWrongException("Error acquired while writing to file: " + e.getMessage()); + } + } + +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java new file mode 100644 index 000000000..9a8e4a545 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java @@ -0,0 +1,24 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; + +public class CreateCommand implements Commands { + public String getCommandName() { + return "create"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String[] args, MultiFileMapShellState state) throws SomethingIsWrongException { + try { + state.tableProvider.createTable(args[0]); + System.out.println("created"); + } catch (Exception e) { + throw new SomethingIsWrongException (e.getMessage()); + } + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java new file mode 100644 index 000000000..7aed7b1d6 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java @@ -0,0 +1,68 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; +import java.io.File; +import java.util.HashMap; + +public class Database implements TableProvider { + HashMap content = new HashMap(); + private String databaseDirectoryPath; + + public Database(String databaseDirectoryPath) { + this.databaseDirectoryPath = databaseDirectoryPath; + File databaseDirectory = new File(databaseDirectoryPath); + //if (databaseDirectory.getUsableSpace() != 0) { + for(File tableFile : databaseDirectory.listFiles()) { + if (tableFile!=null || tableFile.isFile()) { + continue; + } + MultifileTable table = new MultifileTable(databaseDirectoryPath, tableFile.getName()); + content.put(table.getName(), table); + } + //} + } + + public MultifileTable getTable(String name) throws SomethingIsWrongException { + if (name == null) { + throw new SomethingIsWrongException("Table's name cannot be null"); + } + MultifileTable table = content.get(name); + + if (table == null) { + throw new SomethingIsWrongException("Tablename does not exist"); + } + if (table.getChangesCount() > 0) { + throw new SomethingIsWrongException("There are " + table.getChangesCount() + " uncommited changes."); + } + + return table; + } + + public MultifileTable createTable(String name) throws SomethingIsWrongException { + if (name == null) { + throw new IllegalArgumentException("Table's name cannot be null"); + } + if (content.containsKey(name)) { + throw new IllegalStateException("Table already exists"); + } + MultifileTable table = new MultifileTable(databaseDirectoryPath, name); + content.put(name, table); + return table; + } + + public void removeTable(String name) throws SomethingIsWrongException { + if (name == null) { + throw new SomethingIsWrongException("Table's name cannot be null"); + } + + if (!content.containsKey(name)) { + throw new SomethingIsWrongException("Table doesn't exist"); + } + + content.remove(name); + + File tableFile = new File(databaseDirectoryPath, name); + tableFile.delete(); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java new file mode 100644 index 000000000..927f3a606 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java @@ -0,0 +1,14 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + + +import java.io.File; + +public class DatabaseFactory { + public Database create(String directory) { + File databaseDirectory = new File(directory); + if (!databaseDirectory.exists()) { + databaseDirectory.mkdir(); + } + return new Database(databaseDirectory.getAbsolutePath()); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java new file mode 100644 index 000000000..123f3a894 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java @@ -0,0 +1,88 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import ru.fizteh.fivt.storage.strings.*; + +public class DatabaseTest { + + TableProviderFactory factory; + TableProvider provider; + + @Before + public void beforeTest() { + factory = new DatabaseFactory(); + provider = factory.create("C:\\temp\\database_test"); + provider.createTable("table1"); + provider.createTable("table2"); + } + + @Test + public void testCreateTable() throws Exception { + // non-existing tables + Assert.assertNotNull(provider.createTable("newtable1")); + Assert.assertNotNull(provider.createTable("newtable2")); + // existing tables + Assert.assertNull(provider.createTable("table1")); + Assert.assertNull(provider.createTable("table2")); + + // clean-up + provider.removeTable("newtable1"); + provider.removeTable("newtable2"); + } + + @Test + public void testGetTable() throws Exception { + // non-existing tables + Assert.assertNull(provider.getTable("nonexistingtable")); + Assert.assertNull(provider.getTable("thereisnosuchtable")); + // existing tables + Assert.assertNotNull(provider.getTable("table1")); + Assert.assertNotNull(provider.getTable("table2")); + + Table table1 = provider.getTable("table1"); + Assert.assertEquals(table1, provider.getTable("table1")); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetTableExceptions() { + provider.getTable(null); + } + + @Test(expected = IllegalArgumentException.class) + public void testCreateTableExceptions() { + provider.createTable(null); + } + + @Test + public void testRemoveTable() throws Exception { + //prepare + provider.createTable("newtable1"); + provider.createTable("newtable2"); + + // existing tables + provider.removeTable("newtable1"); + provider.removeTable("newtable2"); + } + + @Test(expected = IllegalArgumentException.class) + public void testRemoveTableIllegalArgumentException() { + provider.removeTable(null); + } + + @Test(expected = IllegalStateException.class) + public void testRemoveTableIllegalStateException() { + provider.removeTable("nonexistingtable"); + provider.removeTable("nosuchtable"); + } + + @After + public void testAfter() { + provider.removeTable("table1"); + provider.removeTable("table2"); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java new file mode 100644 index 000000000..357be2b47 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java @@ -0,0 +1,25 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; + + +public class DropCommand implements Commands { + public String getCommandName() { + return "drop"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String[] args, MultiFileMapShellState state) throws SomethingIsWrongException { + try { + state.tableProvider.removeTable(args[0]); + System.out.println("removed"); + } catch (Exception e) { + throw new SomethingIsWrongException (e.getMessage()); + } + } + +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java new file mode 100644 index 000000000..36c19603f --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java @@ -0,0 +1,34 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.io.File; +import java.io.IOException; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.FileMapReadingUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableBuilder; + + +public class MultiFileMapReadingUtils { + public static void load(TableBuilder build) throws IOException { + File tableDir = build.getTableDirectory(); + if (tableDir.listFiles() == null) { + return; + } + + for (File dir : tableDir.listFiles()) { + if(dir.isFile()) { + continue; + } + + if(dir.listFiles().length == 0) { + throw new IllegalArgumentException("empty bucket"); + } + + for(File file : dir.listFiles()) { + build.setCurrentFile(file); + FileMapReadingUtils.scanFromDisk(file.getAbsolutePath(), build); + } + } + + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java new file mode 100644 index 000000000..ae1fa4cac --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java @@ -0,0 +1,7 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; + + +public class MultiFileMapShellState extends FileMapShellState { + public TableProvider tableProvider; +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java new file mode 100644 index 000000000..7399c00aa --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java @@ -0,0 +1,27 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.io.File; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.SimpleTableBuilder; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableUsingStrings; + +public class MultiFileMapTableBuilder extends SimpleTableBuilder { + private int currentDir; + private int currentFile; + + + public MultiFileMapTableBuilder(TableUsingStrings table) { + super(table); + } + + public void setCurrentFile(File file) { + currentDir = GlobalUtils.parseDirNumber(file.getParentFile()); + currentFile = GlobalUtils.parseFileNumber(file); + } + + public void put(String key, String value) { + GlobalUtils.checkKeyPlacement(key, currentDir, currentFile); + super.put(key, value); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java new file mode 100644 index 000000000..7932979a3 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java @@ -0,0 +1,57 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.FileMapWritingUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableBuilder; + +public class MultiFileMapWritingUtils { + + public static void save(TableBuilder build) throws IOException { + File tableDir = build.getTableDirectory(); + if (tableDir.listFiles() == null) { + return; + } + ArrayList> toSave = new ArrayList>(); + boolean dirIsEmpty; + + for (int dirNumber = 0; dirNumber < GlobalUtils.DIR_QUANTITY; ++dirNumber) { + toSave.clear(); + for (int fileNumber = 0; fileNumber < GlobalUtils.FILES_PER_DIR; ++fileNumber) { + toSave.add(new HashSet()); + } + dirIsEmpty = true; + + for (String key : build.getKeys()) { + if (GlobalUtils.getDirNumber(key) == dirNumber) { + int fileNumber = GlobalUtils.getFileNumber(key); + toSave.get(fileNumber).add(key); + dirIsEmpty = false; + } + } + String dirName = dirNumber + ".dir"; + File dir = new File(tableDir, dirName); + if (dirIsEmpty) { + GlobalUtils.deleteFile(dir); + } + for (int fileNumber = 0; fileNumber < GlobalUtils.FILES_PER_DIR; ++fileNumber) { + String fileName = fileNumber + ".dat"; + File file = new File(dir, fileName); + if (toSave.get(fileNumber).isEmpty()) { + GlobalUtils.deleteFile(file); + continue; + } + if (!dir.exists()) { + dir.mkdir(); + } + FileMapWritingUtils.writeOnDisk(toSave.get(fileNumber), + file.getAbsolutePath(), build); + } + } + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java new file mode 100644 index 000000000..ac1a4e9d1 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java @@ -0,0 +1,32 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; + +public class MultifileMapMain { + public static void main(String args[]) { + MultiFileMapShellState state = new MultiFileMapShellState(); + HashSet> com = new HashSet>() {{ add(new ExitCommand()); add(new RollbackCommand()); add(new CommitCommand()); + add(new PutCommand()); add(new GetCommand()); add(new RemoveKeyCommand());}}; + HashSet> com1 = new HashSet>() {{add(new DropCommand()); add(new UseCommand()); + add(new CreateCommand());}}; + ArrayList res = new ArrayList(); + res.addAll(com); + res.addAll(com1); + HashSet actualResult = new HashSet(res); + Shell shell = new Shell(actualResult); + String dbDirectory = System.getProperty("fizteh.db.dir"); + System.out.println(dbDirectory); + DatabaseFactory factory = new DatabaseFactory(); + state.tableProvider = factory.create(dbDirectory); + shell.setShellState(state); + shell.consoleWay(state); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java new file mode 100644 index 000000000..140e5342b --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java @@ -0,0 +1,15 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.io.IOException; + +import ru.fizteh.fivt.students.krivchansky.filemap.FileMapShellStateInterface; + +public interface MultifileMapShellStateInterface extends FileMapShellStateInterface { + public Table useTable(String name); + + public Table createTable(String arguments); + + public void dropTable(String name) throws IOException; + + public String getCurrentTableName(); +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java new file mode 100644 index 000000000..b07edb68d --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java @@ -0,0 +1,99 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +public class MultifileTable extends SomeTable { + + private static final int DIR_QUANTITY = 16; + private static final int FILES_PER_DIR = 16; + + public MultifileTable(String directory, String tableName) { + super(directory, tableName); + } + + protected void save() { + File tableDirectory = getTableDirectory(); + ArrayList> keysToSave = new ArrayList>(); + boolean dirIsEmpty; + for(int dirNumber = 0; dirNumber < DIR_QUANTITY; ++dirNumber) { + keysToSave.clear(); + for(int index = 0; index < FILES_PER_DIR; ++index) { + keysToSave.add(new HashSet()); + } + dirIsEmpty = true; + try { + for(final String key : unchangedOldData.keySet()) { + if (getDirNumber(key) == dirNumber) { + int fileNumber = getFileNumber(key); + keysToSave.get(fileNumber).add(key); + dirIsEmpty = false; + } + } + } catch (SomethingIsWrongException e) { + e.printStackTrace(); + } + String dirName = String.format("%d.dir", dirNumber); + File directory = new File(tableDirectory, dirName); + if (dirIsEmpty) { + directory.delete(); + } + for(int fileNumber = 0; fileNumber < FILES_PER_DIR; ++fileNumber) { + String fileName = String.format("%d.dat", fileNumber); + File file = new File(directory, fileName); + if (keysToSave.get(fileNumber).isEmpty()) { + file.delete(); + continue; + } + if (!directory.exists()) { + directory.mkdir(); + } + try { + writeOnDisk(keysToSave.get(fileNumber), file.getAbsolutePath()); + } catch (SomethingIsWrongException e) { + System.out.println("Error acquired while writing into a table. Message: " + e.getMessage()); + } + } + } + } + + + protected void load() { + File tableDirectory = getTableDirectory(); + for(final File backet: tableDirectory.listFiles()) { + for(final File file: backet.listFiles()) { + try { + scanFromDisk(file.getAbsolutePath()); + } catch (SomethingIsWrongException e) { + System.out.println("Error acquired while reading out of table. Message: " + e.getMessage()); + } + } + } + } + + private File getTableDirectory() { + File curDir = new File(new File(".").getAbsolutePath()); + String temp = curDir.getAbsolutePath(); + File tableDirectory = new File(temp, getName()); + if (!tableDirectory.exists()) { + tableDirectory.mkdir(); + } + return tableDirectory; + } + + private int getDirNumber(String key) throws SomethingIsWrongException { + byte[] bytes = UtilMethods.getBytes(key, UtilMethods.ENCODING); + return bytes[0] % DIR_QUANTITY; + } + + private int getFileNumber(String key) throws SomethingIsWrongException { + byte[] bytes = UtilMethods.getBytes(key, UtilMethods.ENCODING); + return bytes[0] / DIR_QUANTITY % FILES_PER_DIR; + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java new file mode 100644 index 000000000..1c9e64f49 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java @@ -0,0 +1,173 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.util.Random; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import ru.fizteh.fivt.storage.strings.TableProvider; +import ru.fizteh.fivt.storage.strings.TableProviderFactory; +import ru.fizteh.fivt.students.krivchansky.filemap.MyTable; + +public class MultifileTableTest { + + private static final int KEYS_COUNT = 20; + private static final String TABLE_NAME = "testtable"; + MyTable currentTable; + + TableProviderFactory factory = new DatabaseFactory(); + TableProvider provider = factory.create("C:\\temp\\database_test"); + + + @Before + public void gettingReady() throws Exception { + currentTable = (MyTable) provider.createTable(TABLE_NAME); + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String value = String.format("value%d", index); + currentTable.put(key, value); + } + } + + @Test + public void testForNewData() { + // new data + for (int index = 0; index < KEYS_COUNT; ++index) { + String newKey = String.format("new_key%d", index); + String newValue = String.format("new_value%d", index); + Assert.assertNull(currentTable.put(newKey, newValue)); + } + } + + @Test + public void testForExistingData() { + // existing data + for (int index = 0; index < KEYS_COUNT; ++index) { + String expectedValue = String.format("value%d", index); + String key = String.format("key%d", index); + Assert.assertEquals(expectedValue, currentTable.get(key)); + } + } + + @Test + public void testForUnexistingData() { + // non-existing data + Random random = new Random(); + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("k%d", random.nextInt(100)); + Assert.assertNull(currentTable.get(key)); + } + } + + @Test + public void testForReplaceData() { + // replacing + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String oldValue = String.format("value%d", index); + String newValue = String.format("new_value%d", index); + Assert.assertEquals(oldValue, currentTable.put(key, newValue)); + } + } + + @Test + public void testCommit() { + int committed = currentTable.commit(); + Assert.assertEquals(KEYS_COUNT, committed); + + for (int index = 0; index < 2 * KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String value = String.format("value%d", index); + currentTable.put(key, value); + } + + Assert.assertEquals(KEYS_COUNT, currentTable.commit()); + + for (int index = 0; index < 2 * KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + Assert.assertNotNull(currentTable.get(key)); + } + } + + @Test + public void testRollback() { + Assert.assertEquals(KEYS_COUNT, currentTable.rollback()); + + for (int index = 0; index < 2 * KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String value = String.format("value%d", index); + currentTable.put(key, value); + } + + Assert.assertEquals(2 * KEYS_COUNT, currentTable.rollback()); + + for (int index = 0; index < 2 * KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + Assert.assertNull(currentTable.get(key)); + } + } + + @Test + public void testSize() { + Assert.assertEquals(KEYS_COUNT, currentTable.size()); + } + + @Test + public void testGetName() { + Assert.assertEquals(TABLE_NAME, currentTable.getName()); + } + + @Test(expected = IllegalArgumentException.class) + public void testTableExceptions() { + // get + currentTable.get(null); + + // storagePut + currentTable.put(null, "value"); + currentTable.put("key", null); + + // storageRemove + currentTable.remove(null); + } + + @Test + public void testRollbackAndCommit() + { + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String value = String.format("value%d", index); + currentTable.put(key, value); + } + currentTable.commit(); + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + currentTable.remove(key); + } + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String value = String.format("value%d", index); + currentTable.put(key, value); + } + Assert.assertEquals(0, currentTable.rollback()); + + currentTable.remove("non-exists"); + currentTable.remove("non-exists1"); + currentTable.remove("key1"); + currentTable.put("key1", "value1"); + Assert.assertEquals(0, currentTable.rollback()); + + currentTable.put("key1", "value1"); + currentTable.commit(); + currentTable.remove("key1"); + currentTable.put("key1", "value1"); + Assert.assertEquals(0, currentTable.rollback()); + } + + @After + public void cleaningUp() throws Exception { + provider.removeTable(TABLE_NAME); + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProvider.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProvider.java new file mode 100644 index 000000000..6aecaaba0 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProvider.java @@ -0,0 +1,10 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; + +public interface TableProvider { + Table getTable(String a) throws SomethingIsWrongException; + Table createTable(String a) throws SomethingIsWrongException; + void removeTable(String a) throws SomethingIsWrongException; +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProviderFactory.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProviderFactory.java new file mode 100644 index 000000000..68be9f7da --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProviderFactory.java @@ -0,0 +1,5 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +public interface TableProviderFactory { + TableProvider create(String dir); +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java new file mode 100644 index 000000000..1686d0601 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java @@ -0,0 +1,24 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + + + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +public class UseCommand implements Commands { + public String getCommandName() { + return "use"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String[] args, MultiFileMapShellState state) throws SomethingIsWrongException { + MultifileTable oldOne = (MultifileTable) state.table; + state.table = state.tableProvider.getTable(args[0]); + System.out.println("using table " + state.table.getName()); + if (oldOne != null) { + oldOne.commit(); + } + } +} \ No newline at end of file From 458ee80467bb850765e0e2b709d47a9693bb57d6 Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Sun, 12 Oct 2014 00:18:22 +0400 Subject: [PATCH 02/14] Wrong files were added with correct ones --- .../multifilemap/CreateCommand.java | 24 --- .../multifilemap/Database.java | 68 ------- .../multifilemap/DatabaseFactory.java | 14 -- .../multifilemap/DatabaseTest.java | 88 --------- .../multifilemap/DropCommand.java | 25 --- .../MultiFileMapReadingUtils.java | 34 ---- .../multifilemap/MultiFileMapShellState.java | 7 - .../MultiFileMapTableBuilder.java | 27 --- .../MultiFileMapWritingUtils.java | 57 ------ .../multifilemap/MultifileMapMain.java | 32 ---- .../MultifileMapShellStateInterface.java | 15 -- .../multifilemap/MultifileTable.java | 99 ---------- .../multifilemap/MultifileTableTest.java | 173 ------------------ .../multifilemap/TableProvider.java | 10 - .../multifilemap/TableProviderFactory.java | 5 - .../multifilemap/UseCommand.java | 24 --- 16 files changed, 702 deletions(-) delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProvider.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProviderFactory.java delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java deleted file mode 100644 index 9a8e4a545..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java +++ /dev/null @@ -1,24 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; - -public class CreateCommand implements Commands { - public String getCommandName() { - return "create"; - } - - public int getArgumentQuantity() { - return 1; - } - - public void implement(String[] args, MultiFileMapShellState state) throws SomethingIsWrongException { - try { - state.tableProvider.createTable(args[0]); - System.out.println("created"); - } catch (Exception e) { - throw new SomethingIsWrongException (e.getMessage()); - } - } - -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java deleted file mode 100644 index 7aed7b1d6..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java +++ /dev/null @@ -1,68 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; -import java.io.File; -import java.util.HashMap; - -public class Database implements TableProvider { - HashMap content = new HashMap(); - private String databaseDirectoryPath; - - public Database(String databaseDirectoryPath) { - this.databaseDirectoryPath = databaseDirectoryPath; - File databaseDirectory = new File(databaseDirectoryPath); - //if (databaseDirectory.getUsableSpace() != 0) { - for(File tableFile : databaseDirectory.listFiles()) { - if (tableFile!=null || tableFile.isFile()) { - continue; - } - MultifileTable table = new MultifileTable(databaseDirectoryPath, tableFile.getName()); - content.put(table.getName(), table); - } - //} - } - - public MultifileTable getTable(String name) throws SomethingIsWrongException { - if (name == null) { - throw new SomethingIsWrongException("Table's name cannot be null"); - } - MultifileTable table = content.get(name); - - if (table == null) { - throw new SomethingIsWrongException("Tablename does not exist"); - } - if (table.getChangesCount() > 0) { - throw new SomethingIsWrongException("There are " + table.getChangesCount() + " uncommited changes."); - } - - return table; - } - - public MultifileTable createTable(String name) throws SomethingIsWrongException { - if (name == null) { - throw new IllegalArgumentException("Table's name cannot be null"); - } - if (content.containsKey(name)) { - throw new IllegalStateException("Table already exists"); - } - MultifileTable table = new MultifileTable(databaseDirectoryPath, name); - content.put(name, table); - return table; - } - - public void removeTable(String name) throws SomethingIsWrongException { - if (name == null) { - throw new SomethingIsWrongException("Table's name cannot be null"); - } - - if (!content.containsKey(name)) { - throw new SomethingIsWrongException("Table doesn't exist"); - } - - content.remove(name); - - File tableFile = new File(databaseDirectoryPath, name); - tableFile.delete(); - } -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java deleted file mode 100644 index 927f3a606..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java +++ /dev/null @@ -1,14 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - - -import java.io.File; - -public class DatabaseFactory { - public Database create(String directory) { - File databaseDirectory = new File(directory); - if (!databaseDirectory.exists()) { - databaseDirectory.mkdir(); - } - return new Database(databaseDirectory.getAbsolutePath()); - } -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java deleted file mode 100644 index 123f3a894..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import ru.fizteh.fivt.storage.strings.*; - -public class DatabaseTest { - - TableProviderFactory factory; - TableProvider provider; - - @Before - public void beforeTest() { - factory = new DatabaseFactory(); - provider = factory.create("C:\\temp\\database_test"); - provider.createTable("table1"); - provider.createTable("table2"); - } - - @Test - public void testCreateTable() throws Exception { - // non-existing tables - Assert.assertNotNull(provider.createTable("newtable1")); - Assert.assertNotNull(provider.createTable("newtable2")); - // existing tables - Assert.assertNull(provider.createTable("table1")); - Assert.assertNull(provider.createTable("table2")); - - // clean-up - provider.removeTable("newtable1"); - provider.removeTable("newtable2"); - } - - @Test - public void testGetTable() throws Exception { - // non-existing tables - Assert.assertNull(provider.getTable("nonexistingtable")); - Assert.assertNull(provider.getTable("thereisnosuchtable")); - // existing tables - Assert.assertNotNull(provider.getTable("table1")); - Assert.assertNotNull(provider.getTable("table2")); - - Table table1 = provider.getTable("table1"); - Assert.assertEquals(table1, provider.getTable("table1")); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetTableExceptions() { - provider.getTable(null); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateTableExceptions() { - provider.createTable(null); - } - - @Test - public void testRemoveTable() throws Exception { - //prepare - provider.createTable("newtable1"); - provider.createTable("newtable2"); - - // existing tables - provider.removeTable("newtable1"); - provider.removeTable("newtable2"); - } - - @Test(expected = IllegalArgumentException.class) - public void testRemoveTableIllegalArgumentException() { - provider.removeTable(null); - } - - @Test(expected = IllegalStateException.class) - public void testRemoveTableIllegalStateException() { - provider.removeTable("nonexistingtable"); - provider.removeTable("nosuchtable"); - } - - @After - public void testAfter() { - provider.removeTable("table1"); - provider.removeTable("table2"); - } -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java deleted file mode 100644 index 357be2b47..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java +++ /dev/null @@ -1,25 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; - - -public class DropCommand implements Commands { - public String getCommandName() { - return "drop"; - } - - public int getArgumentQuantity() { - return 1; - } - - public void implement(String[] args, MultiFileMapShellState state) throws SomethingIsWrongException { - try { - state.tableProvider.removeTable(args[0]); - System.out.println("removed"); - } catch (Exception e) { - throw new SomethingIsWrongException (e.getMessage()); - } - } - -} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java deleted file mode 100644 index 36c19603f..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java +++ /dev/null @@ -1,34 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -import java.io.File; -import java.io.IOException; - -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.FileMapReadingUtils; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableBuilder; - - -public class MultiFileMapReadingUtils { - public static void load(TableBuilder build) throws IOException { - File tableDir = build.getTableDirectory(); - if (tableDir.listFiles() == null) { - return; - } - - for (File dir : tableDir.listFiles()) { - if(dir.isFile()) { - continue; - } - - if(dir.listFiles().length == 0) { - throw new IllegalArgumentException("empty bucket"); - } - - for(File file : dir.listFiles()) { - build.setCurrentFile(file); - FileMapReadingUtils.scanFromDisk(file.getAbsolutePath(), build); - } - } - - } - -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java deleted file mode 100644 index ae1fa4cac..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java +++ /dev/null @@ -1,7 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; - - -public class MultiFileMapShellState extends FileMapShellState { - public TableProvider tableProvider; -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java deleted file mode 100644 index 7399c00aa..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java +++ /dev/null @@ -1,27 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -import java.io.File; - -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.SimpleTableBuilder; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableUsingStrings; - -public class MultiFileMapTableBuilder extends SimpleTableBuilder { - private int currentDir; - private int currentFile; - - - public MultiFileMapTableBuilder(TableUsingStrings table) { - super(table); - } - - public void setCurrentFile(File file) { - currentDir = GlobalUtils.parseDirNumber(file.getParentFile()); - currentFile = GlobalUtils.parseFileNumber(file); - } - - public void put(String key, String value) { - GlobalUtils.checkKeyPlacement(key, currentDir, currentFile); - super.put(key, value); - } -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java deleted file mode 100644 index 7932979a3..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java +++ /dev/null @@ -1,57 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; - -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.FileMapWritingUtils; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableBuilder; - -public class MultiFileMapWritingUtils { - - public static void save(TableBuilder build) throws IOException { - File tableDir = build.getTableDirectory(); - if (tableDir.listFiles() == null) { - return; - } - ArrayList> toSave = new ArrayList>(); - boolean dirIsEmpty; - - for (int dirNumber = 0; dirNumber < GlobalUtils.DIR_QUANTITY; ++dirNumber) { - toSave.clear(); - for (int fileNumber = 0; fileNumber < GlobalUtils.FILES_PER_DIR; ++fileNumber) { - toSave.add(new HashSet()); - } - dirIsEmpty = true; - - for (String key : build.getKeys()) { - if (GlobalUtils.getDirNumber(key) == dirNumber) { - int fileNumber = GlobalUtils.getFileNumber(key); - toSave.get(fileNumber).add(key); - dirIsEmpty = false; - } - } - String dirName = dirNumber + ".dir"; - File dir = new File(tableDir, dirName); - if (dirIsEmpty) { - GlobalUtils.deleteFile(dir); - } - for (int fileNumber = 0; fileNumber < GlobalUtils.FILES_PER_DIR; ++fileNumber) { - String fileName = fileNumber + ".dat"; - File file = new File(dir, fileName); - if (toSave.get(fileNumber).isEmpty()) { - GlobalUtils.deleteFile(file); - continue; - } - if (!dir.exists()) { - dir.mkdir(); - } - FileMapWritingUtils.writeOnDisk(toSave.get(fileNumber), - file.getAbsolutePath(), build); - } - } - } -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java deleted file mode 100644 index ac1a4e9d1..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java +++ /dev/null @@ -1,32 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; - -public class MultifileMapMain { - public static void main(String args[]) { - MultiFileMapShellState state = new MultiFileMapShellState(); - HashSet> com = new HashSet>() {{ add(new ExitCommand()); add(new RollbackCommand()); add(new CommitCommand()); - add(new PutCommand()); add(new GetCommand()); add(new RemoveKeyCommand());}}; - HashSet> com1 = new HashSet>() {{add(new DropCommand()); add(new UseCommand()); - add(new CreateCommand());}}; - ArrayList res = new ArrayList(); - res.addAll(com); - res.addAll(com1); - HashSet actualResult = new HashSet(res); - Shell shell = new Shell(actualResult); - String dbDirectory = System.getProperty("fizteh.db.dir"); - System.out.println(dbDirectory); - DatabaseFactory factory = new DatabaseFactory(); - state.tableProvider = factory.create(dbDirectory); - shell.setShellState(state); - shell.consoleWay(state); - } -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java deleted file mode 100644 index 140e5342b..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java +++ /dev/null @@ -1,15 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -import java.io.IOException; - -import ru.fizteh.fivt.students.krivchansky.filemap.FileMapShellStateInterface; - -public interface MultifileMapShellStateInterface extends FileMapShellStateInterface { - public Table useTable(String name); - - public Table createTable(String arguments); - - public void dropTable(String name) throws IOException; - - public String getCurrentTableName(); -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java deleted file mode 100644 index b07edb68d..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java +++ /dev/null @@ -1,99 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; - -public class MultifileTable extends SomeTable { - - private static final int DIR_QUANTITY = 16; - private static final int FILES_PER_DIR = 16; - - public MultifileTable(String directory, String tableName) { - super(directory, tableName); - } - - protected void save() { - File tableDirectory = getTableDirectory(); - ArrayList> keysToSave = new ArrayList>(); - boolean dirIsEmpty; - for(int dirNumber = 0; dirNumber < DIR_QUANTITY; ++dirNumber) { - keysToSave.clear(); - for(int index = 0; index < FILES_PER_DIR; ++index) { - keysToSave.add(new HashSet()); - } - dirIsEmpty = true; - try { - for(final String key : unchangedOldData.keySet()) { - if (getDirNumber(key) == dirNumber) { - int fileNumber = getFileNumber(key); - keysToSave.get(fileNumber).add(key); - dirIsEmpty = false; - } - } - } catch (SomethingIsWrongException e) { - e.printStackTrace(); - } - String dirName = String.format("%d.dir", dirNumber); - File directory = new File(tableDirectory, dirName); - if (dirIsEmpty) { - directory.delete(); - } - for(int fileNumber = 0; fileNumber < FILES_PER_DIR; ++fileNumber) { - String fileName = String.format("%d.dat", fileNumber); - File file = new File(directory, fileName); - if (keysToSave.get(fileNumber).isEmpty()) { - file.delete(); - continue; - } - if (!directory.exists()) { - directory.mkdir(); - } - try { - writeOnDisk(keysToSave.get(fileNumber), file.getAbsolutePath()); - } catch (SomethingIsWrongException e) { - System.out.println("Error acquired while writing into a table. Message: " + e.getMessage()); - } - } - } - } - - - protected void load() { - File tableDirectory = getTableDirectory(); - for(final File backet: tableDirectory.listFiles()) { - for(final File file: backet.listFiles()) { - try { - scanFromDisk(file.getAbsolutePath()); - } catch (SomethingIsWrongException e) { - System.out.println("Error acquired while reading out of table. Message: " + e.getMessage()); - } - } - } - } - - private File getTableDirectory() { - File curDir = new File(new File(".").getAbsolutePath()); - String temp = curDir.getAbsolutePath(); - File tableDirectory = new File(temp, getName()); - if (!tableDirectory.exists()) { - tableDirectory.mkdir(); - } - return tableDirectory; - } - - private int getDirNumber(String key) throws SomethingIsWrongException { - byte[] bytes = UtilMethods.getBytes(key, UtilMethods.ENCODING); - return bytes[0] % DIR_QUANTITY; - } - - private int getFileNumber(String key) throws SomethingIsWrongException { - byte[] bytes = UtilMethods.getBytes(key, UtilMethods.ENCODING); - return bytes[0] / DIR_QUANTITY % FILES_PER_DIR; - } -} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java deleted file mode 100644 index 1c9e64f49..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java +++ /dev/null @@ -1,173 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -import java.util.Random; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import ru.fizteh.fivt.storage.strings.TableProvider; -import ru.fizteh.fivt.storage.strings.TableProviderFactory; -import ru.fizteh.fivt.students.krivchansky.filemap.MyTable; - -public class MultifileTableTest { - - private static final int KEYS_COUNT = 20; - private static final String TABLE_NAME = "testtable"; - MyTable currentTable; - - TableProviderFactory factory = new DatabaseFactory(); - TableProvider provider = factory.create("C:\\temp\\database_test"); - - - @Before - public void gettingReady() throws Exception { - currentTable = (MyTable) provider.createTable(TABLE_NAME); - for (int index = 0; index < KEYS_COUNT; ++index) { - String key = String.format("key%d", index); - String value = String.format("value%d", index); - currentTable.put(key, value); - } - } - - @Test - public void testForNewData() { - // new data - for (int index = 0; index < KEYS_COUNT; ++index) { - String newKey = String.format("new_key%d", index); - String newValue = String.format("new_value%d", index); - Assert.assertNull(currentTable.put(newKey, newValue)); - } - } - - @Test - public void testForExistingData() { - // existing data - for (int index = 0; index < KEYS_COUNT; ++index) { - String expectedValue = String.format("value%d", index); - String key = String.format("key%d", index); - Assert.assertEquals(expectedValue, currentTable.get(key)); - } - } - - @Test - public void testForUnexistingData() { - // non-existing data - Random random = new Random(); - for (int index = 0; index < KEYS_COUNT; ++index) { - String key = String.format("k%d", random.nextInt(100)); - Assert.assertNull(currentTable.get(key)); - } - } - - @Test - public void testForReplaceData() { - // replacing - for (int index = 0; index < KEYS_COUNT; ++index) { - String key = String.format("key%d", index); - String oldValue = String.format("value%d", index); - String newValue = String.format("new_value%d", index); - Assert.assertEquals(oldValue, currentTable.put(key, newValue)); - } - } - - @Test - public void testCommit() { - int committed = currentTable.commit(); - Assert.assertEquals(KEYS_COUNT, committed); - - for (int index = 0; index < 2 * KEYS_COUNT; ++index) { - String key = String.format("key%d", index); - String value = String.format("value%d", index); - currentTable.put(key, value); - } - - Assert.assertEquals(KEYS_COUNT, currentTable.commit()); - - for (int index = 0; index < 2 * KEYS_COUNT; ++index) { - String key = String.format("key%d", index); - Assert.assertNotNull(currentTable.get(key)); - } - } - - @Test - public void testRollback() { - Assert.assertEquals(KEYS_COUNT, currentTable.rollback()); - - for (int index = 0; index < 2 * KEYS_COUNT; ++index) { - String key = String.format("key%d", index); - String value = String.format("value%d", index); - currentTable.put(key, value); - } - - Assert.assertEquals(2 * KEYS_COUNT, currentTable.rollback()); - - for (int index = 0; index < 2 * KEYS_COUNT; ++index) { - String key = String.format("key%d", index); - Assert.assertNull(currentTable.get(key)); - } - } - - @Test - public void testSize() { - Assert.assertEquals(KEYS_COUNT, currentTable.size()); - } - - @Test - public void testGetName() { - Assert.assertEquals(TABLE_NAME, currentTable.getName()); - } - - @Test(expected = IllegalArgumentException.class) - public void testTableExceptions() { - // get - currentTable.get(null); - - // storagePut - currentTable.put(null, "value"); - currentTable.put("key", null); - - // storageRemove - currentTable.remove(null); - } - - @Test - public void testRollbackAndCommit() - { - for (int index = 0; index < KEYS_COUNT; ++index) { - String key = String.format("key%d", index); - String value = String.format("value%d", index); - currentTable.put(key, value); - } - currentTable.commit(); - for (int index = 0; index < KEYS_COUNT; ++index) { - String key = String.format("key%d", index); - currentTable.remove(key); - } - for (int index = 0; index < KEYS_COUNT; ++index) { - String key = String.format("key%d", index); - String value = String.format("value%d", index); - currentTable.put(key, value); - } - Assert.assertEquals(0, currentTable.rollback()); - - currentTable.remove("non-exists"); - currentTable.remove("non-exists1"); - currentTable.remove("key1"); - currentTable.put("key1", "value1"); - Assert.assertEquals(0, currentTable.rollback()); - - currentTable.put("key1", "value1"); - currentTable.commit(); - currentTable.remove("key1"); - currentTable.put("key1", "value1"); - Assert.assertEquals(0, currentTable.rollback()); - } - - @After - public void cleaningUp() throws Exception { - provider.removeTable(TABLE_NAME); - } - -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProvider.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProvider.java deleted file mode 100644 index 6aecaaba0..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProvider.java +++ /dev/null @@ -1,10 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.*; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; - -public interface TableProvider { - Table getTable(String a) throws SomethingIsWrongException; - Table createTable(String a) throws SomethingIsWrongException; - void removeTable(String a) throws SomethingIsWrongException; -} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProviderFactory.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProviderFactory.java deleted file mode 100644 index 68be9f7da..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/TableProviderFactory.java +++ /dev/null @@ -1,5 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - -public interface TableProviderFactory { - TableProvider create(String dir); -} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java deleted file mode 100644 index 1686d0601..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java +++ /dev/null @@ -1,24 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; - - - -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; - -public class UseCommand implements Commands { - public String getCommandName() { - return "use"; - } - - public int getArgumentQuantity() { - return 1; - } - - public void implement(String[] args, MultiFileMapShellState state) throws SomethingIsWrongException { - MultifileTable oldOne = (MultifileTable) state.table; - state.table = state.tableProvider.getTable(args[0]); - System.out.println("using table " + state.table.getName()); - if (oldOne != null) { - oldOne.commit(); - } - } -} \ No newline at end of file From 7374d87d10a723bcb6198b8b6a273d5ca29228eb Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Sun, 12 Oct 2014 00:53:52 +0400 Subject: [PATCH 03/14] Checkstyle --- .../NikolaiKrivchanskii/Shell/Commands.java | 6 +-- .../NikolaiKrivchanskii/Shell/Parser.java | 12 +++--- .../NikolaiKrivchanskii/Shell/Shell.java | 32 +++++++------- .../NikolaiKrivchanskii/Shell/ShellState.java | 2 +- .../Shell/UtilMethods.java | 16 +++---- .../filemap/CommitCommand.java | 4 +- .../filemap/ExitCommand.java | 14 +++---- .../filemap/FileMapMain.java | 9 ++-- .../filemap/FileMapReadingUtils.java | 12 +++--- .../filemap/FileMapShellState.java | 4 +- .../filemap/FileMapShellStateInterface.java | 42 +++++++++---------- .../filemap/FileMapWritingUtils.java | 13 +++--- .../filemap/GetCommand.java | 7 ++-- .../filemap/GlobalUtils.java | 25 +++++------ .../NikolaiKrivchanskii/filemap/MyTable.java | 20 ++++----- .../filemap/PutCommand.java | 7 ++-- .../filemap/ReadingUtils.java | 8 ++-- .../filemap/RemoveKeyCommand.java | 1 - .../filemap/RollbackCommand.java | 2 +- .../filemap/SingleFileTable.java | 16 +++---- .../filemap/SizeCommand.java | 29 ++++++------- .../filemap/SomeTable.java | 13 +++--- .../NikolaiKrivchanskii/filemap/Table.java | 16 +++---- .../filemap/TableBuilder.java | 10 ++--- .../filemap/WritingUtils.java | 7 ++-- 25 files changed, 162 insertions(+), 165 deletions(-) diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java index 0285523d1..f415dab67 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java @@ -3,9 +3,9 @@ public interface Commands { - public String getCommandName(); + String getCommandName(); - public int getArgumentQuantity(); + int getArgumentQuantity(); - abstract public void implement(String[] args, State state) throws SomethingIsWrongException; + void implement(String[] args, State state) throws SomethingIsWrongException; } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Parser.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Parser.java index cc3c5c144..294da1161 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Parser.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Parser.java @@ -5,9 +5,9 @@ import java.util.regex.Pattern; public class Parser { - - - public static ArrayList parseCommandArgs(String params) { + + + public static ArrayList parseCommandArgs(String params) { ArrayList matchList = new ArrayList(); Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'"); Matcher regexMatcher = regex.matcher(params); @@ -17,8 +17,8 @@ public static ArrayList parseCommandArgs(String params) { } return matchList; } - - public static String getName(String command) { + + public static String getName(String command) { int spiltIndex = command.indexOf(' '); if (spiltIndex == -1) { return command; @@ -27,7 +27,7 @@ public static String getName(String command) { } } - public static String[] parseFullCommand(String commands) { + public static String[] parseFullCommand(String commands) { String[] commandArray = commands.split(";"); for (int i = 0; i < commandArray.length; ++i) { commandArray[i] = commandArray[i].trim(); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java index 34b2e7ab9..8d8059c76 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java @@ -3,7 +3,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; @@ -11,12 +10,12 @@ public class Shell { private final Map availableCommands; - private static final String greeting = "$ "; + private static final String GREETING = "$ "; State state; - public Shell (Set commands) { - Map tempCommands = new HashMap(); + public Shell(Set commands) { + Map tempCommands = new HashMap(); for (Commands temp : commands) { tempCommands.put(temp.getCommandName(), temp); } @@ -29,16 +28,18 @@ public void setShellState(State state) { private void runCommand(String[] data, State state) throws SomethingIsWrongException { if (data[0].length() == 0) { - throw new SomethingIsWrongException ("Empty string."); + throw new SomethingIsWrongException("Empty string."); } Commands usedOne = availableCommands.get(data[0]); if (usedOne == null) { - throw new SomethingIsWrongException ("Unknown command."); - } else if (data.length - 1 != usedOne.getArgumentQuantity() ) { - if(!(usedOne.getCommandName().equals("rm") && data.length - 1 == usedOne.getArgumentQuantity() + 1) - && !(usedOne.getCommandName().equals("cp") && data.length - 1 == usedOne.getArgumentQuantity() + 1)) { - throw new SomethingIsWrongException ("Wrong number of arguments. Correct argument quantity = " + (data.length-1) + - "\nTo correctly run this command use " + usedOne.getArgumentQuantity() + " arguments."); + throw new SomethingIsWrongException("Unknown command."); + } else if (data.length - 1 != usedOne.getArgumentQuantity()) { + if (!(usedOne.getCommandName().equals("rm") && data.length - 1 == usedOne.getArgumentQuantity() + 1) + && !(usedOne.getCommandName().equals("cp") && data.length - 1 == + usedOne.getArgumentQuantity() + 1)) { + throw new SomethingIsWrongException("Wrong number of arguments. Correct argument quantity = " + + (data.length - 1) + "\nTo correctly run this command use " + + usedOne.getArgumentQuantity() + " arguments."); } } String[] commandArguments = Arrays.copyOfRange(data, 1, data.length); @@ -68,7 +69,7 @@ private void runLine(String line, State state) throws SomethingIsWrongException public void consoleWay(State state) { Scanner forInput = new Scanner(System.in); while (!Thread.currentThread().isInterrupted()) { - System.out.print(greeting); + System.out.print(GREETING); try { runLine(forInput.nextLine(), state); } catch (SomethingIsWrongException exc) { @@ -85,8 +86,10 @@ public void consoleWay(State state) { /* public static void notmain(String[] args) { ShellState state = new ShellState(System.getProperty("user.dir")); - Set commands = new HashSet() {{ /*add(new WhereAreWeCommand()); add(new CopyCommand()); add(new DirectoryInfoCommand()); - add(new ExitCommand()); add(new MakeDirectoryCommand()); add(new MoveCommand()); add(new RemoveCommand()); }};*/ + Set commands = new HashSet() {{ + /*add(new WhereAreWeCommand()); add(new CopyCommand()); add(new DirectoryInfoCommand()); + add(new ExitCommand()); add(new MakeDirectoryCommand()); + add(new MoveCommand()); add(new RemoveCommand()); }};*/ /* Shell shell = new Shell(commands); if (args.length != 0) { @@ -110,3 +113,4 @@ public void consoleWay(State state) { } + diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/ShellState.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/ShellState.java index 51e8abbc3..893f4b1c2 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/ShellState.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/ShellState.java @@ -11,4 +11,4 @@ public String getCurDir() { void changeCurDir(String newCurDir) { currentDirectory = newCurDir; } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/UtilMethods.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/UtilMethods.java index c37a18629..d40ecdaf8 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/UtilMethods.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/UtilMethods.java @@ -11,12 +11,12 @@ import java.util.Collection; public class UtilMethods { - public static final String ENCODING = "UTF-8"; + public static final String ENCODING = "UTF-8"; public static String uniteItems(Collection items, String separator) { boolean isFirstIteration = true; StringBuilder joinBuilder = new StringBuilder(); for (Object item: items) { - if(isFirstIteration) { + if (isFirstIteration) { isFirstIteration = false; } else { joinBuilder.append(separator); @@ -46,14 +46,14 @@ public static void copyFile(File source, File dirDestination) throws SomethingIs ofCopy = new FileOutputStream(copy); byte[] buf = new byte[4096]; //size of reading = 4kB int read = ofOriginal.read(buf); - while(read > 0) { + while (read > 0) { ofCopy.write(buf, 0, read); read = ofOriginal.read(buf); } } catch (FileNotFoundException e) { - throw new SomethingIsWrongException ("This file or directory doesn't exist yet. " + e.getMessage()); + throw new SomethingIsWrongException("This file or directory doesn't exist yet. " + e.getMessage()); } catch (IOException e) { - throw new SomethingIsWrongException ("Error while writing/reading file. " + e.getMessage()); + throw new SomethingIsWrongException("Error while writing/reading file. " + e.getMessage()); } finally { closeCalm(ofOriginal); closeCalm(ofCopy); @@ -63,7 +63,7 @@ public static void copyFile(File source, File dirDestination) throws SomethingIs public static File getAbsoluteName(String fileName, ShellState state) { File file = new File(fileName); - if (!file.isAbsolute()){ + if (!file.isAbsolute()) { file = new File(state.getCurDir(), fileName); } return file; @@ -93,8 +93,8 @@ public static int countBytes(String string, String encoding) { try { byte[] bytes = string.getBytes(encoding); return bytes.length; - } catch(Exception e) { + } catch (Exception e) { return 0; } } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java index d57e63661..7f02aa5af 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java @@ -2,7 +2,7 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; -public class CommitCommand implements Commands{ +public class CommitCommand implements Commands { public String getCommandName() { return "commit"; @@ -15,7 +15,7 @@ public int getArgumentQuantity() { public void implement(String[] args, FileMapShellState state) throws SomethingIsWrongException { if (state.table == null) { - throw new SomethingIsWrongException ("Table not found."); + throw new SomethingIsWrongException("Table not found."); } state.table.commit(); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java index 84965470f..078bdbaf9 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java @@ -12,13 +12,13 @@ public int getArgumentQuantity() { return 0; } public void implement(String[] args, FileMapShellState state) throws SomethingIsWrongException { - MyTable temp = (MyTable) state.table; - if (state.table != null && !temp.getAutoCommit()) { - temp.rollback(); - } else if (temp.getAutoCommit() && state.table != null) { - temp.commit(); - } + MyTable temp = (MyTable) state.table; + if (state.table != null && !temp.getAutoCommit()) { + temp.rollback(); + } else if (temp.getAutoCommit() && state.table != null) { + temp.commit(); + } throw new SomethingIsWrongException("EXIT"); } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java index 402513438..25d3e3bb1 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java @@ -8,13 +8,14 @@ public class FileMapMain { public static void main(String[] args) { - FileMapShellState state = new FileMapShellState(); - Set com = new HashSet() {{ add(new ExitCommand()); add(new RollbackCommand()); add(new CommitCommand()); - add(new PutCommand()); add(new GetCommand()); add(new RemoveKeyCommand());}}; + FileMapShellState state = new FileMapShellState(); + Set com = new HashSet() { { add(new ExitCommand()); + add(new RollbackCommand()); add(new CommitCommand()); + add(new PutCommand()); add(new GetCommand()); add(new RemoveKeyCommand()); }}; Shell shell = new Shell(com); String dbDirectory = System.getProperty("fizteh.db.dir"); state.table = new SingleFileTable(dbDirectory, "master"); shell.setShellState(state); shell.consoleWay(state); } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapReadingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapReadingUtils.java index 31f88128a..2b67222c6 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapReadingUtils.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapReadingUtils.java @@ -35,7 +35,7 @@ public String readKey() throws IOException { } ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte b = tempFile.readByte(); - while(b != 0) { + while (b != 0) { bytes.write(b); b = tempFile.readByte(); } @@ -48,7 +48,7 @@ public String readValue() throws IOException { long currentOffset; currentOffset = tempFile.getFilePointer(); tempFile.seek(offset); - int valueLength = nextOffset-offset; + int valueLength = nextOffset - offset; byte[] bytes = new byte[valueLength]; tempFile.read(bytes, 0, valueLength); tempFile.seek(currentOffset); @@ -77,7 +77,7 @@ public boolean endOfFile() throws IOException { try { result = (tempFile.getFilePointer() == valueShift); } catch (EOFException e) { - + System.err.println("Reached end of file"); } return result; } @@ -87,7 +87,7 @@ private int readNextOffset() throws IOException { int nextOffset = 0; long currentOffset = tempFile.getFilePointer(); if (readKey() == null) { - nextOffset = (int)tempFile.length(); + nextOffset = (int) tempFile.length(); } else { nextOffset = readOffset(); } @@ -106,7 +106,7 @@ private int readOffset() throws IOException { return tempFile.readInt(); } - public void close () { - GlobalUtils.closeCalm(tempFile); + public void close() { + GlobalUtils.closeCalm(tempFile); } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java index 9cd0ba04d..9b8d1d354 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java @@ -2,5 +2,5 @@ public class FileMapShellState { - public Table table = null; - } \ No newline at end of file + public Table table = null; + } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java index 1697958d4..398ffbd87 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java @@ -2,25 +2,25 @@ public interface FileMapShellStateInterface { - public Value put (Key key, Value value); - - public Value get (Key key); - - public int commit(); - - public int rollback(); - - public int size(); - - public Value remove(Key key); - - public Table getTable(); - - public String keyToString(Key key); - - public String valueToString(Value value); - - public Key parseKey(String key); - - public Value parseValue(String value); + Value put(Key key, Value value); + + Value get(Key key); + + int commit(); + + int rollback(); + + int size(); + + Value remove(Key key); + + Table getTable(); + + String keyToString(Key key); + + String valueToString(Value value); + + Key parseKey(String key); + + Value parseValue(String value); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapWritingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapWritingUtils.java index 32b314377..5d46c5022 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapWritingUtils.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapWritingUtils.java @@ -15,8 +15,7 @@ public class FileMapWritingUtils implements Closeable { public FileMapWritingUtils(String filePath) throws IOException { try { dataFile = new RandomAccessFile(filePath, "rw"); - } - catch (FileNotFoundException e) { + } catch (FileNotFoundException e) { throw new IOException(String.format("error while creating file: '%s'", filePath)); } try { @@ -36,12 +35,12 @@ public static void writeOnDisk(Set keys, String file, TableBuilder build FileMapWritingUtils write = new FileMapWritingUtils(file); int shift = GlobalUtils.getKeysLength(keys, GlobalUtils.ENCODING); for (String key : keys) { - write.writeKey(key); - write.writeOffset(shift); - shift += GlobalUtils.countBytes(builder.get(key), GlobalUtils.ENCODING); + write.writeKey(key); + write.writeOffset(shift); + shift += GlobalUtils.countBytes(builder.get(key), GlobalUtils.ENCODING); } for (String key : keys) { - write.writeValue(builder.get(key)); + write.writeValue(builder.get(key)); } write.close(); } @@ -63,4 +62,4 @@ public void close() { GlobalUtils.closeCalm(dataFile); } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java index 9e706382c..4cd5570f3 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java @@ -1,9 +1,8 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import java.util.ArrayList; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; -public class GetCommand implements Commands{ +public class GetCommand implements Commands { public String getCommandName() { return "get"; @@ -15,8 +14,8 @@ public int getArgumentQuantity() { public void implement(String[] args, FileMapShellState state) throws SomethingIsWrongException { - if(state.table == null) { - throw new SomethingIsWrongException ("Table not found."); + if (state.table == null) { + throw new SomethingIsWrongException("Table not found."); } String value = state.table.get(args[0]); if (value == null) { diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GlobalUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GlobalUtils.java index 236b87a55..e534b10b9 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GlobalUtils.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GlobalUtils.java @@ -13,17 +13,17 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.ShellState; public class GlobalUtils { - public static final Charset ENCODING = StandardCharsets.UTF_8; - public static final int DIR_QUANTITY = 16; + public static final Charset ENCODING = StandardCharsets.UTF_8; + public static final int DIR_QUANTITY = 16; public static final int FILES_PER_DIR = 16; - private static final Pattern DIR_PATTERN = Pattern.compile("([^\\.]+).dir"); + private static final Pattern DIR_PATTERN = Pattern.compile("([^\\.]+).dir"); private static final Pattern FILE_PATTERN = Pattern.compile("([^\\.]+).dat"); - + public static String uniteItems(Collection items, String separator) { boolean isFirstIteration = true; StringBuilder joinBuilder = new StringBuilder(); for (Object item: items) { - if(isFirstIteration) { + if (isFirstIteration) { isFirstIteration = false; } else { joinBuilder.append(separator); @@ -46,7 +46,7 @@ public static void closeCalm(Closeable something) { public static File getAbsoluteName(String fileName, ShellState state) { File file = new File(fileName); - if (!file.isAbsolute()){ + if (!file.isAbsolute()) { file = new File(state.getCurDir(), fileName); } return file; @@ -88,7 +88,7 @@ public static boolean compare(Object key1, Object key2) { } else if (key1 == null || key2 == null) { return false; } else { - return key1.equals(key2); + return key1.equals(key2); } } @@ -122,18 +122,15 @@ public static int parseFileNumber(File file) { throw new IllegalArgumentException("incorrect file name"); } - public static void checkKeyPlacement(String key, int currentDir, int currentFile) - { + public static void checkKeyPlacement(String key, int currentDir, int currentFile) { if (currentDir != getDirNumber(key) || currentFile != getFileNumber(key)) { throw new IllegalArgumentException("invalid key placement"); } } - public static String parseTableName(String params) - { + public static String parseTableName(String params) { int index = params.indexOf(' '); - if (index == -1) - { + if (index == -1) { return params; } return params.substring(0, index); @@ -149,4 +146,4 @@ public static int getFileNumber(String key) { return Math.abs(bytes[0] / DIR_QUANTITY % FILES_PER_DIR); } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java index ae2354d1a..0d0b57268 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java @@ -2,14 +2,14 @@ public interface MyTable extends Table { - String getName(); - void setAutoCommit(boolean status); - boolean getAutoCommit(); - int getChangesCounter(); - String get(String a); - String put(String key, String value); - String remove(String a); - int size(); - int commit(); - int rollback(); + String getName(); + void setAutoCommit(boolean status); + boolean getAutoCommit(); + int getChangesCounter(); + String get(String a); + String put(String key, String value); + String remove(String a); + int size(); + int commit(); + int rollback(); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java index 98ba4c4f8..bd00504ae 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java @@ -1,5 +1,4 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import java.util.ArrayList; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; @@ -15,9 +14,9 @@ public int getArgumentQuantity() { public void implement(String[] args, FileMapShellState state) throws SomethingIsWrongException { - if (state.table == null) { - throw new SomethingIsWrongException("No table chosen"); - } + if (state.table == null) { + throw new SomethingIsWrongException("No table chosen"); + } String temp = state.table.put(args[0], args[1]); if (temp != null) { System.out.println("overwrite\n" + temp); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java index 4836869f6..d447189d4 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java @@ -40,7 +40,7 @@ public String readKey() throws SomethingIsWrongException { } ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte b = tempFile.readByte(); - while(b != 0) { + while (b != 0) { bytes.write(b); b = tempFile.readByte(); } @@ -64,7 +64,7 @@ public String readValue() throws SomethingIsWrongException { try { currentOffset = tempFile.getFilePointer(); tempFile.seek(offset); - int valueLength = nextOffset-offset; + int valueLength = nextOffset - offset; byte[] bytes = new byte[valueLength]; tempFile.read(bytes, 0, valueLength); tempFile.seek(currentOffset); @@ -99,7 +99,7 @@ private int readNextOffset() throws SomethingIsWrongException { try { int currentOffset = (int) tempFile.getFilePointer(); if (readKey() == null) { - nextOffset = (int)tempFile.length(); + nextOffset = (int) tempFile.length(); } else { nextOffset = readOffset(); } @@ -134,4 +134,4 @@ private int readOffset() throws SomethingIsWrongException { throw new SomethingIsWrongException("Error aqcuired while reading a file " + e.getMessage()); } } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java index 6e0a70010..5ff887040 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java @@ -1,5 +1,4 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import java.util.ArrayList; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Commands; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java index f14d29f1a..1d638f696 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java @@ -15,7 +15,7 @@ public int getArgumentQuantity() { public void implement(String[] args, FileMapShellState state) throws SomethingIsWrongException { if (state.table == null) { - throw new SomethingIsWrongException ("No table chosen"); + throw new SomethingIsWrongException("No table chosen"); } state.table.rollback(); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java index 0683adead..961393f60 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java @@ -24,15 +24,15 @@ protected void save() throws SomethingIsWrongException { } private String getPathToDatabase() { - File curDir = new File(new File(".").getAbsolutePath()); + File curDir = new File(new File(".").getAbsolutePath()); File databaseFile; - try { - databaseFile = new File (curDir.getCanonicalPath(), DATABASENAME); - return databaseFile.getAbsolutePath(); - } catch (IOException e) { - e.getMessage(); - } - return ""; + try { + databaseFile = new File(curDir.getCanonicalPath(), DATABASENAME); + return databaseFile.getAbsolutePath(); + } catch (IOException e) { + e.getMessage(); + } + return ""; } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java index 17965d6e6..58cebe458 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java @@ -4,22 +4,23 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; -public class SizeCommand> extends SomeCommand { +public class SizeCommand> extends SomeCommand { - public String getCommandName() { - return "size"; - } + public String getCommandName() { + return "size"; + } - public int getArgumentQuantity() { - return 0; - } + public int getArgumentQuantity() { + return 0; + } - public void implement(String[] args, State state) - throws SomethingIsWrongException { - if (state.getTable() == null) { - throw new SomethingIsWrongException("no table"); - } - System.out.println(state.size()); - } + public void implement(String[] args, State state) + throws SomethingIsWrongException { + if (state.getTable() == null) { + throw new SomethingIsWrongException("no table"); + } + System.out.println(state.size()); + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java index 6e6175e71..8e8c6e072 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java @@ -2,8 +2,7 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; -import java.io.File; -import java.io.IOException; + import java.util.HashMap; import java.util.HashSet; import java.util.Set; @@ -73,9 +72,9 @@ public String get(String key) { return unchangedOldData.get(key); } - public String put(String key, String Value) { + public String put(String key, String newValue) { String value = oldValue(key); - currentData.put(key, Value); + currentData.put(key, newValue); if (value == null) { ++size; } @@ -119,12 +118,12 @@ private int keySize(Set keys) { public void writeOnDisk(Set keys, String file) throws SomethingIsWrongException { WritingUtils write = new WritingUtils(file); int temp = keySize(keys); - for(String key : keys) { + for (String key : keys) { write.writeKey(key); write.writeOffset(temp); temp += UtilMethods.countBytes(unchangedOldData.get(key), UtilMethods.ENCODING); } - for(String key : keys) { + for (String key : keys) { String tempCheck = unchangedOldData.get(key); if (tempCheck != null) { write.writeValue(tempCheck); @@ -138,7 +137,7 @@ public void scanFromDisk(String file) throws SomethingIsWrongException { throw new SomethingIsWrongException("Unable to scan from disc."); } ReadingUtils read = new ReadingUtils(file); - while(!read.endOfFile()) { + while (!read.endOfFile()) { String key = read.readKey(); String value = read.readValue(); unchangedOldData.put(key, value); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java index 819a12d49..ffccedda7 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java @@ -1,11 +1,11 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; public interface Table { - String getName(); - String get(String a); - String put(String a, String b); - String remove(String a); - int size(); - int commit(); - int rollback(); -} \ No newline at end of file + String getName(); + String get(String a); + String put(String a, String b); + String remove(String a); + int size(); + int commit(); + int rollback(); +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableBuilder.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableBuilder.java index 260f91bf4..d2aab8f10 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableBuilder.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableBuilder.java @@ -4,13 +4,13 @@ import java.util.Set; public interface TableBuilder { - public String get(String key); + String get(String key); - public void put(String key, String value); + void put(String key, String value); - public Set getKeys(); + Set getKeys(); - public File getTableDirectory(); + File getTableDirectory(); - public void setCurrentFile(File currentFile); + void setCurrentFile(File currentFile); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/WritingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/WritingUtils.java index 4bfd33ab8..64fbb5e57 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/WritingUtils.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/WritingUtils.java @@ -16,9 +16,8 @@ public class WritingUtils { public WritingUtils(String filePath) throws SomethingIsWrongException { try { dataFile = new RandomAccessFile(filePath, "rw"); - } - catch (FileNotFoundException e) { - throw new SomethingIsWrongException (String.format("error while creating file: '%s'", filePath)); + } catch (FileNotFoundException e) { + throw new SomethingIsWrongException(String.format("error while creating file: '%s'", filePath)); } try { dataFile.setLength(0); @@ -56,4 +55,4 @@ public void writeValue(String value) throws SomethingIsWrongException { } } -} \ No newline at end of file +} From 6fef3f58e8d607c744359cbef8be0303c949fe81 Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Sun, 12 Oct 2014 00:58:30 +0400 Subject: [PATCH 04/14] Tiny one --- .../NikolaiKrivchanskii/Shell/Shell.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java index 8d8059c76..3739fcbdd 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java @@ -34,13 +34,13 @@ private void runCommand(String[] data, State state) throws SomethingIsWrongExcep if (usedOne == null) { throw new SomethingIsWrongException("Unknown command."); } else if (data.length - 1 != usedOne.getArgumentQuantity()) { - if (!(usedOne.getCommandName().equals("rm") && data.length - 1 == usedOne.getArgumentQuantity() + 1) - && !(usedOne.getCommandName().equals("cp") && data.length - 1 == - usedOne.getArgumentQuantity() + 1)) { - throw new SomethingIsWrongException("Wrong number of arguments. Correct argument quantity = " - + (data.length - 1) + "\nTo correctly run this command use " - + usedOne.getArgumentQuantity() + " arguments."); - } + if (!(usedOne.getCommandName().equals("rm") && data.length - 1 == usedOne.getArgumentQuantity() + 1) + && !(usedOne.getCommandName().equals("cp") && data.length - 1 + == usedOne.getArgumentQuantity() + 1)) { + throw new SomethingIsWrongException("Wrong number of arguments. Correct argument quantity = " + + (data.length - 1) + "\nTo correctly run this command use " + + usedOne.getArgumentQuantity() + " arguments."); + } } String[] commandArguments = Arrays.copyOfRange(data, 1, data.length); usedOne.implement(commandArguments, state); @@ -85,11 +85,11 @@ public void consoleWay(State state) { } /* public static void notmain(String[] args) { - ShellState state = new ShellState(System.getProperty("user.dir")); + ShellState state = new ShellState(System.getProperty("user.dir")); Set commands = new HashSet() {{ /*add(new WhereAreWeCommand()); add(new CopyCommand()); add(new DirectoryInfoCommand()); - add(new ExitCommand()); add(new MakeDirectoryCommand()); - add(new MoveCommand()); add(new RemoveCommand()); }};*/ + add(new ExitCommand()); add(new MakeDirectoryCommand()); + add(new MoveCommand()); add(new RemoveCommand()); }};*/ /* Shell shell = new Shell(commands); if (args.length != 0) { From 1fef5ff9b2519d5259e23d56fbd986d2011b9018 Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Sun, 12 Oct 2014 01:01:22 +0400 Subject: [PATCH 05/14] And even smaller one --- .../fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java index 3739fcbdd..a3b375401 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java @@ -36,7 +36,7 @@ private void runCommand(String[] data, State state) throws SomethingIsWrongExcep } else if (data.length - 1 != usedOne.getArgumentQuantity()) { if (!(usedOne.getCommandName().equals("rm") && data.length - 1 == usedOne.getArgumentQuantity() + 1) && !(usedOne.getCommandName().equals("cp") && data.length - 1 - == usedOne.getArgumentQuantity() + 1)) { + == usedOne.getArgumentQuantity() + 1)) { throw new SomethingIsWrongException("Wrong number of arguments. Correct argument quantity = " + (data.length - 1) + "\nTo correctly run this command use " + usedOne.getArgumentQuantity() + " arguments."); From 44d1e8744a8af97d6280cf868fb09cdc23b15601 Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Mon, 20 Oct 2014 14:31:34 +0400 Subject: [PATCH 06/14] Fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Коммит не той версии это эпично. --- .../filemap/FileMapMain.java | 3 +- .../filemap/FileMapShellStateInterface.java | 1 + .../filemap/ListCommand.java | 38 +++++++++++++++++++ .../NikolaiKrivchanskii/filemap/MyTable.java | 4 ++ .../filemap/ReadingUtils.java | 6 ++- .../filemap/SomeTable.java | 10 ++++- 6 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java index 25d3e3bb1..fe237164f 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java @@ -11,7 +11,8 @@ public static void main(String[] args) { FileMapShellState state = new FileMapShellState(); Set com = new HashSet() { { add(new ExitCommand()); add(new RollbackCommand()); add(new CommitCommand()); - add(new PutCommand()); add(new GetCommand()); add(new RemoveKeyCommand()); }}; + add(new PutCommand()); add(new GetCommand()); add(new RemoveKeyCommand()); + add(new ListCommand()); }}; Shell shell = new Shell(com); String dbDirectory = System.getProperty("fizteh.db.dir"); state.table = new SingleFileTable(dbDirectory, "master"); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java index 398ffbd87..db1836208 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellStateInterface.java @@ -1,5 +1,6 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + public interface FileMapShellStateInterface { Value put(Key key, Value value); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java new file mode 100644 index 000000000..5bf4a0b1a --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java @@ -0,0 +1,38 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import java.util.Set; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +public class ListCommand implements Commands { + + public String getCommandName() { + return "list"; + } + + public int getArgumentQuantity() { + return 0; + } + + public void implement(String[] args, FileMapShellState state) + throws SomethingIsWrongException { + if (state.table == null) { + throw new SomethingIsWrongException("Table not found."); + } + MyTable temp = (MyTable) state.table; + Set keySet = temp.list(); + if (keySet.size() == 0) { + System.out.println("\n"); + return; + } + StringBuilder sb = new StringBuilder(""); + for(String key : keySet) { + sb.append(key); + sb.append(", "); + } + sb.deleteCharAt(sb.length()-1); + sb.deleteCharAt(sb.length()-1); + System.out.println(sb.toString()); + } + +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java index 0d0b57268..587b224d1 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java @@ -1,11 +1,15 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; +import java.util.HashMap; +import java.util.Set; + public interface MyTable extends Table { String getName(); void setAutoCommit(boolean status); boolean getAutoCommit(); int getChangesCounter(); + Set list(); String get(String a); String put(String key, String value); String remove(String a); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java index d447189d4..fee2b1aaa 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java @@ -131,7 +131,11 @@ private int readOffset() throws SomethingIsWrongException { try { return tempFile.readInt(); } catch (IOException e) { - throw new SomethingIsWrongException("Error aqcuired while reading a file " + e.getMessage()); + if (e.getMessage() != null) { + throw new SomethingIsWrongException("Error aqcuired while reading a file " + e.getMessage()); + } else { + throw new SomethingIsWrongException("Empty file"); + } } } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java index 8e8c6e072..f7ffff14d 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java @@ -29,6 +29,12 @@ public boolean getAutoCommit() { return autoCommit; } + public Set list() { + Set toReturnSafe = new HashSet(); + toReturnSafe = currentData.keySet(); + return toReturnSafe; + } + public int getChangesCounter() { return unsavedChangesCounter; } @@ -58,7 +64,9 @@ public SomeTable(String dir, String name) { try { load(); } catch (SomethingIsWrongException e) { - System.err.println("Error aqcuired while opening a table. Message: " + e.getMessage()); + if (e.getMessage() != "Unable to scan from disc." && e.getMessage() != "Empty file") { + System.err.println("Error aqcuired while opening a table. Message: " + e.getMessage()); + } } } From e8388a1cbc7568e7e0e5e951001ff0d4e721a5cd Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Mon, 20 Oct 2014 14:43:59 +0400 Subject: [PATCH 07/14] Checkstyle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Вообще стоит отметить что он и создавал файл при отсутствии и корректно работал с пустым файлом, но писал "предупреждение" в поток ошибок, да. --- .../NikolaiKrivchanskii/filemap/ListCommand.java | 14 +++++++------- .../NikolaiKrivchanskii/filemap/MyTable.java | 1 - .../NikolaiKrivchanskii/filemap/ReadingUtils.java | 4 ++-- .../NikolaiKrivchanskii/filemap/SomeTable.java | 10 +++++----- 4 files changed, 14 insertions(+), 15 deletions(-) diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java index 5bf4a0b1a..15198ff0c 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java @@ -22,17 +22,17 @@ public void implement(String[] args, FileMapShellState state) MyTable temp = (MyTable) state.table; Set keySet = temp.list(); if (keySet.size() == 0) { - System.out.println("\n"); - return; + System.out.println("\n"); + return; } StringBuilder sb = new StringBuilder(""); for(String key : keySet) { - sb.append(key); - sb.append(", "); + sb.append(key); + sb.append(", "); } - sb.deleteCharAt(sb.length()-1); - sb.deleteCharAt(sb.length()-1); + sb.deleteCharAt(sb.length() - 1); + sb.deleteCharAt(sb.length() - 1); System.out.println(sb.toString()); } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java index 587b224d1..055fa8b2f 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java @@ -1,6 +1,5 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import java.util.HashMap; import java.util.Set; diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java index fee2b1aaa..6acadf993 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ReadingUtils.java @@ -131,10 +131,10 @@ private int readOffset() throws SomethingIsWrongException { try { return tempFile.readInt(); } catch (IOException e) { - if (e.getMessage() != null) { + if (e.getMessage() != null) { throw new SomethingIsWrongException("Error aqcuired while reading a file " + e.getMessage()); } else { - throw new SomethingIsWrongException("Empty file"); + throw new SomethingIsWrongException("Empty file"); } } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java index f7ffff14d..a6b7d6db6 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java @@ -30,9 +30,9 @@ public boolean getAutoCommit() { } public Set list() { - Set toReturnSafe = new HashSet(); - toReturnSafe = currentData.keySet(); - return toReturnSafe; + Set toReturnSafe = new HashSet(); + toReturnSafe = currentData.keySet(); + return toReturnSafe; } public int getChangesCounter() { @@ -64,9 +64,9 @@ public SomeTable(String dir, String name) { try { load(); } catch (SomethingIsWrongException e) { - if (e.getMessage() != "Unable to scan from disc." && e.getMessage() != "Empty file") { + if (!e.getMessage().equals("Unable to scan from disc.") && !e.getMessage().equals("Empty file")) { System.err.println("Error aqcuired while opening a table. Message: " + e.getMessage()); - } + } } } From cdb5fac5772deb3fa05783ad5c16608110c989d1 Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Mon, 20 Oct 2014 14:50:25 +0400 Subject: [PATCH 08/14] Mini --- .../fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java index 15198ff0c..bd7313be5 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java @@ -26,7 +26,7 @@ public void implement(String[] args, FileMapShellState state) return; } StringBuilder sb = new StringBuilder(""); - for(String key : keySet) { + for (String key : keySet) { sb.append(key); sb.append(", "); } From 722c8f6c9f638e201334c14a8b039c59756b23ff Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Mon, 10 Nov 2014 18:16:26 +0400 Subject: [PATCH 09/14] unused func deleted some small commit --- .../fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java index a6b7d6db6..3897a0c6c 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java @@ -50,10 +50,6 @@ public int size() { return size; } - public int getChangesCount() { - return unsavedChangesCounter; - } - public SomeTable(String dir, String name) { this.parentDirectory = dir; this.name = name; From d6034439e630df330a47f7464d8ab2ee85971934 Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Mon, 15 Dec 2014 13:12:05 +0400 Subject: [PATCH 10/14] =?UTF-8?q?=D0=A2=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20?= =?UTF-8?q?=D0=B1=D1=83=D0=B4=D1=83=20=D0=B6=D0=B4=D0=B0=D1=82=D1=8C=20?= =?UTF-8?q?=D1=84=D0=B0=D0=B9=D0=BB=201.new?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../students/NikolaiKrivchanskii/filemap/SingleFileTable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java index 961393f60..855e8f07a 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java @@ -9,7 +9,7 @@ public class SingleFileTable extends SomeTable { - public static final String DATABASENAME = "db.dat"; + public static final String DATABASENAME = "1.new"; public SingleFileTable(String dir, String name) { super(dir, name); From 3a827b06c71651d2c0cd9b6b237edf2c9c424f96 Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Tue, 16 Dec 2014 01:52:05 +0400 Subject: [PATCH 11/14] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D1=81=D0=BE?= =?UTF-8?q?=D0=B7=D0=B4=D0=B0=D0=BB=20=D0=B2=D0=B5=D1=82=D0=BA=D1=83=20Par?= =?UTF-8?q?allel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Traaaviiiis --- .../NikolaiKrivchanskii/Shell/Commands.java | 2 +- .../NikolaiKrivchanskii/Shell/Shell.java | 120 +++++---- .../filemap/CommitCommand.java | 13 +- .../filemap/ExitCommand.java | 39 +-- .../filemap/FileMapMain.java | 22 -- .../filemap/FileMapShellState.java | 2 +- .../filemap/GetCommand.java | 27 +- .../filemap/ListCommand.java | 8 +- .../NikolaiKrivchanskii/filemap/MyTable.java | 2 +- .../filemap/PutCommand.java | 25 +- .../filemap/RemoveKeyCommand.java | 25 +- .../filemap/RollbackCommand.java | 13 +- .../filemap/SimpleTableBuilder.java | 33 +++ .../filemap/SingleFileTable.java | 2 +- .../filemap/SizeCommand.java | 29 +- .../filemap/SomeStorage.java | 216 +++++++++++++++ .../filemap/SomeTable.java | 2 +- .../NikolaiKrivchanskii/filemap/Table.java | 1 + .../filemap/TableUsingStrings.java | 39 +++ .../multifilemap/CreateCommand.java | 32 +++ .../multifilemap/Database.java | 102 +++++++ .../multifilemap/DatabaseFactory.java | 24 ++ .../multifilemap/DatabaseTest.java | 88 +++++++ .../multifilemap/DropCommand.java | 34 +++ .../MultiFileMapReadingUtils.java | 34 +++ .../multifilemap/MultiFileMapShellState.java | 90 +++++++ .../MultiFileMapTableBuilder.java | 27 ++ .../MultiFileMapTableProviderClass.java | 9 + ...MultiFileMapTableProviderClassFactory.java | 7 + .../MultiFileMapWritingUtils.java | 57 ++++ .../multifilemap/MultifileMapMain.java | 48 ++++ .../MultifileMapShellStateInterface.java | 15 ++ .../multifilemap/MultifileTable.java | 35 +++ .../multifilemap/MultifileTableTest.java | 173 ++++++++++++ .../multifilemap/ShowTablesCommand.java | 28 ++ .../multifilemap/UseCommand.java | 43 +++ .../storable/DatabaseRow.java | 125 +++++++++ .../storable/DatabaseRowTest.java | 64 +++++ .../storable/DatabaseTable.java | 160 +++++++++++ .../storable/DatabaseTableProvider.java | 249 ++++++++++++++++++ .../DatabaseTableProviderFactory.java | 33 +++ .../DatabaseTableProviderFactoryTest.java | 20 ++ .../storable/DatabaseTableProviderTest.java | 27 ++ .../storable/DatabaseTableTest.java | 86 ++++++ .../storable/LocalUtils.java | 86 ++++++ .../storable/StorableMain.java | 58 ++++ .../storable/StorableShellState.java | 105 ++++++++ .../storable/StoreableTableBuilder.java | 61 +++++ .../storable/StoreableTypes.java | 97 +++++++ .../storable/TableInfo.java | 27 ++ .../storable/XmlDeserializer.java | 82 ++++++ .../storable/XmlSerializer.java | 52 ++++ 52 files changed, 2652 insertions(+), 146 deletions(-) delete mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SimpleTableBuilder.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClass.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClassFactory.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/ShowTablesCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRow.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRowTest.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTable.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactory.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactoryTest.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderTest.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableTest.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/LocalUtils.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableMain.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableShellState.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTableBuilder.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTypes.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/TableInfo.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlDeserializer.java create mode 100644 src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlSerializer.java diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java index f415dab67..ba941f5ac 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java @@ -7,5 +7,5 @@ public interface Commands { int getArgumentQuantity(); - void implement(String[] args, State state) throws SomethingIsWrongException; + abstract void implement(String args, State state) throws SomethingIsWrongException; } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java index a3b375401..42530a139 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java @@ -1,22 +1,28 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + public class Shell { private final Map availableCommands; - private static final String GREETING = "$ "; + private static final String greeting = "$ "; State state; - public Shell(Set commands) { - Map tempCommands = new HashMap(); - for (Commands temp : commands) { + public Shell (Set> commands) { + Map tempCommands = new HashMap(); + for (Commands temp : commands) { tempCommands.put(temp.getCommandName(), temp); } availableCommands = Collections.unmodifiableMap(tempCommands); @@ -26,52 +32,47 @@ public void setShellState(State state) { this.state = state; } - private void runCommand(String[] data, State state) throws SomethingIsWrongException { - if (data[0].length() == 0) { - throw new SomethingIsWrongException("Empty string."); - } - Commands usedOne = availableCommands.get(data[0]); - if (usedOne == null) { - throw new SomethingIsWrongException("Unknown command."); - } else if (data.length - 1 != usedOne.getArgumentQuantity()) { - if (!(usedOne.getCommandName().equals("rm") && data.length - 1 == usedOne.getArgumentQuantity() + 1) - && !(usedOne.getCommandName().equals("cp") && data.length - 1 - == usedOne.getArgumentQuantity() + 1)) { - throw new SomethingIsWrongException("Wrong number of arguments. Correct argument quantity = " - + (data.length - 1) + "\nTo correctly run this command use " - + usedOne.getArgumentQuantity() + " arguments."); - } + private void runCommand(String[] data, State state) throws SomethingIsWrongException { + for (String command : data) { + if (data[0].length() == 0) { + throw new SomethingIsWrongException ("Empty string."); + } + String name = Parser.getName(command); + Commands usedOne = availableCommands.get(name); + String args = Parser.getParameters(command); + if (usedOne == null) { + throw new SomethingIsWrongException ("Unknown command."); + } + usedOne.implement(args, state); + } } - String[] commandArguments = Arrays.copyOfRange(data, 1, data.length); - usedOne.implement(commandArguments, state); - } - private String[] splitLine(String str) { - str = str.trim(); - String[] toReturn = str.split("\\s*;\\s*", -2); - return toReturn; + /* public static String[] splitLine(String str) { + str = str.trim(); + return str.split("(\\s*;\\s*)", -1); } - private void runLine(String line, State state) throws SomethingIsWrongException { - String[] splitted = splitLine(line); - int count = splitted.length - 1; - for (String temp : splitted) { + private void runLine(String[] line, State state) throws SomethingIsWrongException { + int count = line.length - 1; + for (String temp : line) { --count; if (count >= 0) { - runCommand(temp.split("\\s+"), state); //This thing is needed to check if after last ";" - } else if (count < 0) { //situated a command or an empty string. So it - if (temp.length() != 0) { //won't throw a "Wrong command" exception when it - runCommand(temp.split("\\s+"), state); //looks like: "dir; cd ..; dir;" neither it will - } //loose a "dir" in: "dir; cd ..; dir; dir". - } //So it does nothing if it is the end, but performs - } //if there is a command after last ";". - } + runCommand(temp, state); //This thing is needed to check if after last ";" + } else if (count < 0) { //situated a command or an empty string. So it + if (temp.length() != 0) { //won't throw a "Wrong command" exception when it + runCommand(temp, state); //looks like: "dir; cd ..; dir;" neither it will + } //loose a "dir" in: "dir; cd ..; dir; dir". + } //So it does nothing if it is the end, but performs + } //if there is a command after last ";". + }*/ public void consoleWay(State state) { Scanner forInput = new Scanner(System.in); - while (!Thread.currentThread().isInterrupted()) { - System.out.print(GREETING); + while (!Thread.currentThread().isInterrupted()) { + System.out.print(greeting); try { - runLine(forInput.nextLine(), state); + String temp = forInput.nextLine(); + String[] commands = Parser.parseFullCommand(temp); + runCommand(commands, state); } catch (SomethingIsWrongException exc) { if (exc.getMessage().equals("EXIT")) { forInput.close(); @@ -79,19 +80,19 @@ public void consoleWay(State state) { } else { System.err.println(exc.getMessage()); } + } catch (IllegalArgumentException | IllegalStateException e) { + System.err.println(e.getMessage()); } } forInput.close(); } - /* public static void notmain(String[] args) { - ShellState state = new ShellState(System.getProperty("user.dir")); - Set commands = new HashSet() {{ - /*add(new WhereAreWeCommand()); add(new CopyCommand()); add(new DirectoryInfoCommand()); - add(new ExitCommand()); add(new MakeDirectoryCommand()); - add(new MoveCommand()); add(new RemoveCommand()); }};*/ - /* Shell shell = new Shell(commands); - + /*public static void main(String[] args) { + ShellState state = new ShellState(System.getProperty("user.dir")); + Set commands = new HashSet() {{ add(new WhereAreWeCommand()); add(new CopyCommand()); add(new DirectoryInfoCommand()); + add(new ExitCommand()); add(new MakeDirectoryCommand()); add(new MoveCommand()); add(new RemoveCommand()); }}; + Shell shell = new Shell(commands); + if (args.length != 0) { String arg = UtilMethods.uniteItems(Arrays.asList(args), " "); try { @@ -111,6 +112,25 @@ public void consoleWay(State state) { }*/ + public void run(String[] args, Shell shell) { + if (args.length != 0) { + String arg = UtilMethods.uniteItems(Arrays.asList(args), " "); + String[] commands = Parser.parseFullCommand(arg); + try { + runCommand(commands, state); + } catch (SomethingIsWrongException exc) { + if (exc.getMessage().equals("EXIT")) { + System.exit(0); + } else { + System.err.println(exc.getMessage()); + System.exit(-1); + } + } + } else { + consoleWay(state); + } + System.exit(0); + } + } - diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java index 7f02aa5af..08e13570d 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java @@ -1,8 +1,9 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; -public class CommitCommand implements Commands { +public class CommitCommand extends SomeCommand { public String getCommandName() { return "commit"; @@ -12,12 +13,12 @@ public int getArgumentQuantity() { return 0; } - public void implement(String[] args, FileMapShellState state) + public void implement(String args, State state) throws SomethingIsWrongException { - if (state.table == null) { - throw new SomethingIsWrongException("Table not found."); + if (state.getTable() == null) { + throw new SomethingIsWrongException ("no table"); } - state.table.commit(); + System.out.println(state.commit()); } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java index 078bdbaf9..dcc6ba810 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java @@ -1,24 +1,27 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; -public class ExitCommand implements Commands { - - public String getCommandName() { - return "exit"; - } +public class ExitCommand extends SomeCommand{ - public int getArgumentQuantity() { - return 0; - } - public void implement(String[] args, FileMapShellState state) throws SomethingIsWrongException { - MyTable temp = (MyTable) state.table; - if (state.table != null && !temp.getAutoCommit()) { - temp.rollback(); - } else if (temp.getAutoCommit() && state.table != null) { - temp.commit(); - } - throw new SomethingIsWrongException("EXIT"); - } + public String getCommandName() { + return "exit"; + } + + public int getArgumentQuantity() { + return 0; + } + + public void implement(String args, State state) + throws SomethingIsWrongException { + /*MyTable temp = (MyTable) state.getTable();*/ + if (state.getTable() != null /*&& !temp.getAutoCommit()*/) { + state.rollback(); + }/* else if (temp.getAutoCommit() && state.getTable() != null) { + state.commit(); + }*/ + throw new SomethingIsWrongException("EXIT"); + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java deleted file mode 100644 index fe237164f..000000000 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapMain.java +++ /dev/null @@ -1,22 +0,0 @@ -package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; - - -import java.util.HashSet; -import java.util.Set; - -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; - -public class FileMapMain { - public static void main(String[] args) { - FileMapShellState state = new FileMapShellState(); - Set com = new HashSet() { { add(new ExitCommand()); - add(new RollbackCommand()); add(new CommitCommand()); - add(new PutCommand()); add(new GetCommand()); add(new RemoveKeyCommand()); - add(new ListCommand()); }}; - Shell shell = new Shell(com); - String dbDirectory = System.getProperty("fizteh.db.dir"); - state.table = new SingleFileTable(dbDirectory, "master"); - shell.setShellState(state); - shell.consoleWay(state); - } -} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java index 9b8d1d354..aa4fa2343 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/FileMapShellState.java @@ -1,5 +1,5 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; - +import ru.fizteh.fivt.storage.strings.Table; public class FileMapShellState { public Table table = null; diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java index 4cd5570f3..4c0029d8d 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java @@ -1,8 +1,12 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; +import java.util.ArrayList; -public class GetCommand implements Commands { +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Parser; + +public class GetCommand> extends SomeCommand{ public String getCommandName() { return "get"; @@ -11,17 +15,22 @@ public String getCommandName() { public int getArgumentQuantity() { return 1; } - - public void implement(String[] args, FileMapShellState state) + + public void implement(String args, State state) throws SomethingIsWrongException { - if (state.table == null) { - throw new SomethingIsWrongException("Table not found."); + if (state.getTable() == null) { + throw new SomethingIsWrongException ("no table"); + } + ArrayList parameters = Parser.parseCommandArgs(args); + if (parameters.size() != 1) { + throw new IllegalArgumentException("Use 1 argument for this operation"); } - String value = state.table.get(args[0]); + Key key = state.parseKey(parameters.get(0)); + Value value = state.get(key); if (value == null) { - System.out.println("Not found\n"); + System.out.println("not found"); } else { - System.out.println("Found:\n" + value); + System.out.println("found\n" + state.valueToString(value)); } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java index bd7313be5..b53e6807b 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java @@ -1,5 +1,6 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; +import java.util.ArrayList; import java.util.Set; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; @@ -14,17 +15,22 @@ public int getArgumentQuantity() { return 0; } - public void implement(String[] args, FileMapShellState state) + public void implement(String args, FileMapShellState state) throws SomethingIsWrongException { if (state.table == null) { throw new SomethingIsWrongException("Table not found."); } + ArrayList parameters = Parser.parseCommandArgs(args); + if (parameters.size() != 0) { + throw new SomethingIsWrongException("This command takes no parameters"); + } MyTable temp = (MyTable) state.table; Set keySet = temp.list(); if (keySet.size() == 0) { System.out.println("\n"); return; } + StringBuilder sb = new StringBuilder(""); for (String key : keySet) { sb.append(key); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java index 055fa8b2f..ddeafc5c6 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java @@ -1,7 +1,7 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; import java.util.Set; - +import ru.fizteh.fivt.storage.strings.Table; public interface MyTable extends Table { String getName(); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java index bd00504ae..a123a20a4 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java @@ -1,8 +1,12 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; +import java.util.ArrayList; -public class PutCommand implements Commands { +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Parser; + +public class PutCommand> extends SomeCommand{ public String getCommandName() { return "put"; @@ -12,14 +16,21 @@ public int getArgumentQuantity() { return 2; } - public void implement(String[] args, FileMapShellState state) + public void implement(String args, State state) throws SomethingIsWrongException { - if (state.table == null) { - throw new SomethingIsWrongException("No table chosen"); + if (state.getTable() == null) { + System.err.println("no table"); + return; + } + ArrayList parameters = Parser.parseCommandArgs(args); + if (parameters.size() != 2) { + throw new IllegalArgumentException("Use 2 arguments for this operation"); } - String temp = state.table.put(args[0], args[1]); + Key key = state.parseKey(parameters.get(0)); + Value value = state.parseValue(parameters.get(1)); + Value temp = state.put(key, value); if (temp != null) { - System.out.println("overwrite\n" + temp); + System.out.println("overwrite\n" + state.valueToString(temp)); } else { System.out.println("new"); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java index 5ff887040..e63a57d1d 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java @@ -1,9 +1,12 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Commands; +import java.util.ArrayList; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Parser; -public class RemoveKeyCommand implements Commands { +public class RemoveKeyCommand> extends SomeCommand{ public String getCommandName() { return "remove"; @@ -12,14 +15,22 @@ public String getCommandName() { public int getArgumentQuantity() { return 1; } - - public void implement(String[] args, FileMapShellState state) + + public void implement(String args, State state) throws SomethingIsWrongException { - String a = state.table.remove(args[0]); - if (a.isEmpty()) { + if (state.getTable() == null) { + throw new SomethingIsWrongException("no table"); + } + ArrayList parameters = Parser.parseCommandArgs(args); + if (parameters.size() != 1) { + throw new IllegalArgumentException("Use 1 argument for this operation"); + } + Key key = state.parseKey(parameters.get(0)); + Value a = state.remove(key); + if (a == null) { System.out.println("not found"); } else { - System.out.println("found\n" + a); + System.out.println("removed"); } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java index 1d638f696..5fb6b77b0 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java @@ -1,8 +1,9 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; -public class RollbackCommand implements Commands { +public class RollbackCommand extends SomeCommand{ public String getCommandName() { return "rollback"; @@ -12,12 +13,12 @@ public int getArgumentQuantity() { return 0; } - public void implement(String[] args, FileMapShellState state) + public void implement(String args, State state) throws SomethingIsWrongException { - if (state.table == null) { - throw new SomethingIsWrongException("No table chosen"); + if (state.getTable() == null) { + throw new SomethingIsWrongException("no table"); } - state.table.rollback(); + System.out.println(state.rollback()); } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SimpleTableBuilder.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SimpleTableBuilder.java new file mode 100644 index 000000000..3018b7736 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SimpleTableBuilder.java @@ -0,0 +1,33 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import java.io.File; +import java.util.Set; + +public class SimpleTableBuilder implements TableBuilder { + TableUsingStrings table; + + public String get(String key) { + return table.rawGet(key); + } + + public void put(String key, String value) { + table.rawPut(key, value); + } + + public Set getKeys() { + return table.unchangedOldData.keySet(); + } + + public File getTableDirectory() { + return new File(table.getParentDirectory(), table.getName()); + } + + public void setCurrentFile(File currentFile) { + } + + public SimpleTableBuilder(TableUsingStrings table) { + this.table = table; + } + + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java index 855e8f07a..961393f60 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SingleFileTable.java @@ -9,7 +9,7 @@ public class SingleFileTable extends SomeTable { - public static final String DATABASENAME = "1.new"; + public static final String DATABASENAME = "db.dat"; public SingleFileTable(String dir, String name) { super(dir, name); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java index 58cebe458..242f921b3 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java @@ -4,23 +4,22 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; -public class SizeCommand> extends SomeCommand { +public class SizeCommand> extends SomeCommand { - public String getCommandName() { - return "size"; - } + public String getCommandName() { + return "size"; + } - public int getArgumentQuantity() { - return 0; - } + public int getArgumentQuantity() { + return 0; + } - public void implement(String[] args, State state) - throws SomethingIsWrongException { - if (state.getTable() == null) { - throw new SomethingIsWrongException("no table"); - } - System.out.println(state.size()); - } + public void implement(String args, State state) + throws SomethingIsWrongException { + if (state.getTable() == null) { + throw new SomethingIsWrongException("no table"); + } + System.out.println(state.size()); + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java new file mode 100644 index 000000000..08451c15c --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java @@ -0,0 +1,216 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + + +public abstract class SomeStorage { + protected HashMap unchangedOldData; + protected HashSet deletedKeys; + private String name; + protected String parentDirectory; + protected boolean doAutoCommit; + private final Lock transactionLock = new ReentrantLock(true); + + protected final ThreadLocal transaction = new ThreadLocal() { + public Transactions initialValue() { + return new Transactions(); + } + }; + + class Transactions { + HashMap currentData; + int size; + int unsavedChangesCounter; + + Transactions() { + this.currentData = new HashMap(); + this.size = 0; + this.unsavedChangesCounter = 0; + } + + public void newModification(Key key, Value value) { + currentData.put(key, value); + } + + public int saveModifications() { + int changesCounter = 0; + for(Key key : currentData.keySet()) { + Value newOne = currentData.get(key); + if(!GlobalUtils.compare(newOne, unchangedOldData.get(key))) { + if (newOne != null) { + unchangedOldData.put(key, newOne); + } else { + unchangedOldData.remove(key); + } + changesCounter++; + } + } + return changesCounter; + } + + public int calculateChangesQuantity() { + int changesCounter = 0; + for(Key key : currentData.keySet()) { + Value newOne = currentData.get(key); + if(!GlobalUtils.compare(newOne, unchangedOldData.get(key))) { + changesCounter++; + } + } + return changesCounter; + } + + public int calculateSize() { + int size = unchangedOldData.size(); + for(Key key : currentData.keySet()) { + Value newOne = currentData.get(key); + Value oldOne = unchangedOldData.get(key); + if (newOne == null && oldOne != null) { + size--; + } else if (newOne != null && oldOne == null) { + size++; + } + } + return size; + } + + public Value getVal(Key key) { + if (currentData.containsKey(key)) { + return currentData.get(key); + } + return unchangedOldData.get(key); + } + + public HashSet getKeys() { + HashSet result = new HashSet(); + result.addAll(currentData.keySet()); + return result; + } + + public int getSize() { + return unchangedOldData.size() + calculateSize(); + } + + public void incrementUnsavedChangesCounter() { + unsavedChangesCounter++; + } + + public int getUnsavedChangesCounter() { + return unsavedChangesCounter; + } + + public void clear() { + currentData.clear(); + unsavedChangesCounter = 0; + size = 0; + } + + } + + public String getParentDirectory() { + return parentDirectory; + } + + public void setAutoCommit(boolean status) { + doAutoCommit = status; + } + + public boolean getAutoCommit() { + return doAutoCommit; + } + + public String getName() { + return name; + } + public int sizeOfStorage() { + return transaction.get().calculateSize(); + } + + public int getChangesCounter() { + return transaction.get().calculateChangesQuantity(); + } + + protected abstract void load() throws IOException; + protected abstract void save() throws IOException; + + public SomeStorage(String dir, String name) { + this.parentDirectory = dir; + this.name = name; + unchangedOldData = new HashMap(); + try { + load(); + } catch (IOException e) { + if (e.getMessage() != "didn't exist" && e.getMessage() != "empty file") { + throw new IllegalArgumentException("invalid file format " + e.getMessage()); + } + } + + } + + public Value getFromStorage(Key key) { + if (key == null) { + throw new IllegalArgumentException ("key cannot be null"); + } + return transaction.get().getVal(key); + } + + public Set getAllKeys() { + return transaction.get().getKeys(); + } + + public Value putIntoStorage(Key key, Value value) { + Value oldVal = transaction.get().getVal(key); + transaction.get().newModification(key, value); + return oldVal; + } + + public Value removeFromStorage(Key key) { + if (key == null ) { + throw new IllegalArgumentException("key cannot be null"); + } + if (getFromStorage(key) == null) { + return null; + } + Value oldVal = transaction.get().getVal(key); + transaction.get().newModification(key, null); + transaction.get().incrementUnsavedChangesCounter(); + return oldVal; + } + + public int rollbackStorage() { + int deletedOrAdded = transaction.get().calculateChangesQuantity(); + transaction.get().clear(); + return deletedOrAdded; + } + + public int commitStorage() { + try{ + transactionLock.lock(); + int commitCount = transaction.get().saveModifications(); + transaction.get().clear(); + try { + save(); + } catch (IOException e) { + System.err.println("commit error: " + e.getMessage()); + return 0; + } + return commitCount; + } finally { + transactionLock.unlock(); + } + } + + void rawPut(Key key, Value value) { + unchangedOldData.put(key, value); + } + + Value rawGet(Key key) { + return unchangedOldData.get(key); + } + + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java index 3897a0c6c..81d2ea819 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java @@ -16,7 +16,7 @@ public abstract class SomeTable implements MyTable { private String parentDirectory; private static int size; public static int unsavedChangesCounter; - protected boolean autoCommit = true; //to block JUnit functional for a filemap + protected boolean autoCommit = false; //to block JUnit functional for a filemap protected abstract void load() throws SomethingIsWrongException; protected abstract void save() throws SomethingIsWrongException; diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java index ffccedda7..240eaf373 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/Table.java @@ -1,5 +1,6 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + public interface Table { String getName(); String get(String a); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java new file mode 100644 index 000000000..44924e793 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java @@ -0,0 +1,39 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; + +import java.util.HashSet; +import java.util.Set; + +public abstract class TableUsingStrings extends SomeStorage implements MyTable { + protected TableUsingStrings(String dir, String name) { + super(dir, name); + } + + public String remove(String key) { + return removeFromStorage(key); + } + + public int size() { + return sizeOfStorage(); + } + + public String get(String key) { + return getFromStorage(key); + } + + public String put(String key, String value) { + return putIntoStorage(key, value); + } + + public int rollback() { + return rollbackStorage(); + } + + public int commit() { + return commitStorage(); + } + + public Set list() { + return getAllKeys(); + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java new file mode 100644 index 000000000..18b492294 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java @@ -0,0 +1,32 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; + +public class CreateCommand> extends SomeCommand { + public String getCommandName() { + return "create"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String args, State state) throws SomethingIsWrongException { + Table newOne = null; + String tableName = GlobalUtils.parseTableName(args); + try { + newOne = state.createTable(args); + if (newOne != null) { + System.out.println("created"); + } else { + System.out.println(tableName + " exists"); + } + } catch (IllegalArgumentException e) { + throw new SomethingIsWrongException (e.getMessage()); + } + + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java new file mode 100644 index 000000000..b32232c7e --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java @@ -0,0 +1,102 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import ru.fizteh.fivt.storage.strings.TableProvider; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; + +public class Database implements TableProvider { + private static final String CHECK_NAME_EXPRESSION = "[^0-9A-Za-zА-Яа-я]+"; + HashMap content = new HashMap(); + private String databaseDirectoryPath; + private MultifileTable currentTable = null; + + public Database(String databaseDirectoryPath) { + this.databaseDirectoryPath = databaseDirectoryPath; + File databaseDirectory = new File(databaseDirectoryPath); + for(File tableFile : databaseDirectory.listFiles()) { + if (tableFile.isFile()) { + continue; + } + MultifileTable table = new MultifileTable(databaseDirectoryPath, tableFile.getName()); + content.put(table.getName(), table); + } + } + + public MultifileTable getTable(String name) { + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("table's name cannot be null"); + } + checkName(name); + MultifileTable table = content.get(name); + if (table == null) { + return table; + } + if (currentTable != null) { + int changes = currentTable.getChangesCounter(); + if (changes > 0 && !currentTable.getAutoCommit()) { + throw new IllegalStateException(changes + " unsaved changes"); + } else if (currentTable.getAutoCommit()) { + currentTable.commit(); + } + } + + currentTable = table; + return table; + } + + public HashMap showTables() { + HashMap tables = new HashMap(); + for (Entry contents : content.entrySet()) { + tables.put(contents.getKey(), contents.getValue().size()); + } + return tables; + } + + public MultifileTable createTable(String name) { + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("Table's name cannot be null"); + } + checkName(name); + if (content.containsKey(name)) { + return null; + } + File tableDirectory = new File(databaseDirectoryPath, name); + if (!tableDirectory.exists()) { + tableDirectory.mkdir(); + } + MultifileTable table = new MultifileTable(databaseDirectoryPath, name); + content.put(name, table); + return table; + } + + public void removeTable(String name) { + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException ("Table's name cannot be null"); + } + if (!content.containsKey(name)) { + throw new IllegalStateException(name + " not exists"); + } + if (currentTable != null) { + if (currentTable.getName().equals(name)) { + currentTable = null; + } + } + content.remove(name); + File tableFile = new File(databaseDirectoryPath, name); + GlobalUtils.deleteFile(tableFile); + } + + private void checkName(String name) { + Pattern pattern = Pattern.compile(CHECK_NAME_EXPRESSION); + Matcher matcher = pattern.matcher(name); + if (matcher.find()) { + throw new IllegalArgumentException("bad symbol in table's name"); + } + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java new file mode 100644 index 000000000..27edbc20f --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java @@ -0,0 +1,24 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + + +import java.io.File; + +import ru.fizteh.fivt.storage.strings.TableProvider; + + + +public class DatabaseFactory implements MultiFileMapTableProviderClassFactory { + public TableProvider create(String directory) { + if (directory == null || directory.isEmpty() ) { + throw new IllegalArgumentException ("directory name cannot be null"); + } + File databaseDirectory = new File(directory); + if (databaseDirectory.isFile()) { + throw new IllegalArgumentException ("it must be directory, not file"); + } + if (!databaseDirectory.exists()) { + databaseDirectory.mkdir(); + } + return new Database(databaseDirectory.getAbsolutePath()); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java new file mode 100644 index 000000000..123f3a894 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java @@ -0,0 +1,88 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import ru.fizteh.fivt.storage.strings.*; + +public class DatabaseTest { + + TableProviderFactory factory; + TableProvider provider; + + @Before + public void beforeTest() { + factory = new DatabaseFactory(); + provider = factory.create("C:\\temp\\database_test"); + provider.createTable("table1"); + provider.createTable("table2"); + } + + @Test + public void testCreateTable() throws Exception { + // non-existing tables + Assert.assertNotNull(provider.createTable("newtable1")); + Assert.assertNotNull(provider.createTable("newtable2")); + // existing tables + Assert.assertNull(provider.createTable("table1")); + Assert.assertNull(provider.createTable("table2")); + + // clean-up + provider.removeTable("newtable1"); + provider.removeTable("newtable2"); + } + + @Test + public void testGetTable() throws Exception { + // non-existing tables + Assert.assertNull(provider.getTable("nonexistingtable")); + Assert.assertNull(provider.getTable("thereisnosuchtable")); + // existing tables + Assert.assertNotNull(provider.getTable("table1")); + Assert.assertNotNull(provider.getTable("table2")); + + Table table1 = provider.getTable("table1"); + Assert.assertEquals(table1, provider.getTable("table1")); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetTableExceptions() { + provider.getTable(null); + } + + @Test(expected = IllegalArgumentException.class) + public void testCreateTableExceptions() { + provider.createTable(null); + } + + @Test + public void testRemoveTable() throws Exception { + //prepare + provider.createTable("newtable1"); + provider.createTable("newtable2"); + + // existing tables + provider.removeTable("newtable1"); + provider.removeTable("newtable2"); + } + + @Test(expected = IllegalArgumentException.class) + public void testRemoveTableIllegalArgumentException() { + provider.removeTable(null); + } + + @Test(expected = IllegalStateException.class) + public void testRemoveTableIllegalStateException() { + provider.removeTable("nonexistingtable"); + provider.removeTable("nosuchtable"); + } + + @After + public void testAfter() { + provider.removeTable("table1"); + provider.removeTable("table2"); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java new file mode 100644 index 000000000..67f45f8ab --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java @@ -0,0 +1,34 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; +import java.io.IOException; +import java.util.ArrayList; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Parser; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; + + +public class DropCommand extends SomeCommand{ + public String getCommandName() { + return "drop"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String args, State state) throws SomethingIsWrongException { + ArrayList parameters = Parser.parseCommandArgs(args); + if (parameters.size() != 1) { + throw new IllegalArgumentException("Correct number of arguments -- 1"); + } + try { + state.dropTable(parameters.get(0)); + System.out.println("dropped"); + } catch (IOException e) { + throw new SomethingIsWrongException (e.getMessage()); + } catch (IllegalStateException e) { + throw new SomethingIsWrongException (e.getMessage()); + } + } + +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java new file mode 100644 index 000000000..36c19603f --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java @@ -0,0 +1,34 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.io.File; +import java.io.IOException; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.FileMapReadingUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableBuilder; + + +public class MultiFileMapReadingUtils { + public static void load(TableBuilder build) throws IOException { + File tableDir = build.getTableDirectory(); + if (tableDir.listFiles() == null) { + return; + } + + for (File dir : tableDir.listFiles()) { + if(dir.isFile()) { + continue; + } + + if(dir.listFiles().length == 0) { + throw new IllegalArgumentException("empty bucket"); + } + + for(File file : dir.listFiles()) { + build.setCurrentFile(file); + FileMapReadingUtils.scanFromDisk(file.getAbsolutePath(), build); + } + } + + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java new file mode 100644 index 000000000..12c0a8ac9 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java @@ -0,0 +1,90 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + + +import java.io.IOException; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.FileMapShellState; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.MyTable; + +public class MultiFileMapShellState extends FileMapShellState implements MultifileMapShellStateInterface { + public MultiFileMapTableProviderClass tableProvider; + + public MyTable useTable(String name) { + MyTable tempTable = (MyTable) tableProvider.getTable(name); + if (tempTable != null) { + table = tempTable; + } + return tempTable; + } + + public MyTable createTable(String args) { + return (MyTable) tableProvider.createTable(args); + } + + public void dropTable(String name) throws IOException { + tableProvider.removeTable(name); + if (table.getName().equals(name)) { + table = null; + } + } + + public String getCurrentTableName() { + return table.getName(); + } + + @Override + public String put(String key, String value) { + return table.put(key, value); + } + + @Override + public String get(String key) { + return table.get(key); + } + + @Override + public int commit() { + return table.commit(); + } + + @Override + public int rollback() { + return table.rollback(); + } + + @Override + public int size() { + return table.size(); + } + + @Override + public String remove(String key) { + return table.remove(key); + } + + @Override + public MyTable getTable() { + return (MyTable) table; + } + + @Override + public String keyToString(String key) { + return key; + } + + @Override + public String valueToString(String value) { + return value; + } + + @Override + public String parseKey(String key) { + return key; + } + + @Override + public String parseValue(String value) { + return value; + } +} + diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java new file mode 100644 index 000000000..7399c00aa --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java @@ -0,0 +1,27 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.io.File; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.SimpleTableBuilder; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableUsingStrings; + +public class MultiFileMapTableBuilder extends SimpleTableBuilder { + private int currentDir; + private int currentFile; + + + public MultiFileMapTableBuilder(TableUsingStrings table) { + super(table); + } + + public void setCurrentFile(File file) { + currentDir = GlobalUtils.parseDirNumber(file.getParentFile()); + currentFile = GlobalUtils.parseFileNumber(file); + } + + public void put(String key, String value) { + GlobalUtils.checkKeyPlacement(key, currentDir, currentFile); + super.put(key, value); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClass.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClass.java new file mode 100644 index 000000000..701011b3f --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClass.java @@ -0,0 +1,9 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.util.HashMap; + +import ru.fizteh.fivt.storage.strings.TableProvider; + +public abstract interface MultiFileMapTableProviderClass extends TableProvider { + HashMap showTables(); +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClassFactory.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClassFactory.java new file mode 100644 index 000000000..19ab5b4cd --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClassFactory.java @@ -0,0 +1,7 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import ru.fizteh.fivt.storage.strings.TableProviderFactory; + +public interface MultiFileMapTableProviderClassFactory extends TableProviderFactory { + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java new file mode 100644 index 000000000..7932979a3 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java @@ -0,0 +1,57 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.FileMapWritingUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableBuilder; + +public class MultiFileMapWritingUtils { + + public static void save(TableBuilder build) throws IOException { + File tableDir = build.getTableDirectory(); + if (tableDir.listFiles() == null) { + return; + } + ArrayList> toSave = new ArrayList>(); + boolean dirIsEmpty; + + for (int dirNumber = 0; dirNumber < GlobalUtils.DIR_QUANTITY; ++dirNumber) { + toSave.clear(); + for (int fileNumber = 0; fileNumber < GlobalUtils.FILES_PER_DIR; ++fileNumber) { + toSave.add(new HashSet()); + } + dirIsEmpty = true; + + for (String key : build.getKeys()) { + if (GlobalUtils.getDirNumber(key) == dirNumber) { + int fileNumber = GlobalUtils.getFileNumber(key); + toSave.get(fileNumber).add(key); + dirIsEmpty = false; + } + } + String dirName = dirNumber + ".dir"; + File dir = new File(tableDir, dirName); + if (dirIsEmpty) { + GlobalUtils.deleteFile(dir); + } + for (int fileNumber = 0; fileNumber < GlobalUtils.FILES_PER_DIR; ++fileNumber) { + String fileName = fileNumber + ".dat"; + File file = new File(dir, fileName); + if (toSave.get(fileNumber).isEmpty()) { + GlobalUtils.deleteFile(file); + continue; + } + if (!dir.exists()) { + dir.mkdir(); + } + FileMapWritingUtils.writeOnDisk(toSave.get(fileNumber), + file.getAbsolutePath(), build); + } + } + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java new file mode 100644 index 000000000..b51d13a9b --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java @@ -0,0 +1,48 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.util.ArrayList; +import java.util.HashSet; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.CommitCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.ExitCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.FileMapShellState; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GetCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.ListCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.PutCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.RemoveKeyCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.RollbackCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.SizeCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Commands; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Shell; + + +public class MultifileMapMain { + public static void main(String args[]) { + HashSet> com = new HashSet>() {{ + add(new ExitCommand()); add(new RollbackCommand()); add(new CommitCommand()); add(new ListCommand()); + add(new PutCommand()); add(new GetCommand()); add(new RemoveKeyCommand()); add(new SizeCommand());}}; + HashSet> com1 = new HashSet>() + {{add(new DropCommand()); add(new UseCommand()); + add(new CreateCommand());}}; + ArrayList> res = new ArrayList>(); + res.addAll(com); + res.addAll(com1); + HashSet> actualResult = new HashSet>(res); + Shell shell = new Shell(actualResult); + try { + String dbDirectory = System.getProperty("fizteh.db.dir"); + if (dbDirectory == null) { + System.err.println("error: nope. Gimme something."); + System.exit(-2); + } + MultiFileMapShellState state = new MultiFileMapShellState(); + DatabaseFactory factory = new DatabaseFactory(); + state.tableProvider = (MultiFileMapTableProviderClass) factory.create(dbDirectory); + shell.setShellState(state); + } catch (IllegalArgumentException e) { + System.err.println("error: " + e.getMessage()); + System.exit(-1); + } + shell.run(args, shell); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java new file mode 100644 index 000000000..67edef8eb --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java @@ -0,0 +1,15 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.io.IOException; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.FileMapShellStateInterface; + +public interface MultifileMapShellStateInterface extends FileMapShellStateInterface { + public Table useTable(String name); + + public Table createTable(String arguments); + + public void dropTable(String name) throws IOException; + + public String getCurrentTableName(); +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java new file mode 100644 index 000000000..86cb3a1c8 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java @@ -0,0 +1,35 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.io.IOException; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.SimpleTableBuilder; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableUsingStrings; + + +public class MultifileTable extends TableUsingStrings { + + + + public MultifileTable(String directory, String tableName) { + super(directory, tableName); + } + + /*private File getTableDirectory() { + File tableDirectory = new File(getParentDirectory(), getName()); + if (!tableDirectory.exists()) { + tableDirectory.mkdir(); + } + return tableDirectory; + }*/ + + protected void load() throws IOException { + MultiFileMapReadingUtils.load(new SimpleTableBuilder(this)); + + } + + protected void save() throws IOException{ + MultiFileMapWritingUtils.save(new SimpleTableBuilder(this)); + + } + +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java new file mode 100644 index 000000000..e7d5706a6 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java @@ -0,0 +1,173 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.util.Random; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import ru.fizteh.fivt.storage.strings.TableProvider; +import ru.fizteh.fivt.storage.strings.TableProviderFactory; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.MyTable; + +public class MultifileTableTest { + + private static final int KEYS_COUNT = 20; + private static final String TABLE_NAME = "testtable"; + MyTable currentTable; + + TableProviderFactory factory = new DatabaseFactory(); + TableProvider provider = factory.create("C:\\temp\\database_test"); + + + @Before + public void gettingReady() throws Exception { + currentTable = (MyTable) provider.createTable(TABLE_NAME); + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String value = String.format("value%d", index); + currentTable.put(key, value); + } + } + + @Test + public void testForNewData() { + // new data + for (int index = 0; index < KEYS_COUNT; ++index) { + String newKey = String.format("new_key%d", index); + String newValue = String.format("new_value%d", index); + Assert.assertNull(currentTable.put(newKey, newValue)); + } + } + + @Test + public void testForExistingData() { + // existing data + for (int index = 0; index < KEYS_COUNT; ++index) { + String expectedValue = String.format("value%d", index); + String key = String.format("key%d", index); + Assert.assertEquals(expectedValue, currentTable.get(key)); + } + } + + @Test + public void testForUnexistingData() { + // non-existing data + Random random = new Random(); + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("k%d", random.nextInt(100)); + Assert.assertNull(currentTable.get(key)); + } + } + + @Test + public void testForReplaceData() { + // replacing + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String oldValue = String.format("value%d", index); + String newValue = String.format("new_value%d", index); + Assert.assertEquals(oldValue, currentTable.put(key, newValue)); + } + } + + @Test + public void testCommit() { + int committed = currentTable.commit(); + Assert.assertEquals(KEYS_COUNT, committed); + + for (int index = 0; index < 2 * KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String value = String.format("value%d", index); + currentTable.put(key, value); + } + + Assert.assertEquals(KEYS_COUNT, currentTable.commit()); + + for (int index = 0; index < 2 * KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + Assert.assertNotNull(currentTable.get(key)); + } + } + + @Test + public void testRollback() { + Assert.assertEquals(KEYS_COUNT, currentTable.rollback()); + + for (int index = 0; index < 2 * KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String value = String.format("value%d", index); + currentTable.put(key, value); + } + + Assert.assertEquals(2 * KEYS_COUNT, currentTable.rollback()); + + for (int index = 0; index < 2 * KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + Assert.assertNull(currentTable.get(key)); + } + } + + @Test + public void testSize() { + Assert.assertEquals(KEYS_COUNT, currentTable.size()); + } + + @Test + public void testGetName() { + Assert.assertEquals(TABLE_NAME, currentTable.getName()); + } + + @Test(expected = IllegalArgumentException.class) + public void testTableExceptions() { + // get + currentTable.get(null); + + // storagePut + currentTable.put(null, "value"); + currentTable.put("key", null); + + // storageRemove + currentTable.remove(null); + } + + @Test + public void testRollbackAndCommit() + { + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String value = String.format("value%d", index); + currentTable.put(key, value); + } + currentTable.commit(); + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + currentTable.remove(key); + } + for (int index = 0; index < KEYS_COUNT; ++index) { + String key = String.format("key%d", index); + String value = String.format("value%d", index); + currentTable.put(key, value); + } + Assert.assertEquals(0, currentTable.rollback()); + + currentTable.remove("non-exists"); + currentTable.remove("non-exists1"); + currentTable.remove("key1"); + currentTable.put("key1", "value1"); + Assert.assertEquals(0, currentTable.rollback()); + + currentTable.put("key1", "value1"); + currentTable.commit(); + currentTable.remove("key1"); + currentTable.put("key1", "value1"); + Assert.assertEquals(0, currentTable.rollback()); + } + + @After + public void cleaningUp() throws Exception { + provider.removeTable(TABLE_NAME); + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/ShowTablesCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/ShowTablesCommand.java new file mode 100644 index 000000000..3ce818f21 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/ShowTablesCommand.java @@ -0,0 +1,28 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map.Entry; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; + +public class ShowTablesCommand implements Commands { + public String getCommandName() { + return "show"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String args, MultiFileMapShellState state) throws SomethingIsWrongException { + ArrayList parameters = Parser.parseCommandArgs(args); + if(parameters.get(0) != "tables") { + throw new SomethingIsWrongException("no command with this name"); + } + HashMap tables = state.tableProvider.showTables(); + for(Entry iterator : tables.entrySet()) { + System.out.println(iterator.getKey() + ' ' + iterator.getValue()); + } + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java new file mode 100644 index 000000000..4831ca76d --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java @@ -0,0 +1,43 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; + + +import java.util.ArrayList; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Parser; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; + +public class UseCommand> extends SomeCommand { + public String getCommandName() { + return "use"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String args, State state) throws SomethingIsWrongException { + ArrayList parameters = Parser.parseCommandArgs(args); + if (parameters.size() != 1) { + throw new IllegalArgumentException("Correct number of arguments -- 1"); + } + Table newOne = null; + try { + newOne = state.useTable(parameters.get(0)); + } catch (IllegalStateException e) { + System.err.println(e.getMessage()); + return; + } catch (IllegalArgumentException e) { + System.err.println(e.getMessage()); + return; + } + + if (newOne == null) { + System.out.println(parameters.get(0) + " not exists"); + return; + } + + System.out.println("using " + state.getCurrentTableName()); + + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRow.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRow.java new file mode 100644 index 000000000..ae2cf2e0c --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRow.java @@ -0,0 +1,125 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; + +import ru.fizteh.fivt.storage.structured.ColumnFormatException; +import ru.fizteh.fivt.storage.structured.Storeable; + +public class DatabaseRow implements Storeable { + final List> classes = new ArrayList<>(); + List columns = new ArrayList<>(); + + public DatabaseRow(List> classes) { + this.classes.addAll(classes); + for (int i = 0; i < classes.size(); ++i) { + columns.add(null); + } + } + + public DatabaseRow() {} + + private void checkBounds(int index) throws IndexOutOfBoundsException { + if (index < 0 || index >= classes.size()) { + throw new IndexOutOfBoundsException(String.format("index out of bound: %d", index)); + } + } + + private void checkColumnType(int columnIndex, Class actualType) throws ColumnFormatException { + if (!actualType.isAssignableFrom(classes.get(columnIndex))) { + throw new ColumnFormatException(String.format("incorrect type: expected type: %s actual type: %s", + classes.get(columnIndex).getName(), actualType.getName())); + } + } + + public boolean equals(Object obj) { + DatabaseRow otherStoreable = (DatabaseRow) obj; + return otherStoreable.columns.equals(columns) && otherStoreable.classes.equals(classes); + } + + public String getStringAt(int columnIndex) throws ColumnFormatException, IndexOutOfBoundsException { + checkBounds(columnIndex); + checkColumnType(columnIndex, String.class); + return (String) columns.get(columnIndex); + } + + public Object getColumnAt(int columnIndex) throws IndexOutOfBoundsException { + checkBounds(columnIndex); + return columns.get(columnIndex); + } + + public Integer getIntAt(int columnIndex) throws ColumnFormatException, IndexOutOfBoundsException { + checkBounds(columnIndex); + checkColumnType(columnIndex, Integer.class); + return (Integer) columns.get(columnIndex); + } + + public Long getLongAt(int columnIndex) throws ColumnFormatException, IndexOutOfBoundsException { + checkBounds(columnIndex); + checkColumnType(columnIndex, Long.class); + return (Long) columns.get(columnIndex); + } + + public Byte getByteAt(int columnIndex) throws ColumnFormatException, IndexOutOfBoundsException { + checkBounds(columnIndex); + checkColumnType(columnIndex, Byte.class); + return (Byte) columns.get(columnIndex); + } + + public Float getFloatAt(int columnIndex) throws ColumnFormatException, IndexOutOfBoundsException { + checkBounds(columnIndex); + checkColumnType(columnIndex, Float.class); + return (Float) columns.get(columnIndex); + } + + public Double getDoubleAt(int columnIndex) throws ColumnFormatException, IndexOutOfBoundsException { + checkBounds(columnIndex); + checkColumnType(columnIndex, Double.class); + return (Double) columns.get(columnIndex); + } + + public Boolean getBooleanAt(int columnIndex) throws ColumnFormatException, IndexOutOfBoundsException { + checkBounds(columnIndex); + checkColumnType(columnIndex, Boolean.class); + return (Boolean) columns.get(columnIndex); + } + + @Override + public String toString() { + return LocalUtils.join(columns); + } + + public void setColumns(List values) throws ColumnFormatException, IndexOutOfBoundsException { + if (values.size() != classes.size()) { + throw new IndexOutOfBoundsException(); + } + + columns.clear(); + + for (int index = 0; index < values.size(); ++index) { + columns.add(values.get(index)); + } + } + + public void setColumnAt(int columnIndex, Object value) throws ColumnFormatException, IndexOutOfBoundsException { + checkBounds(columnIndex); + if (value != null) { + checkColumnType(columnIndex, value.getClass()); + try { + LocalUtils.checkValue(value, value.getClass()); + } catch(ParseException e) { + throw new IllegalArgumentException("incorrect value: " + value.toString()); + } + } + columns.set(columnIndex, value); + } + + public void addColumn(Class columnType) { + classes.add(columnType); + columns.add(null); + } + + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRowTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRowTest.java new file mode 100644 index 000000000..bcf15c7e3 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRowTest.java @@ -0,0 +1,64 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import ru.fizteh.fivt.storage.structured.ColumnFormatException; +import ru.fizteh.fivt.storage.structured.Storeable; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.storable.DatabaseRow; + +import java.util.ArrayList; +import java.util.List; + +public class DatabaseRowTest { + Storeable storeable; + + @Before + public void setUp() { + List> columnTypes = new ArrayList<>(); + columnTypes.add(Integer.class); + columnTypes.add(String.class); + storeable = new DatabaseRow(columnTypes); + } + + @After + public void tearDown() throws Exception { + storeable = null; + } + + + @Test(expected = IndexOutOfBoundsException.class) + public void putValueOutOfBound() { + storeable.setColumnAt(3, null); + } + + @Test + public void putNullValueShouldPass() { + storeable.setColumnAt(0, null); + storeable.setColumnAt(1, null); + } + + @Test(expected = ColumnFormatException.class) + public void putIncorrectType1ShouldFail() { + storeable.setColumnAt(0, "adasda"); + } + + @Test(expected = ColumnFormatException.class) + public void putIncorrectType2ShouldFail() { + storeable.setColumnAt(1, 2); + } + + @Test(expected = ColumnFormatException.class) + public void putIncorrectType3ShouldFail() { + storeable.setColumnAt(1, new SimpleClass()); + } + + @Test + public void putCorrectValueShouldPass() throws Exception { + storeable.setColumnAt(1, "String"); + } +} + +class SimpleClass { +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTable.java new file mode 100644 index 000000000..1ce958cac --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTable.java @@ -0,0 +1,160 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.text.ParseException; +import java.util.List; +import java.util.Set; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.SomeStorage; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap.MultiFileMapReadingUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap.MultiFileMapWritingUtils; +import ru.fizteh.fivt.storage.structured.ColumnFormatException; +import ru.fizteh.fivt.storage.structured.Storeable; +import ru.fizteh.fivt.storage.structured.Table; + +public class DatabaseTable extends SomeStorage implements Table { + + DatabaseTableProvider provider; + private List> columnTypes; + + public DatabaseTable(DatabaseTableProvider provider, String databaseDir, String name, List> columnTypes) { + super(databaseDir, name); + if (columnTypes == null || columnTypes.isEmpty()) { + throw new IllegalArgumentException ("column types cannot be null"); + } + this.columnTypes = columnTypes; + this.provider = provider; + try{ + checkTableDirectory(); + load(); + } catch(IOException e) { + throw new IllegalArgumentException("invalid file format"); + } + } + + public Storeable get(String key) { + return getFromStorage(key); + } + + public Storeable put(String key, Storeable value) throws ColumnFormatException { + if (key != null) { + if (LocalUtils.checkStringCorrect(key)) { + throw new IllegalArgumentException("key cannot be empty"); + } + } else if (key == null) { + throw new IllegalArgumentException("key can't be null"); + } + + if (value == null) { + throw new IllegalArgumentException("value cannot be null"); + } + + if (!checkAlienStoreable(value)) { + throw new ColumnFormatException("alien storeable"); + } + isStoreableCorrect(value); + return putIntoStorage(key, value); + } + + public Storeable remove(String key) { + return removeFromStorage(key); + } + + public int size() { + return sizeOfStorage(); + } + + public int commit() throws IOException { + return commitStorage(); + } + + public int rollback() { + return rollbackStorage(); + } + + public int getColumnsCount() { + return columnTypes.size(); + } + + public Class getColumnType(int columnIndex) throws IndexOutOfBoundsException { + if (columnIndex < 0 || columnIndex > getColumnsCount()) { + throw new IndexOutOfBoundsException(); + } + return columnTypes.get(columnIndex); + } + + protected void load() throws IOException { + if (provider == null) { + return; + } + MultiFileMapReadingUtils.load(new StoreableTableBuilder(provider, this)); + } + + protected void save() throws IOException { + MultiFileMapWritingUtils.save(new StoreableTableBuilder(provider, this)); + } + + private void checkTableDirectory() throws IOException { + File tableDirectory = new File(getParentDirectory(), getName()); + if (!tableDirectory.exists()) { + tableDirectory.mkdir(); + writeSignatureFile(); + } else { + File[] children = tableDirectory.listFiles(); + if (children == null || children.length == 0) { + throw new IllegalArgumentException(String.format("table directory: %s is empty", tableDirectory.getAbsolutePath())); + } + } + } + + private void writeSignatureFile() throws IOException { + File tableDirectory = new File(getParentDirectory(), getName()); + File signatureFile = new File(tableDirectory, DatabaseTableProvider.SIGNATURE_FILE); + signatureFile.createNewFile(); + BufferedWriter writer = new BufferedWriter(new FileWriter(signatureFile)); + List formattedColumnTypes = LocalUtils.formatColumnTypes(columnTypes); + String signature = LocalUtils.join(formattedColumnTypes); + writer.write(signature); + writer.close(); + } + + + public boolean checkAlienStoreable(Storeable storeable) { + for (int index = 0; index < getColumnsCount(); ++index) { + try { + Object o = storeable.getColumnAt(index); + if (o == null) { + continue; + } + if (!o.getClass().equals(getColumnType(index))) { + return false; + } + } catch (IndexOutOfBoundsException e) { + return false; + } + } + try { + storeable.getColumnAt(getColumnsCount()); + } catch (IndexOutOfBoundsException e) { + return true; + } + return false; + } + + Set rawGetKeys() { + return unchangedOldData.keySet(); + } + + public void isStoreableCorrect(Storeable storeable) { + for (int index = 0; index < getColumnsCount(); ++index) { + try { + LocalUtils.checkValue(storeable.getColumnAt(index), columnTypes.get(index)); + } catch (ParseException e) { + throw new IllegalArgumentException(e); + } + } + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java new file mode 100644 index 000000000..172801347 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java @@ -0,0 +1,249 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map.Entry; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap.MultifileTable; +import ru.fizteh.fivt.storage.structured.ColumnFormatException; +import ru.fizteh.fivt.storage.structured.Storeable; +import ru.fizteh.fivt.storage.structured.Table; +import ru.fizteh.fivt.storage.structured.TableProvider; + + +public class DatabaseTableProvider implements TableProvider { + static final String SIGNATURE_FILE = "signature.tsv"; + private static final String CHECKER = "[0-9A-Za-zА-Яа-я]+"; + private final Lock tableLock = new ReentrantLock(true); + + HashMap tables = new HashMap(); + private String databaseDirPath; + private DatabaseTable currentTable = null; + + public DatabaseTableProvider(String databaseDirPath) { + if (databaseDirPath == null) { + throw new IllegalArgumentException ("path to database can not be null"); + } + + this.databaseDirPath = databaseDirPath; + File databaseDir = new File(databaseDirPath); + if (databaseDir.isFile()) { + throw new IllegalArgumentException("database dir cannot be file"); + } + for (File tableFile : databaseDir.listFiles()) { + if (tableFile.isFile()) { + continue; + } + List> columnTypes = readTableSignature(tableFile.getName()); + if (columnTypes == null) { + throw new IllegalArgumentException("table directory is empty"); + } + DatabaseTable table = new DatabaseTable(this, databaseDirPath, tableFile.getName(), columnTypes); + tables.put(table.getName(), table); + } + } + + public Table getTable(String name) { + try { + tableLock.lock(); + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("table cannot be null"); + } + checkTableName(name); + DatabaseTable table = tables.get(name); + if (table == null) { + return null; + } + if (currentTable != null && currentTable.getChangesCounter() > 0) { + throw new IllegalStateException (currentTable.getChangesCounter() + " unsaved changes"); + } + currentTable = table; + return table; + } finally { + tableLock.unlock(); + } + } + + public Table createTable(String name, List> columnTypes) throws IOException { + try { + tableLock.lock(); + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("table's name cannot be null"); + } + checkTableName(name); + if (columnTypes == null || columnTypes.isEmpty()) { + throw new IllegalArgumentException("wrong type ()"); + } + checkColumnTypes(columnTypes); + if (tables.containsKey(name)) { + return null; + } + DatabaseTable table = new DatabaseTable(this, databaseDirPath, name, columnTypes); + tables.put(name, table); + return table; + } finally { + tableLock.unlock(); + } + } + + public void removeTable(String name) throws IOException { + try { + tableLock.lock(); + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("table's name cannot be null"); + } + + if (!tables.containsKey(name)) { + throw new IllegalStateException(name + " not exists"); + } + if (currentTable != null) { + if (currentTable.getName().equals(name)) { + currentTable = null; + } + } + tables.remove(name); + File tableFile = new File(databaseDirPath, name); + GlobalUtils.deleteFile(tableFile); + } finally { + tableLock.unlock(); + } + } + + public HashMap showTables() { + HashMap content = new HashMap(); + for (Entry contents : tables.entrySet()) { + content.put(contents.getKey(), contents.getValue().size()); + } + return content; + } + + public String serialize(Table table, Storeable value) throws ColumnFormatException { + if (value == null) { + throw new IllegalArgumentException("value cannot be null"); + } + try { + XmlSerializer xmlSerializer = new XmlSerializer(); + for (int index = 0; index < table.getColumnsCount(); ++index) { + xmlSerializer.write(value.getColumnAt(index)); + } + xmlSerializer.close(); + return xmlSerializer.getRepresentation(); + } catch (IOException e) { + System.err.println(e.getMessage()); + } catch (ParseException e) { + throw new IllegalArgumentException("incorrect value"); + } + return null; + } + + + public Storeable deserialize(Table table, String val) throws ParseException { + if (val == null || val.isEmpty()) { + throw new IllegalArgumentException("value cannot be null or empty"); + } + XmlDeserializer deserializer = new XmlDeserializer(val); + Storeable result = null; + List values = new ArrayList<>(table.getColumnsCount()); + for (int index = 0; index < table.getColumnsCount(); ++index) { + try { + Class expectedType = table.getColumnType(index); + Object columnValue = deserializer.getNext(expectedType); + LocalUtils.checkValue(columnValue, expectedType); + values.add(columnValue); + } catch (ColumnFormatException e) { + throw new ParseException("incompatible type: " + e.getMessage(), index); + } catch (IndexOutOfBoundsException e) { + throw new ParseException("Xml representation doesn't match the format", index); + } + } + try { + deserializer.close(); + result = createFor(table, values); + } catch (ColumnFormatException e) { + throw new ParseException("incompatible types: " + e.getMessage(), 0); + } catch (IndexOutOfBoundsException e) { + throw new ParseException("Xml representation doesn't match the format", 0); + } catch (IOException e) { + throw new ParseException(e.getMessage(), 0); + } + return result; + } + + public Storeable createFor(Table table) { + return rawCreateFor(table); + } + + public Storeable createFor(Table table, List values) throws ColumnFormatException, IndexOutOfBoundsException { + if (values == null) { + throw new IllegalArgumentException("values cannot be null"); + } + DatabaseRow row = rawCreateFor(table); + row.setColumns(values); + return row; + } + + private DatabaseRow rawCreateFor(Table table) { + DatabaseRow row = new DatabaseRow(); + for (int index = 0; index < table.getColumnsCount(); ++index) { + row.addColumn(table.getColumnType(index)); + } + return row; + } + + + private List> readTableSignature(String tableName) { + File tableDirectory = new File(databaseDirPath, tableName); + File signatureFile = new File(tableDirectory, SIGNATURE_FILE); + String signature = null; + if (!signatureFile.exists()) { + return null; + } + try (BufferedReader reader = new BufferedReader(new FileReader(signatureFile))) { + signature = reader.readLine(); + } catch (IOException e) { + System.err.println("error loading signature file: " + e.getMessage()); + return null; + } + if (signature == null) { + throw new IllegalArgumentException("incorrect signature file"); + } + List> columnTypes = new ArrayList>(); + for (final String columnType : signature.split("\\s+")) { + Class type = StoreableTypes.getTypeByName(columnType); + if (type == null) { + throw new IllegalArgumentException("wrong type (" + columnType + ')'); + } + columnTypes.add(type); + } + return columnTypes; + } + + private boolean checkCorrectTable(File tableDirectory) { + File signatureFile = new File(tableDirectory, SIGNATURE_FILE); + return signatureFile.exists(); + } + + private void checkColumnTypes(List> columnTypes) { + for (final Class columnType : columnTypes) { + if (columnType == null) { + throw new IllegalArgumentException("wrong type ()"); + } + StoreableTypes.getSimpleName(columnType); + } + } + + private void checkTableName(String name) { + if (!name.matches(CHECKER)) { + throw new IllegalArgumentException("Bad symbol!"); + } + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactory.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactory.java new file mode 100644 index 000000000..c4e20c3c8 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactory.java @@ -0,0 +1,33 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import java.io.File; +import java.io.IOException; + + +import ru.fizteh.fivt.storage.structured.TableProvider; +import ru.fizteh.fivt.storage.structured.TableProviderFactory; + +public class DatabaseTableProviderFactory implements TableProviderFactory { + + public synchronized TableProvider create(String directory) throws IOException { + if (directory == null) { + throw new IllegalArgumentException("directory cannot be null"); + } + + if (directory.trim().isEmpty()) { + throw new IllegalArgumentException("directory's name cannot be empty"); + } + + File databaseDirectory = new File(directory); + if (databaseDirectory.isFile()) { + throw new IllegalArgumentException("cannot create database in file. Provide a directory, please"); + } + + if (!databaseDirectory.exists()) { + if (!databaseDirectory.mkdir()) { + throw new IOException("provider is unavailable"); + } + } + return new DatabaseTableProvider(databaseDirectory.getAbsolutePath()); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactoryTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactoryTest.java new file mode 100644 index 000000000..3b5b2ea76 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactoryTest.java @@ -0,0 +1,20 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import org.junit.Test; + +import ru.fizteh.fivt.storage.structured.TableProviderFactory; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.storable.DatabaseTableProviderFactory; + +import java.io.IOException; + +public class DatabaseTableProviderFactoryTest { + @Test(expected = IllegalArgumentException.class) + public void createProviderNullDirectoryTest() { + TableProviderFactory factory = new DatabaseTableProviderFactory(); + try { + factory.create(null); + } catch (IOException e) { + // + } + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderTest.java new file mode 100644 index 000000000..a64438d5c --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderTest.java @@ -0,0 +1,27 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + + +import org.junit.Test; + +import ru.fizteh.fivt.storage.structured.TableProviderFactory; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.storable.DatabaseTableProviderFactory; + +import java.io.IOException; + +public class DatabaseTableProviderTest { + TableProviderFactory factory = new DatabaseTableProviderFactory(); + + @Test(expected = IOException.class) + public void createProviderUnavailableShouldFail() throws IOException { + factory.create("M:\\"); + } + + @Test(expected = IllegalArgumentException.class) + public void createProviderEmptyShouldFail() { + try { + factory.create(""); + } catch (IOException e) { + + } + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableTest.java new file mode 100644 index 000000000..f7f717b78 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableTest.java @@ -0,0 +1,86 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + + +import org.junit.*; +import java.io.IOException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import ru.fizteh.fivt.storage.structured.Storeable; +import ru.fizteh.fivt.storage.structured.Table; +import ru.fizteh.fivt.storage.structured.TableProvider; + +public class DatabaseTableTest { + private static final String DATABASE = "C:\\temp\\storeable_test"; + TableProvider provider; + Table currentTable; + + @Before + public void beforeTest() { + DatabaseTableProviderFactory factory = new DatabaseTableProviderFactory(); + try { + provider = factory.create(DATABASE); + } catch (IOException e) { + + } + + List> columnTypes = new ArrayList<>(); + columnTypes.add(Integer.class); + columnTypes.add(String.class); + try { + currentTable = provider.createTable("testTable", columnTypes); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @After + public void afterTest() { + try { + provider.removeTable("testTable"); + } catch (IOException e) { + // SAD + } + } + + @Test + public void putRemoveShouldNotFail() throws Exception { + currentTable.commit(); + currentTable.put("key1", provider.deserialize(currentTable, getXml(1, "2"))); + currentTable.remove("key1"); + Assert.assertEquals(0, currentTable.commit()); + } + + @Test(expected = ParseException.class) + public void putEmptyValueTest() throws ParseException { + Storeable smth = provider.deserialize(currentTable, getXml(1, "")); + } + + /*@Test(expected = ParseException.class) + public void putNlValueTest() throws ParseException { + Storeable smth = provider.deserialize(currentTable, getXml(1, " ")); + }*/ + + @Test(expected = IllegalArgumentException.class) + public void putNlKeyShouldFail() { + currentTable.put(" ", provider.createFor(currentTable)); + } + + + /*@Test(expected = IllegalArgumentException.class) + public void testPutValueWithWhiteSpaces() + { + Storeable newValue = provider.createFor(currentTable); + DatabaseRow row = (DatabaseRow) newValue; + List values = new ArrayList() {{ + add(1); + add(" "); + }}; + row.setColumns(values); + currentTable.put("somekey", row); + }*/ + + private String getXml(int value1, String value2) { + return String.format("%d%s", value1, value2); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/LocalUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/LocalUtils.java new file mode 100644 index 000000000..b1544fa23 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/LocalUtils.java @@ -0,0 +1,86 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Parser; +import ru.fizteh.fivt.storage.structured.ColumnFormatException; +import ru.fizteh.fivt.storage.structured.Table; + +public class LocalUtils { + public static List parseValues(List valuesRepresentation, Table table) throws ColumnFormatException { + List values = new ArrayList<>(valuesRepresentation.size() - 1); + + for (int index = 1; index < valuesRepresentation.size(); ++index) { + Object value = StoreableTypes.parseByClass(valuesRepresentation.get(index), table.getColumnType(index - 1)); + values.add(value); + } + return values; + } + + public static String join(List list) { + StringBuilder sb = new StringBuilder(); + boolean first = true; + for (final Object listEntry : list) { + if (!first) { + sb.append(" "); + } + first = false; + if (listEntry == null) { + sb.append("null"); + } else { + sb.append(listEntry.toString()); + } + } + return sb.toString(); + } + + public static TableInfo parseCreateCommand(String parameters) throws IllegalArgumentException { + parameters = parameters.trim(); + String tableName = parameters.split("\\s+")[0]; + parameters = parameters.replaceAll("\\s+", " "); + int spaceIndex = parameters.indexOf(' '); + if (spaceIndex == -1) { + throw new IllegalArgumentException("wrong type (no column types)"); + } + String columnTypesString = parameters.substring(spaceIndex).replaceAll("\\((.*)\\)", "$1"); + List columnTypes = Parser.parseCommandArgs(columnTypesString); + + TableInfo info = new TableInfo(tableName); + for (final String columnType : columnTypes) { + info.addColumn(StoreableTypes.getTypeByName(columnType)); + } + + return info; + } + + public static List formatColumnTypes(List> columnTypes) { + List formattedColumnTypes = new ArrayList(); + for (final Class columnType : columnTypes) { + formattedColumnTypes.add(StoreableTypes.getSimpleName(columnType)); + } + return formattedColumnTypes; + } + + public static void checkValue(Object value, Class type) throws ParseException { + if (value == null) { + return; + } + //String t = StoreableTypes.getSimpleName(type); + switch (StoreableTypes.getSimpleName(type)) { + case "String": + String stringValue = (String) value; + /*if (checkStringCorrect(stringValue)) + throw new ParseException("value cannot be null", 0);*/ + break; + } + } + + public static boolean checkStringCorrect(String string) { + + return (string.matches("\\s*") || string.split("\\s+").length != 1); + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableMain.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableMain.java new file mode 100644 index 000000000..73b8ee831 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableMain.java @@ -0,0 +1,58 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap.CreateCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap.DropCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap.UseCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.CommitCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.ExitCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GetCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.PutCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.RemoveKeyCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.RollbackCommand; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Commands; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Shell; +import ru.fizteh.fivt.storage.structured.Storeable; +import ru.fizteh.fivt.storage.structured.Table; + +public class StorableMain { + public static void main(String[] args) { + List> commands = new ArrayList>(); + HashSet> com = new HashSet>() {{ + add(new ExitCommand()); + add(new RollbackCommand()); + add(new CommitCommand()); + add(new PutCommand()); + add(new GetCommand()); + add(new RemoveKeyCommand()); + add(new DropCommand()); + add(new UseCommand()); + add(new CreateCommand());}}; + commands.addAll(com); + HashSet> actualResult = new HashSet>(commands); + Shell shell = new Shell(actualResult); + String databaseDirectory = System.getProperty("fizteh.db.dir"); + + if (databaseDirectory == null) { + System.err.println("You haven't set database directory"); + System.exit(1); + } + + try { + DatabaseTableProviderFactory factory = new DatabaseTableProviderFactory(); + StorableShellState shellState = new StorableShellState(factory.create(databaseDirectory)); + shell.setShellState(shellState); + } catch (IOException e) { + System.err.println("some error occurred during loading"); + System.exit(1); + } catch (IllegalArgumentException e) { + System.err.println("error while loading: " + e.getMessage()); + System.exit(1); + } + shell.run(args, shell); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableShellState.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableShellState.java new file mode 100644 index 000000000..76599dec7 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableShellState.java @@ -0,0 +1,105 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import java.io.IOException; + +import ru.fizteh.fivt.storage.structured.Storeable; +import ru.fizteh.fivt.storage.structured.Table; +import ru.fizteh.fivt.storage.structured.TableProvider; + +import java.text.ParseException; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap.MultifileMapShellStateInterface; + +public class StorableShellState implements MultifileMapShellStateInterface { + Table table; + TableProvider tableProvider; + + public StorableShellState(TableProvider provider) { + tableProvider = provider; + } + + + public Storeable put(String key, Storeable value) { + return table.put(key, value); + } + + public Storeable get(String key) { + return table.get(key); + } + + public int commit() { + try { + return table.commit(); + } catch (IOException e) { + return -1; + } + } + + public int rollback() { + return table.rollback(); + } + + public int size() { + return table.size(); + } + + public Storeable remove(String key) { + return table.remove(key); + } + + public Table getTable() { + return table; + } + + public String keyToString(String key) { + return key; + } + + public String valueToString(Storeable value) { + String string = tableProvider.serialize(table, value); + return string; + } + + public String parseKey(String key) { + return key; + } + + public Storeable parseValue(String value) { + try { + return tableProvider.deserialize(table, value); + } catch (ParseException e) { + return null; + } + } + + public Table useTable(String name) { + Table temp = tableProvider.getTable(name); + if (temp != null) { + table = temp; + } + return temp; + } + + public Table createTable(String arguments) { + TableInfo info = null; + info = LocalUtils.parseCreateCommand(arguments); + try { + return tableProvider.createTable(info.getName(), info.getColumnsTypes()); + } catch (IOException e) { + return null; + } + } + + public void dropTable(String name) throws IOException { + tableProvider.removeTable(name); + if (table.getName().equals(name)) { + table = null; + } + + } + + public String getCurrentTableName() { + return table.getName(); + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTableBuilder.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTableBuilder.java new file mode 100644 index 000000000..ee5380c63 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTableBuilder.java @@ -0,0 +1,61 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import java.io.File; +import java.text.ParseException; +import java.util.Set; + +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; +import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableBuilder; +import ru.fizteh.fivt.storage.structured.ColumnFormatException; +import ru.fizteh.fivt.storage.structured.Storeable; + +public class StoreableTableBuilder implements TableBuilder { + DatabaseTableProvider provider; + DatabaseTable table; + + private int currentDir; + private int currentFile; + + public StoreableTableBuilder(DatabaseTableProvider provider, DatabaseTable table) { + this.provider = provider; + this.table = table; + } + + public String get(String key) { + Storeable val = table.get(key); + try { + String presentation = provider.serialize(table, val); + return presentation; + } catch (ColumnFormatException e) { + return null; + } + } + + public void put(String key, String value) { + GlobalUtils.checkKeyPlacement(key, currentDir, currentFile); + + Storeable objectValue = null; + try { + objectValue = provider.deserialize(table, value); + } catch (ParseException e) { + System.err.println(e.getMessage()); + } + table.put(key, objectValue); + + } + + public Set getKeys() { + return table.rawGetKeys(); + } + + public File getTableDirectory() { + return new File(table.getParentDirectory(), table.getName()); + } + + public void setCurrentFile(File curFile) { + currentDir = GlobalUtils.parseDirNumber(curFile.getParentFile()); + currentFile = GlobalUtils.parseFileNumber(curFile); + + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTypes.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTypes.java new file mode 100644 index 000000000..956b531dc --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTypes.java @@ -0,0 +1,97 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public enum StoreableTypes { + + INTEGER("int", Integer.class) { + public Object ParseValue(String arg) { + return Integer.parseInt(arg); + } + }, + + LONG("long", Long.class) { + public Object ParseValue(String arg) { + return Long.parseLong(arg); + } + }, + + FLOAT("float", Float.class) { + public Object ParseValue(String arg) { + return Float.parseFloat(arg); + } + }, + + DOUBLE("double", Double.class) { + public Object ParseValue(String arg) { + return Double.parseDouble(arg); + } + }, + + STRING("String", String.class) { + public Object ParseValue(String arg) { + return arg; + } + }, + + BYTE("byte", Byte.class) { + public Object ParseValue(String arg) { + return Byte.parseByte(arg); + } + }, + + BOOLEAN("boolean", Boolean.class) { + public Object ParseValue(String arg) { + return Boolean.parseBoolean(arg); + } + }; + + private final String name; + private final Class type; + + private StoreableTypes(String name, Class type) { + this.name = name; + this.type = type; + } + + private static final Map typesByName; + private static final Map, StoreableTypes> typesByClass; + + static { + HashMap tempByName = new HashMap<>(); + HashMap, StoreableTypes> tempByClass = new HashMap<>(); + for (StoreableTypes value : values()) { + tempByName.put(value.name, value); + tempByClass.put(value.type, value); + } + typesByName = Collections.unmodifiableMap(tempByName); + typesByClass = Collections.unmodifiableMap(tempByClass); + } + public static Class getTypeByName(String name) { + StoreableTypes formatter = typesByName.get(name); + if (formatter == null) { + throw new IllegalArgumentException("wrong type (" + name + ')'); + } + return formatter.type; + } + + public static String getSimpleName(Class type) { + StoreableTypes formatter = typesByClass.get(type); + if (formatter == null) { + throw new IllegalArgumentException("unknown format"); + } + return formatter.name; + } + + public abstract Object ParseValue(String string); + + public static Object parseByClass(String string, Class type) { + StoreableTypes formatter = typesByClass.get(type); + if (formatter == null) { + throw new IllegalArgumentException ("wrong type (" + type + ')'); + } + return formatter.ParseValue(string); + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/TableInfo.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/TableInfo.java new file mode 100644 index 000000000..66d82981a --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/TableInfo.java @@ -0,0 +1,27 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import java.util.ArrayList; +import java.util.List; + +public class TableInfo { + private String name; + private List> typesOfColumns; + + public TableInfo(String name) { + this.name = name; + this.typesOfColumns = new ArrayList>(); + } + + public void addColumn(Class columnType) { + typesOfColumns.add(columnType); + } + + public List> getColumnsTypes() { + return typesOfColumns; + } + + public String getName() { + return name; + } + +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlDeserializer.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlDeserializer.java new file mode 100644 index 000000000..36983b7cc --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlDeserializer.java @@ -0,0 +1,82 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import java.io.IOException; +import java.io.StringReader; +import java.text.ParseException; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import ru.fizteh.fivt.storage.structured.ColumnFormatException; + +public class XmlDeserializer { + String representation; + XMLStreamReader reader; + + public XmlDeserializer(String representation) throws ParseException { + this.representation = representation; + try { + reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(representation)); + if (!reader.hasNext()) { + throw new ParseException("xml presentation is empty", 0); + } + int type = reader.next(); + if (type != XMLStreamConstants.START_ELEMENT) { + throw new ParseException("incorrect xml", 0); + } + if (!reader.getName().getLocalPart().equals("row")) { + throw new ParseException("incorrect xml", 0); + } + + } catch (XMLStreamException e) { + throw new ParseException("error in deserializer: " + e.getMessage(), 0); + } + } + + public Object getNext(Class typeExpected) throws ColumnFormatException, ParseException { + Object val = null; + try { + int type = reader.next(); + String k = reader.getName().getLocalPart(); + if(type != XMLStreamConstants.START_ELEMENT || !k.equals("col")) { + if (type == XMLStreamConstants.START_ELEMENT && k.equals("null")) { + reader.next(); + return val; + } + throw new ParseException ("incorrect xml", 0); + } + type = reader.next(); + if (type == XMLStreamConstants.CHARACTERS) { + val = StoreableTypes.parseByClass(reader.getText(), typeExpected); + } else { + if (!reader.getName().getLocalPart().equals("null")) { + throw new ParseException("incorrect xml", 0); + } + val = null; + type = reader.next(); + if (type != XMLStreamConstants.END_ELEMENT) { + throw new ParseException("incorrect xml", 0); + } + } + type = reader.next(); + if (type != XMLStreamConstants.END_ELEMENT) { + throw new ParseException("incorrect xml", 0); + } + } catch (XMLStreamException e) { + throw new ParseException("error in deserializer: " + e.getMessage(), 0); + } + return val; + } + + public void close() throws ParseException, IOException { + try { + int type = reader.next(); + if (type != XMLStreamConstants.END_ELEMENT && type != XMLStreamConstants.END_DOCUMENT) { + throw new ParseException("incorrect xml", 0); + } + } catch (XMLStreamException e) { + throw new IOException("error while deserializing: " + e.getMessage()); + } + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlSerializer.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlSerializer.java new file mode 100644 index 000000000..0c9958ef2 --- /dev/null +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlSerializer.java @@ -0,0 +1,52 @@ +package ru.fizteh.fivt.students.NikolaiKrivchanskii.storable; + +import java.io.IOException; +import java.io.StringWriter; +import java.text.ParseException; + +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +public class XmlSerializer { + StringWriter strWriter = new StringWriter(); + XMLStreamWriter writer = null; + + public XmlSerializer() throws IOException { + XMLOutputFactory factory = XMLOutputFactory.newInstance(); + try { + writer = factory.createXMLStreamWriter(strWriter); + writer.writeStartElement("row"); + } catch (XMLStreamException e) { + throw new IOException("error while serializing: " + e.getMessage()); + } + } + + public void write(Object value) throws IOException, ParseException { + try { + writer.writeStartElement("col"); + if (value == null) { + writer.writeStartElement("null"); + writer.writeEndElement(); + } else { + writer.writeCharacters(value.toString()); + } + writer.writeEndElement(); + } catch (XMLStreamException e) { + throw new IOException("error while serializing: " + e.getMessage()); + } + } + + public void close() throws IOException { + try { + writer.writeEndElement(); + writer.flush(); + } catch (XMLStreamException e) { + throw new IOException("error while serializing: " + e.getMessage()); + } + } + + public String getRepresentation() { + return strWriter.getBuffer().toString(); + } +} From 0a982a290c563ea90e01627e4a6a31da41642002 Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Tue, 16 Dec 2014 03:02:31 +0400 Subject: [PATCH 12/14] =?UTF-8?q?=D0=9D=D0=B5=D0=B4=D0=BE=D1=87=D1=91?= =?UTF-8?q?=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../NikolaiKrivchanskii/filemap/ListCommand.java | 4 ++-- .../students/NikolaiKrivchanskii/filemap/MyTable.java | 5 +++-- .../NikolaiKrivchanskii/filemap/SomeStorage.java | 11 ++++++----- .../NikolaiKrivchanskii/filemap/SomeTable.java | 8 ++++---- .../filemap/TableUsingStrings.java | 6 +++--- .../storable/DatabaseTableProvider.java | 1 + 6 files changed, 19 insertions(+), 16 deletions(-) diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java index b53e6807b..9e198891e 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java @@ -1,7 +1,7 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; import java.util.ArrayList; -import java.util.Set; +import java.util.List; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; @@ -25,7 +25,7 @@ public void implement(String args, FileMapShellState state) throw new SomethingIsWrongException("This command takes no parameters"); } MyTable temp = (MyTable) state.table; - Set keySet = temp.list(); + List keySet = temp.list(); if (keySet.size() == 0) { System.out.println("\n"); return; diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java index ddeafc5c6..8af5d75fb 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/MyTable.java @@ -1,6 +1,7 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import java.util.Set; +import java.util.List; + import ru.fizteh.fivt.storage.strings.Table; public interface MyTable extends Table { @@ -8,7 +9,7 @@ public interface MyTable extends Table { void setAutoCommit(boolean status); boolean getAutoCommit(); int getChangesCounter(); - Set list(); + List list(); String get(String a); String put(String key, String value); String remove(String a); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java index 08451c15c..b7ef300fb 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java @@ -3,6 +3,8 @@ import java.io.IOException; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -85,10 +87,9 @@ public Value getVal(Key key) { return unchangedOldData.get(key); } - public HashSet getKeys() { - HashSet result = new HashSet(); - result.addAll(currentData.keySet()); - return result; + public List getKeys() { + List toReturnSafe = new LinkedList(currentData.keySet()); + return toReturnSafe; } public int getSize() { @@ -158,7 +159,7 @@ public Value getFromStorage(Key key) { return transaction.get().getVal(key); } - public Set getAllKeys() { + public List getAllKeys() { return transaction.get().getKeys(); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java index 81d2ea819..cdaae90df 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeTable.java @@ -2,9 +2,10 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; - import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; import java.util.Set; @@ -29,9 +30,8 @@ public boolean getAutoCommit() { return autoCommit; } - public Set list() { - Set toReturnSafe = new HashSet(); - toReturnSafe = currentData.keySet(); + public List list() { + List toReturnSafe = new LinkedList(currentData.keySet()); return toReturnSafe; } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java index 44924e793..dc8c31173 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java @@ -1,7 +1,7 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; -import java.util.HashSet; -import java.util.Set; + +import java.util.List; public abstract class TableUsingStrings extends SomeStorage implements MyTable { protected TableUsingStrings(String dir, String name) { @@ -32,7 +32,7 @@ public int commit() { return commitStorage(); } - public Set list() { + public List list() { return getAllKeys(); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java index 172801347..879d3ec11 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java @@ -7,6 +7,7 @@ import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.locks.Lock; From 3add65d9f9435d3f445a17b8536484ef3bc8de3f Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Tue, 16 Dec 2014 07:28:41 +0400 Subject: [PATCH 13/14] Travis --- .../NikolaiKrivchanskii/Shell/Commands.java | 2 +- .../NikolaiKrivchanskii/Shell/Shell.java | 86 ++---- .../filemap/CommitCommand.java | 2 +- .../filemap/ExitCommand.java | 34 +-- .../filemap/GetCommand.java | 5 +- .../filemap/ListCommand.java | 2 +- .../filemap/PutCommand.java | 19 +- .../filemap/RemoveKeyCommand.java | 13 +- .../filemap/RollbackCommand.java | 4 +- .../filemap/SimpleTableBuilder.java | 48 +-- .../filemap/SizeCommand.java | 29 +- .../filemap/SomeStorage.java | 227 +++++++------- .../filemap/TableUsingStrings.java | 62 ++-- .../multifilemap/CreateCommand.java | 49 +-- .../multifilemap/Database.java | 53 ++-- .../multifilemap/DatabaseFactory.java | 20 +- .../multifilemap/DatabaseTest.java | 4 +- .../multifilemap/DropCommand.java | 44 +-- .../MultiFileMapReadingUtils.java | 44 +-- .../multifilemap/MultiFileMapShellState.java | 3 +- .../MultiFileMapTableBuilder.java | 34 +-- .../MultiFileMapTableProviderClass.java | 4 +- .../MultiFileMapWritingUtils.java | 80 ++--- .../multifilemap/MultifileMapMain.java | 38 +-- .../MultifileMapShellStateInterface.java | 17 +- .../multifilemap/MultifileTable.java | 30 +- .../multifilemap/MultifileTableTest.java | 5 +- .../multifilemap/ShowTablesCommand.java | 38 +-- .../multifilemap/UseCommand.java | 45 +-- .../storable/DatabaseRow.java | 64 ++-- .../storable/DatabaseRowTest.java | 1 - .../storable/DatabaseTable.java | 234 ++++++++------- .../storable/DatabaseTableProvider.java | 282 +++++++++--------- .../DatabaseTableProviderFactory.java | 3 +- .../DatabaseTableProviderFactoryTest.java | 3 +- .../storable/DatabaseTableProviderTest.java | 5 +- .../storable/DatabaseTableTest.java | 12 +- .../storable/LocalUtils.java | 10 +- .../storable/StorableMain.java | 20 +- .../storable/StorableShellState.java | 160 +++++----- .../storable/StoreableTableBuilder.java | 52 ++-- .../storable/StoreableTypes.java | 178 +++++------ .../storable/TableInfo.java | 40 +-- .../storable/XmlDeserializer.java | 118 ++++---- .../storable/XmlSerializer.java | 12 +- 45 files changed, 1111 insertions(+), 1124 deletions(-) diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java index ba941f5ac..cd74dfe24 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Commands.java @@ -7,5 +7,5 @@ public interface Commands { int getArgumentQuantity(); - abstract void implement(String args, State state) throws SomethingIsWrongException; + void implement(String args, State state) throws SomethingIsWrongException; } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java index 42530a139..9b1380f2c 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/Shell/Shell.java @@ -1,27 +1,23 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; public class Shell { private final Map availableCommands; - private static final String greeting = "$ "; + private static final String GREETING = "$ "; State state; - public Shell (Set> commands) { - Map tempCommands = new HashMap(); + public Shell(Set> commands) { + Map tempCommands = new HashMap(); for (Commands temp : commands) { tempCommands.put(temp.getCommandName(), temp); } @@ -34,44 +30,26 @@ public void setShellState(State state) { private void runCommand(String[] data, State state) throws SomethingIsWrongException { for (String command : data) { - if (data[0].length() == 0) { - throw new SomethingIsWrongException ("Empty string."); - } - String name = Parser.getName(command); - Commands usedOne = availableCommands.get(name); - String args = Parser.getParameters(command); - if (usedOne == null) { - throw new SomethingIsWrongException ("Unknown command."); - } - usedOne.implement(args, state); - } + if (data[0].length() == 0) { + throw new SomethingIsWrongException("Empty string."); + } + String name = Parser.getName(command); + Commands usedOne = availableCommands.get(name); + String args = Parser.getParameters(command); + if (usedOne == null) { + throw new SomethingIsWrongException("Unknown command."); + } + usedOne.implement(args, state); + } } - /* public static String[] splitLine(String str) { - str = str.trim(); - return str.split("(\\s*;\\s*)", -1); - } - private void runLine(String[] line, State state) throws SomethingIsWrongException { - int count = line.length - 1; - for (String temp : line) { - --count; - if (count >= 0) { - runCommand(temp, state); //This thing is needed to check if after last ";" - } else if (count < 0) { //situated a command or an empty string. So it - if (temp.length() != 0) { //won't throw a "Wrong command" exception when it - runCommand(temp, state); //looks like: "dir; cd ..; dir;" neither it will - } //loose a "dir" in: "dir; cd ..; dir; dir". - } //So it does nothing if it is the end, but performs - } //if there is a command after last ";". - }*/ - public void consoleWay(State state) { Scanner forInput = new Scanner(System.in); - while (!Thread.currentThread().isInterrupted()) { - System.out.print(greeting); + while (!Thread.currentThread().isInterrupted()) { + System.out.print(GREETING); try { - String temp = forInput.nextLine(); - String[] commands = Parser.parseFullCommand(temp); + String temp = forInput.nextLine(); + String[] commands = Parser.parseFullCommand(temp); runCommand(commands, state); } catch (SomethingIsWrongException exc) { if (exc.getMessage().equals("EXIT")) { @@ -81,39 +59,15 @@ public void consoleWay(State state) { System.err.println(exc.getMessage()); } } catch (IllegalArgumentException | IllegalStateException e) { - System.err.println(e.getMessage()); + System.err.println(e.getMessage()); } } forInput.close(); } - /*public static void main(String[] args) { - ShellState state = new ShellState(System.getProperty("user.dir")); - Set commands = new HashSet() {{ add(new WhereAreWeCommand()); add(new CopyCommand()); add(new DirectoryInfoCommand()); - add(new ExitCommand()); add(new MakeDirectoryCommand()); add(new MoveCommand()); add(new RemoveCommand()); }}; - Shell shell = new Shell(commands); - - if (args.length != 0) { - String arg = UtilMethods.uniteItems(Arrays.asList(args), " "); - try { - shell.runLine(arg, state); - } catch (SomethingIsWrongException exc) { - if (exc.getMessage().equals("EXIT")) { - System.exit(0); - } else { - System.err.println(exc.getMessage()); - System.exit(-1); - } - } - } else { - shell.consoleWay(state); - } - System.exit(0); - }*/ - public void run(String[] args, Shell shell) { - if (args.length != 0) { + if (args.length != 0) { String arg = UtilMethods.uniteItems(Arrays.asList(args), " "); String[] commands = Parser.parseFullCommand(arg); try { diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java index 08e13570d..dd4152169 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/CommitCommand.java @@ -16,7 +16,7 @@ public int getArgumentQuantity() { public void implement(String args, State state) throws SomethingIsWrongException { if (state.getTable() == null) { - throw new SomethingIsWrongException ("no table"); + throw new SomethingIsWrongException("no table"); } System.out.println(state.commit()); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java index dcc6ba810..6313c8a25 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ExitCommand.java @@ -3,25 +3,25 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; -public class ExitCommand extends SomeCommand{ +public class ExitCommand extends SomeCommand { - public String getCommandName() { - return "exit"; - } + public String getCommandName() { + return "exit"; + } - public int getArgumentQuantity() { - return 0; - } + public int getArgumentQuantity() { + return 0; + } - public void implement(String args, State state) - throws SomethingIsWrongException { - /*MyTable temp = (MyTable) state.getTable();*/ - if (state.getTable() != null /*&& !temp.getAutoCommit()*/) { - state.rollback(); - }/* else if (temp.getAutoCommit() && state.getTable() != null) { - state.commit(); - }*/ - throw new SomethingIsWrongException("EXIT"); - } + public void implement(String args, State state) + throws SomethingIsWrongException { + /*MyTable temp = (MyTable) state.getTable();*/ + if (state.getTable() != null /*&& !temp.getAutoCommit()*/) { + state.rollback(); + }/* else if (temp.getAutoCommit() && state.getTable() != null) { + state.commit(); + }*/ + throw new SomethingIsWrongException("EXIT"); + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java index 4c0029d8d..d72227cc4 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/GetCommand.java @@ -6,7 +6,8 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Parser; -public class GetCommand> extends SomeCommand{ +public class GetCommand> + extends SomeCommand { public String getCommandName() { return "get"; @@ -19,7 +20,7 @@ public int getArgumentQuantity() { public void implement(String args, State state) throws SomethingIsWrongException { if (state.getTable() == null) { - throw new SomethingIsWrongException ("no table"); + throw new SomethingIsWrongException("no table"); } ArrayList parameters = Parser.parseCommandArgs(args); if (parameters.size() != 1) { diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java index 9e198891e..a0ecaed49 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/ListCommand.java @@ -22,7 +22,7 @@ public void implement(String args, FileMapShellState state) } ArrayList parameters = Parser.parseCommandArgs(args); if (parameters.size() != 0) { - throw new SomethingIsWrongException("This command takes no parameters"); + throw new SomethingIsWrongException("This command takes no parameters"); } MyTable temp = (MyTable) state.table; List keySet = temp.list(); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java index a123a20a4..e6104335b 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/PutCommand.java @@ -6,7 +6,8 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Parser; -public class PutCommand> extends SomeCommand{ +public class PutCommand> + extends SomeCommand { public String getCommandName() { return "put"; @@ -18,17 +19,17 @@ public int getArgumentQuantity() { public void implement(String args, State state) throws SomethingIsWrongException { - if (state.getTable() == null) { - System.err.println("no table"); - return; - } - ArrayList parameters = Parser.parseCommandArgs(args); + if (state.getTable() == null) { + System.err.println("no table"); + return; + } + ArrayList parameters = Parser.parseCommandArgs(args); if (parameters.size() != 2) { throw new IllegalArgumentException("Use 2 arguments for this operation"); } - Key key = state.parseKey(parameters.get(0)); - Value value = state.parseValue(parameters.get(1)); - Value temp = state.put(key, value); + Key key = state.parseKey(parameters.get(0)); + Value value = state.parseValue(parameters.get(1)); + Value temp = state.put(key, value); if (temp != null) { System.out.println("overwrite\n" + state.valueToString(temp)); } else { diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java index e63a57d1d..36522b46a 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RemoveKeyCommand.java @@ -6,7 +6,8 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.Parser; -public class RemoveKeyCommand> extends SomeCommand{ +public class RemoveKeyCommand> + extends SomeCommand { public String getCommandName() { return "remove"; @@ -18,14 +19,14 @@ public int getArgumentQuantity() { public void implement(String args, State state) throws SomethingIsWrongException { - if (state.getTable() == null) { - throw new SomethingIsWrongException("no table"); - } - ArrayList parameters = Parser.parseCommandArgs(args); + if (state.getTable() == null) { + throw new SomethingIsWrongException("no table"); + } + ArrayList parameters = Parser.parseCommandArgs(args); if (parameters.size() != 1) { throw new IllegalArgumentException("Use 1 argument for this operation"); } - Key key = state.parseKey(parameters.get(0)); + Key key = state.parseKey(parameters.get(0)); Value a = state.remove(key); if (a == null) { System.out.println("not found"); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java index 5fb6b77b0..4a244a42c 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/RollbackCommand.java @@ -3,7 +3,7 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; -public class RollbackCommand extends SomeCommand{ +public class RollbackCommand extends SomeCommand { public String getCommandName() { return "rollback"; @@ -16,7 +16,7 @@ public int getArgumentQuantity() { public void implement(String args, State state) throws SomethingIsWrongException { if (state.getTable() == null) { - throw new SomethingIsWrongException("no table"); + throw new SomethingIsWrongException("no table"); } System.out.println(state.rollback()); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SimpleTableBuilder.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SimpleTableBuilder.java index 3018b7736..5ee2dc35a 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SimpleTableBuilder.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SimpleTableBuilder.java @@ -4,30 +4,30 @@ import java.util.Set; public class SimpleTableBuilder implements TableBuilder { - TableUsingStrings table; - - public String get(String key) { - return table.rawGet(key); - } - - public void put(String key, String value) { - table.rawPut(key, value); - } - - public Set getKeys() { - return table.unchangedOldData.keySet(); - } - - public File getTableDirectory() { - return new File(table.getParentDirectory(), table.getName()); - } - - public void setCurrentFile(File currentFile) { - } - - public SimpleTableBuilder(TableUsingStrings table) { - this.table = table; - } + TableUsingStrings table; + + public String get(String key) { + return table.rawGet(key); + } + + public void put(String key, String value) { + table.rawPut(key, value); + } + + public Set getKeys() { + return table.unchangedOldData.keySet(); + } + + public File getTableDirectory() { + return new File(table.getParentDirectory(), table.getName()); + } + + public void setCurrentFile(File currentFile) { + } + + public SimpleTableBuilder(TableUsingStrings table) { + this.table = table; + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java index 242f921b3..d4f55a716 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SizeCommand.java @@ -4,22 +4,23 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; -public class SizeCommand> extends SomeCommand { +public class SizeCommand> + extends SomeCommand { - public String getCommandName() { - return "size"; - } + public String getCommandName() { + return "size"; + } - public int getArgumentQuantity() { - return 0; - } + public int getArgumentQuantity() { + return 0; + } - public void implement(String args, State state) - throws SomethingIsWrongException { - if (state.getTable() == null) { - throw new SomethingIsWrongException("no table"); - } - System.out.println(state.size()); - } + public void implement(String args, State state) + throws SomethingIsWrongException { + if (state.getTable() == null) { + throw new SomethingIsWrongException("no table"); + } + System.out.println(state.size()); + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java index b7ef300fb..13c59995e 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/SomeStorage.java @@ -5,7 +5,6 @@ import java.util.HashSet; import java.util.LinkedList; import java.util.List; -import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -25,91 +24,91 @@ public Transactions initialValue() { }; class Transactions { - HashMap currentData; - int size; - int unsavedChangesCounter; - - Transactions() { - this.currentData = new HashMap(); - this.size = 0; - this.unsavedChangesCounter = 0; - } - - public void newModification(Key key, Value value) { - currentData.put(key, value); - } - - public int saveModifications() { - int changesCounter = 0; - for(Key key : currentData.keySet()) { - Value newOne = currentData.get(key); - if(!GlobalUtils.compare(newOne, unchangedOldData.get(key))) { - if (newOne != null) { - unchangedOldData.put(key, newOne); - } else { - unchangedOldData.remove(key); - } - changesCounter++; - } - } - return changesCounter; - } - - public int calculateChangesQuantity() { - int changesCounter = 0; - for(Key key : currentData.keySet()) { - Value newOne = currentData.get(key); - if(!GlobalUtils.compare(newOne, unchangedOldData.get(key))) { - changesCounter++; - } - } - return changesCounter; - } - - public int calculateSize() { - int size = unchangedOldData.size(); - for(Key key : currentData.keySet()) { - Value newOne = currentData.get(key); - Value oldOne = unchangedOldData.get(key); - if (newOne == null && oldOne != null) { - size--; - } else if (newOne != null && oldOne == null) { - size++; - } - } - return size; - } - - public Value getVal(Key key) { - if (currentData.containsKey(key)) { - return currentData.get(key); - } - return unchangedOldData.get(key); - } - - public List getKeys() { - List toReturnSafe = new LinkedList(currentData.keySet()); - return toReturnSafe; - } - - public int getSize() { - return unchangedOldData.size() + calculateSize(); - } - - public void incrementUnsavedChangesCounter() { - unsavedChangesCounter++; - } - - public int getUnsavedChangesCounter() { - return unsavedChangesCounter; - } - - public void clear() { - currentData.clear(); - unsavedChangesCounter = 0; - size = 0; - } - + HashMap currentData; + int size; + int unsavedChangesCounter; + + Transactions() { + this.currentData = new HashMap(); + this.size = 0; + this.unsavedChangesCounter = 0; + } + + public void newModification(Key key, Value value) { + currentData.put(key, value); + } + + public int saveModifications() { + int changesCounter = 0; + for (Key key : currentData.keySet()) { + Value newOne = currentData.get(key); + if (!GlobalUtils.compare(newOne, unchangedOldData.get(key))) { + if (newOne != null) { + unchangedOldData.put(key, newOne); + } else { + unchangedOldData.remove(key); + } + changesCounter++; + } + } + return changesCounter; + } + + public int calculateChangesQuantity() { + int changesCounter = 0; + for (Key key : currentData.keySet()) { + Value newOne = currentData.get(key); + if (!GlobalUtils.compare(newOne, unchangedOldData.get(key))) { + changesCounter++; + } + } + return changesCounter; + } + + public int calculateSize() { + int size = unchangedOldData.size(); + for (Key key : currentData.keySet()) { + Value newOne = currentData.get(key); + Value oldOne = unchangedOldData.get(key); + if (newOne == null && oldOne != null) { + size--; + } else if (newOne != null && oldOne == null) { + size++; + } + } + return size; + } + + public Value getVal(Key key) { + if (currentData.containsKey(key)) { + return currentData.get(key); + } + return unchangedOldData.get(key); + } + + public List getKeys() { + List result = new LinkedList(currentData.keySet()); + return result; + } + + public int getSize() { + return unchangedOldData.size() + calculateSize(); + } + + public void incrementUnsavedChangesCounter() { + unsavedChangesCounter++; + } + + public int getUnsavedChangesCounter() { + return unsavedChangesCounter; + } + + public void clear() { + currentData.clear(); + unsavedChangesCounter = 0; + size = 0; + } + } public String getParentDirectory() { @@ -117,11 +116,11 @@ public String getParentDirectory() { } public void setAutoCommit(boolean status) { - doAutoCommit = status; + doAutoCommit = status; } public boolean getAutoCommit() { - return doAutoCommit; + return doAutoCommit; } public String getName() { @@ -145,37 +144,39 @@ public SomeStorage(String dir, String name) { try { load(); } catch (IOException e) { - if (e.getMessage() != "didn't exist" && e.getMessage() != "empty file") { - throw new IllegalArgumentException("invalid file format " + e.getMessage()); - } + if (!e.getMessage().equals("didn't exist") + && !e.getMessage().equals("empty file")) { + throw new IllegalArgumentException( + "invalid file format " + e.getMessage()); + } } } public Value getFromStorage(Key key) { if (key == null) { - throw new IllegalArgumentException ("key cannot be null"); + throw new IllegalArgumentException("key cannot be null"); } return transaction.get().getVal(key); } public List getAllKeys() { - return transaction.get().getKeys(); + return transaction.get().getKeys(); } public Value putIntoStorage(Key key, Value value) { - Value oldVal = transaction.get().getVal(key); + Value oldVal = transaction.get().getVal(key); transaction.get().newModification(key, value); return oldVal; } public Value removeFromStorage(Key key) { - if (key == null ) { - throw new IllegalArgumentException("key cannot be null"); + if (key == null) { + throw new IllegalArgumentException("key cannot be null"); + } + if (getFromStorage(key) == null) { + return null; } - if (getFromStorage(key) == null) { - return null; - } Value oldVal = transaction.get().getVal(key); transaction.get().newModification(key, null); transaction.get().incrementUnsavedChangesCounter(); @@ -189,28 +190,28 @@ public int rollbackStorage() { } public int commitStorage() { - try{ - transactionLock.lock(); - int commitCount = transaction.get().saveModifications(); - transaction.get().clear(); - try { - save(); - } catch (IOException e) { - System.err.println("commit error: " + e.getMessage()); - return 0; - } - return commitCount; + try { + transactionLock.lock(); + int commitCount = transaction.get().saveModifications(); + transaction.get().clear(); + try { + save(); + } catch (IOException e) { + System.err.println("commit error: " + e.getMessage()); + return 0; + } + return commitCount; } finally { - transactionLock.unlock(); + transactionLock.unlock(); } } void rawPut(Key key, Value value) { - unchangedOldData.put(key, value); + unchangedOldData.put(key, value); } Value rawGet(Key key) { - return unchangedOldData.get(key); + return unchangedOldData.get(key); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java index dc8c31173..969fab330 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/filemap/TableUsingStrings.java @@ -1,39 +1,39 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap; - import java.util.List; + public abstract class TableUsingStrings extends SomeStorage implements MyTable { - protected TableUsingStrings(String dir, String name) { - super(dir, name); - } - - public String remove(String key) { - return removeFromStorage(key); - } - - public int size() { - return sizeOfStorage(); - } - - public String get(String key) { - return getFromStorage(key); - } - - public String put(String key, String value) { - return putIntoStorage(key, value); - } - - public int rollback() { - return rollbackStorage(); - } - - public int commit() { - return commitStorage(); - } - - public List list() { + protected TableUsingStrings(String dir, String name) { + super(dir, name); + } + + public String remove(String key) { + return removeFromStorage(key); + } + + public int size() { + return sizeOfStorage(); + } + + public String get(String key) { + return getFromStorage(key); + } + + public String put(String key, String value) { + return putIntoStorage(key, value); + } + + public int rollback() { + return rollbackStorage(); + } + + public int commit() { + return commitStorage(); + } + + public List list() { return getAllKeys(); } - + } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java index 18b492294..8edc64b55 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/CreateCommand.java @@ -4,29 +4,30 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; -public class CreateCommand> extends SomeCommand { - public String getCommandName() { - return "create"; - } - - public int getArgumentQuantity() { - return 1; - } - - public void implement(String args, State state) throws SomethingIsWrongException { - Table newOne = null; - String tableName = GlobalUtils.parseTableName(args); - try { - newOne = state.createTable(args); - if (newOne != null) { - System.out.println("created"); - } else { - System.out.println(tableName + " exists"); - } - } catch (IllegalArgumentException e) { - throw new SomethingIsWrongException (e.getMessage()); - } - - } +public class CreateCommand> + extends SomeCommand { + public String getCommandName() { + return "create"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String args, State state) throws SomethingIsWrongException { + Table newOne = null; + String tableName = GlobalUtils.parseTableName(args); + try { + newOne = state.createTable(args); + if (newOne != null) { + System.out.println("created"); + } else { + System.out.println(tableName + " exists"); + } + } catch (IllegalArgumentException e) { + throw new SomethingIsWrongException(e.getMessage()); + } + + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java index b32232c7e..75badc24e 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/Database.java @@ -2,7 +2,6 @@ import java.io.File; import java.util.HashMap; -import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -11,7 +10,7 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; public class Database implements TableProvider { - private static final String CHECK_NAME_EXPRESSION = "[^0-9A-Za-zА-Яа-я]+"; + private static final String CHECK_NAME_EXPRESSION = "[^0-9A-Za-zА-Яа-я]+"; HashMap content = new HashMap(); private String databaseDirectoryPath; private MultifileTable currentTable = null; @@ -19,13 +18,13 @@ public class Database implements TableProvider { public Database(String databaseDirectoryPath) { this.databaseDirectoryPath = databaseDirectoryPath; File databaseDirectory = new File(databaseDirectoryPath); - for(File tableFile : databaseDirectory.listFiles()) { - if (tableFile.isFile()) { - continue; - } - MultifileTable table = new MultifileTable(databaseDirectoryPath, tableFile.getName()); - content.put(table.getName(), table); - } + for (File tableFile : databaseDirectory.listFiles()) { + if (tableFile.isFile()) { + continue; + } + MultifileTable table = new MultifileTable(databaseDirectoryPath, tableFile.getName()); + content.put(table.getName(), table); + } } public MultifileTable getTable(String name) { @@ -38,11 +37,11 @@ public MultifileTable getTable(String name) { return table; } if (currentTable != null) { - int changes = currentTable.getChangesCounter(); + int changes = currentTable.getChangesCounter(); if (changes > 0 && !currentTable.getAutoCommit()) { - throw new IllegalStateException(changes + " unsaved changes"); + throw new IllegalStateException(changes + " unsaved changes"); } else if (currentTable.getAutoCommit()) { - currentTable.commit(); + currentTable.commit(); } } @@ -51,11 +50,11 @@ public MultifileTable getTable(String name) { } public HashMap showTables() { - HashMap tables = new HashMap(); - for (Entry contents : content.entrySet()) { - tables.put(contents.getKey(), contents.getValue().size()); - } - return tables; + HashMap tables = new HashMap(); + for (Entry contents : content.entrySet()) { + tables.put(contents.getKey(), contents.getValue().size()); + } + return tables; } public MultifileTable createTable(String name) { @@ -68,7 +67,7 @@ public MultifileTable createTable(String name) { } File tableDirectory = new File(databaseDirectoryPath, name); if (!tableDirectory.exists()) { - tableDirectory.mkdir(); + tableDirectory.mkdir(); } MultifileTable table = new MultifileTable(databaseDirectoryPath, name); content.put(name, table); @@ -77,15 +76,15 @@ public MultifileTable createTable(String name) { public void removeTable(String name) { if (name == null || name.isEmpty()) { - throw new IllegalArgumentException ("Table's name cannot be null"); + throw new IllegalArgumentException("Table's name cannot be null"); } if (!content.containsKey(name)) { throw new IllegalStateException(name + " not exists"); } if (currentTable != null) { - if (currentTable.getName().equals(name)) { - currentTable = null; - } + if (currentTable.getName().equals(name)) { + currentTable = null; + } } content.remove(name); File tableFile = new File(databaseDirectoryPath, name); @@ -93,10 +92,10 @@ public void removeTable(String name) { } private void checkName(String name) { - Pattern pattern = Pattern.compile(CHECK_NAME_EXPRESSION); - Matcher matcher = pattern.matcher(name); - if (matcher.find()) { - throw new IllegalArgumentException("bad symbol in table's name"); - } + Pattern pattern = Pattern.compile(CHECK_NAME_EXPRESSION); + Matcher matcher = pattern.matcher(name); + if (matcher.find()) { + throw new IllegalArgumentException("bad symbol in table's name"); + } } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java index 27edbc20f..127f2a0c1 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseFactory.java @@ -9,16 +9,16 @@ public class DatabaseFactory implements MultiFileMapTableProviderClassFactory { public TableProvider create(String directory) { - if (directory == null || directory.isEmpty() ) { - throw new IllegalArgumentException ("directory name cannot be null"); - } - File databaseDirectory = new File(directory); - if (databaseDirectory.isFile()) { - throw new IllegalArgumentException ("it must be directory, not file"); - } - if (!databaseDirectory.exists()) { - databaseDirectory.mkdir(); - } + if (directory == null || directory.isEmpty()) { + throw new IllegalArgumentException("directory name cannot be null"); + } + File databaseDirectory = new File(directory); + if (databaseDirectory.isFile()) { + throw new IllegalArgumentException("it must be directory, not file"); + } + if (!databaseDirectory.exists()) { + databaseDirectory.mkdir(); + } return new Database(databaseDirectory.getAbsolutePath()); } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java index 123f3a894..2ebc9132b 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java @@ -10,7 +10,7 @@ public class DatabaseTest { - TableProviderFactory factory; + TableProviderFactory factory; TableProvider provider; @Before @@ -82,7 +82,7 @@ public void testRemoveTableIllegalStateException() { @After public void testAfter() { - provider.removeTable("table1"); + provider.removeTable("table1"); provider.removeTable("table2"); } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java index 67f45f8ab..f0b589954 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DropCommand.java @@ -7,28 +7,28 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; -public class DropCommand extends SomeCommand{ - public String getCommandName() { - return "drop"; - } - - public int getArgumentQuantity() { - return 1; - } - - public void implement(String args, State state) throws SomethingIsWrongException { - ArrayList parameters = Parser.parseCommandArgs(args); - if (parameters.size() != 1) { +public class DropCommand extends SomeCommand { + public String getCommandName() { + return "drop"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String args, State state) throws SomethingIsWrongException { + ArrayList parameters = Parser.parseCommandArgs(args); + if (parameters.size() != 1) { throw new IllegalArgumentException("Correct number of arguments -- 1"); } - try { - state.dropTable(parameters.get(0)); - System.out.println("dropped"); - } catch (IOException e) { - throw new SomethingIsWrongException (e.getMessage()); - } catch (IllegalStateException e) { - throw new SomethingIsWrongException (e.getMessage()); - } - } + try { + state.dropTable(parameters.get(0)); + System.out.println("dropped"); + } catch (IOException e) { + throw new SomethingIsWrongException(e.getMessage()); + } catch (IllegalStateException e) { + throw new SomethingIsWrongException(e.getMessage()); + } + } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java index 36c19603f..6189f5a5a 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapReadingUtils.java @@ -8,27 +8,27 @@ public class MultiFileMapReadingUtils { - public static void load(TableBuilder build) throws IOException { - File tableDir = build.getTableDirectory(); - if (tableDir.listFiles() == null) { - return; - } - - for (File dir : tableDir.listFiles()) { - if(dir.isFile()) { - continue; - } - - if(dir.listFiles().length == 0) { - throw new IllegalArgumentException("empty bucket"); - } - - for(File file : dir.listFiles()) { - build.setCurrentFile(file); - FileMapReadingUtils.scanFromDisk(file.getAbsolutePath(), build); - } - } - - } + public static void load(TableBuilder build) throws IOException { + File tableDir = build.getTableDirectory(); + if (tableDir.listFiles() == null) { + return; + } + + for (File dir : tableDir.listFiles()) { + if (dir.isFile()) { + continue; + } + + if (dir.listFiles().length == 0) { + throw new IllegalArgumentException("empty bucket"); + } + + for (File file : dir.listFiles()) { + build.setCurrentFile(file); + FileMapReadingUtils.scanFromDisk(file.getAbsolutePath(), build); + } + } + + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java index 12c0a8ac9..ecf0934a4 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapShellState.java @@ -6,7 +6,8 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.FileMapShellState; import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.MyTable; -public class MultiFileMapShellState extends FileMapShellState implements MultifileMapShellStateInterface { +public class MultiFileMapShellState extends FileMapShellState + implements MultifileMapShellStateInterface { public MultiFileMapTableProviderClass tableProvider; public MyTable useTable(String name) { diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java index 7399c00aa..92855f74d 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableBuilder.java @@ -7,21 +7,21 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.TableUsingStrings; public class MultiFileMapTableBuilder extends SimpleTableBuilder { - private int currentDir; - private int currentFile; - - - public MultiFileMapTableBuilder(TableUsingStrings table) { - super(table); - } - - public void setCurrentFile(File file) { - currentDir = GlobalUtils.parseDirNumber(file.getParentFile()); - currentFile = GlobalUtils.parseFileNumber(file); - } - - public void put(String key, String value) { - GlobalUtils.checkKeyPlacement(key, currentDir, currentFile); - super.put(key, value); - } + private int currentDir; + private int currentFile; + + + public MultiFileMapTableBuilder(TableUsingStrings table) { + super(table); + } + + public void setCurrentFile(File file) { + currentDir = GlobalUtils.parseDirNumber(file.getParentFile()); + currentFile = GlobalUtils.parseFileNumber(file); + } + + public void put(String key, String value) { + GlobalUtils.checkKeyPlacement(key, currentDir, currentFile); + super.put(key, value); + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClass.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClass.java index 701011b3f..5ff9f50b7 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClass.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapTableProviderClass.java @@ -4,6 +4,6 @@ import ru.fizteh.fivt.storage.strings.TableProvider; -public abstract interface MultiFileMapTableProviderClass extends TableProvider { - HashMap showTables(); +public interface MultiFileMapTableProviderClass extends TableProvider { + HashMap showTables(); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java index 7932979a3..893d78491 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultiFileMapWritingUtils.java @@ -12,46 +12,46 @@ public class MultiFileMapWritingUtils { - public static void save(TableBuilder build) throws IOException { - File tableDir = build.getTableDirectory(); - if (tableDir.listFiles() == null) { - return; - } - ArrayList> toSave = new ArrayList>(); - boolean dirIsEmpty; + public static void save(TableBuilder build) throws IOException { + File tableDir = build.getTableDirectory(); + if (tableDir.listFiles() == null) { + return; + } + ArrayList> toSave = new ArrayList>(); + boolean dirIsEmpty; - for (int dirNumber = 0; dirNumber < GlobalUtils.DIR_QUANTITY; ++dirNumber) { - toSave.clear(); - for (int fileNumber = 0; fileNumber < GlobalUtils.FILES_PER_DIR; ++fileNumber) { - toSave.add(new HashSet()); - } - dirIsEmpty = true; + for (int dirNumber = 0; dirNumber < GlobalUtils.DIR_QUANTITY; ++dirNumber) { + toSave.clear(); + for (int fileNumber = 0; fileNumber < GlobalUtils.FILES_PER_DIR; ++fileNumber) { + toSave.add(new HashSet()); + } + dirIsEmpty = true; - for (String key : build.getKeys()) { - if (GlobalUtils.getDirNumber(key) == dirNumber) { - int fileNumber = GlobalUtils.getFileNumber(key); - toSave.get(fileNumber).add(key); - dirIsEmpty = false; - } - } - String dirName = dirNumber + ".dir"; - File dir = new File(tableDir, dirName); - if (dirIsEmpty) { - GlobalUtils.deleteFile(dir); - } - for (int fileNumber = 0; fileNumber < GlobalUtils.FILES_PER_DIR; ++fileNumber) { - String fileName = fileNumber + ".dat"; - File file = new File(dir, fileName); - if (toSave.get(fileNumber).isEmpty()) { - GlobalUtils.deleteFile(file); - continue; - } - if (!dir.exists()) { - dir.mkdir(); - } - FileMapWritingUtils.writeOnDisk(toSave.get(fileNumber), - file.getAbsolutePath(), build); - } - } - } + for (String key : build.getKeys()) { + if (GlobalUtils.getDirNumber(key) == dirNumber) { + int fileNumber = GlobalUtils.getFileNumber(key); + toSave.get(fileNumber).add(key); + dirIsEmpty = false; + } + } + String dirName = dirNumber + ".dir"; + File dir = new File(tableDir, dirName); + if (dirIsEmpty) { + GlobalUtils.deleteFile(dir); + } + for (int fileNumber = 0; fileNumber < GlobalUtils.FILES_PER_DIR; ++fileNumber) { + String fileName = fileNumber + ".dat"; + File file = new File(dir, fileName); + if (toSave.get(fileNumber).isEmpty()) { + GlobalUtils.deleteFile(file); + continue; + } + if (!dir.exists()) { + dir.mkdir(); + } + FileMapWritingUtils.writeOnDisk(toSave.get(fileNumber), + file.getAbsolutePath(), build); + } + } + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java index b51d13a9b..57606eba7 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapMain.java @@ -17,32 +17,34 @@ public class MultifileMapMain { - public static void main(String args[]) { - HashSet> com = new HashSet>() {{ - add(new ExitCommand()); add(new RollbackCommand()); add(new CommitCommand()); add(new ListCommand()); - add(new PutCommand()); add(new GetCommand()); add(new RemoveKeyCommand()); add(new SizeCommand());}}; + public static void main(String[] args) { + HashSet> com = new HashSet>() { { + add(new ExitCommand()); add(new RollbackCommand()); + add(new CommitCommand()); add(new ListCommand()); + add(new PutCommand()); add(new GetCommand()); + add(new RemoveKeyCommand()); add(new SizeCommand()); }}; HashSet> com1 = new HashSet>() - {{add(new DropCommand()); add(new UseCommand()); - add(new CreateCommand());}}; + { { add(new DropCommand()); add(new UseCommand()); + add(new CreateCommand()); }}; ArrayList> res = new ArrayList>(); res.addAll(com); res.addAll(com1); HashSet> actualResult = new HashSet>(res); Shell shell = new Shell(actualResult); try { - String dbDirectory = System.getProperty("fizteh.db.dir"); - if (dbDirectory == null) { - System.err.println("error: nope. Gimme something."); - System.exit(-2); - } - MultiFileMapShellState state = new MultiFileMapShellState(); - DatabaseFactory factory = new DatabaseFactory(); - state.tableProvider = (MultiFileMapTableProviderClass) factory.create(dbDirectory); - shell.setShellState(state); + String dbDirectory = System.getProperty("fizteh.db.dir"); + if (dbDirectory == null) { + System.err.println("error: nope. Gimme something."); + System.exit(-2); + } + MultiFileMapShellState state = new MultiFileMapShellState(); + DatabaseFactory factory = new DatabaseFactory(); + state.tableProvider = (MultiFileMapTableProviderClass) factory.create(dbDirectory); + shell.setShellState(state); } catch (IllegalArgumentException e) { - System.err.println("error: " + e.getMessage()); - System.exit(-1); + System.err.println("error: " + e.getMessage()); + System.exit(-1); } shell.run(args, shell); - } + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java index 67edef8eb..ee15ba0bc 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileMapShellStateInterface.java @@ -4,12 +4,13 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.FileMapShellStateInterface; -public interface MultifileMapShellStateInterface extends FileMapShellStateInterface { - public Table useTable(String name); - - public Table createTable(String arguments); - - public void dropTable(String name) throws IOException; - - public String getCurrentTableName(); +public interface MultifileMapShellStateInterface + extends FileMapShellStateInterface { + Table useTable(String name); + + Table createTable(String arguments); + + void dropTable(String name) throws IOException; + + String getCurrentTableName(); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java index 86cb3a1c8..738f3fdd5 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTable.java @@ -7,7 +7,7 @@ public class MultifileTable extends TableUsingStrings { - + public MultifileTable(String directory, String tableName) { @@ -15,21 +15,21 @@ public MultifileTable(String directory, String tableName) { } /*private File getTableDirectory() { - File tableDirectory = new File(getParentDirectory(), getName()); - if (!tableDirectory.exists()) { - tableDirectory.mkdir(); - } - return tableDirectory; + File tableDirectory = new File(getParentDirectory(), getName()); + if (!tableDirectory.exists()) { + tableDirectory.mkdir(); + } + return tableDirectory; }*/ - protected void load() throws IOException { - MultiFileMapReadingUtils.load(new SimpleTableBuilder(this)); - - } + protected void load() throws IOException { + MultiFileMapReadingUtils.load(new SimpleTableBuilder(this)); + + } - protected void save() throws IOException{ - MultiFileMapWritingUtils.save(new SimpleTableBuilder(this)); - - } + protected void save() throws IOException { + MultiFileMapWritingUtils.save(new SimpleTableBuilder(this)); + + } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java index e7d5706a6..58c719e65 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/MultifileTableTest.java @@ -13,7 +13,7 @@ public class MultifileTableTest { - private static final int KEYS_COUNT = 20; + private static final int KEYS_COUNT = 20; private static final String TABLE_NAME = "testtable"; MyTable currentTable; @@ -133,8 +133,7 @@ public void testTableExceptions() { } @Test - public void testRollbackAndCommit() - { + public void testRollbackAndCommit() { for (int index = 0; index < KEYS_COUNT; ++index) { String key = String.format("key%d", index); String value = String.format("value%d", index); diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/ShowTablesCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/ShowTablesCommand.java index 3ce818f21..974322b48 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/ShowTablesCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/ShowTablesCommand.java @@ -7,22 +7,22 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.*; public class ShowTablesCommand implements Commands { - public String getCommandName() { - return "show"; - } - - public int getArgumentQuantity() { - return 1; - } - - public void implement(String args, MultiFileMapShellState state) throws SomethingIsWrongException { - ArrayList parameters = Parser.parseCommandArgs(args); - if(parameters.get(0) != "tables") { - throw new SomethingIsWrongException("no command with this name"); - } - HashMap tables = state.tableProvider.showTables(); - for(Entry iterator : tables.entrySet()) { - System.out.println(iterator.getKey() + ' ' + iterator.getValue()); - } - } -} \ No newline at end of file + public String getCommandName() { + return "show"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String args, MultiFileMapShellState state) throws SomethingIsWrongException { + ArrayList parameters = Parser.parseCommandArgs(args); + if (!parameters.get(0).equals("tables")) { + throw new SomethingIsWrongException("no command with this name"); + } + HashMap tables = state.tableProvider.showTables(); + for (Entry iterator : tables.entrySet()) { + System.out.println(iterator.getKey() + ' ' + iterator.getValue()); + } + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java index 4831ca76d..76c96415c 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/UseCommand.java @@ -7,37 +7,38 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomeCommand; import ru.fizteh.fivt.students.NikolaiKrivchanskii.Shell.SomethingIsWrongException; -public class UseCommand> extends SomeCommand { - public String getCommandName() { - return "use"; - } - - public int getArgumentQuantity() { - return 1; - } - - public void implement(String args, State state) throws SomethingIsWrongException { - ArrayList parameters = Parser.parseCommandArgs(args); +public class UseCommand> + extends SomeCommand { + public String getCommandName() { + return "use"; + } + + public int getArgumentQuantity() { + return 1; + } + + public void implement(String args, State state) throws SomethingIsWrongException { + ArrayList parameters = Parser.parseCommandArgs(args); if (parameters.size() != 1) { throw new IllegalArgumentException("Correct number of arguments -- 1"); } - Table newOne = null; - try { - newOne = state.useTable(parameters.get(0)); - } catch (IllegalStateException e) { - System.err.println(e.getMessage()); + Table newOne = null; + try { + newOne = state.useTable(parameters.get(0)); + } catch (IllegalStateException e) { + System.err.println(e.getMessage()); return; } catch (IllegalArgumentException e) { System.err.println(e.getMessage()); return; } - - if (newOne == null) { - System.out.println(parameters.get(0) + " not exists"); + + if (newOne == null) { + System.out.println(parameters.get(0) + " not exists"); return; } System.out.println("using " + state.getCurrentTableName()); - - } -} \ No newline at end of file + + } +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRow.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRow.java index ae2cf2e0c..ab4fbe62f 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRow.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRow.java @@ -9,35 +9,39 @@ import ru.fizteh.fivt.storage.structured.Storeable; public class DatabaseRow implements Storeable { - final List> classes = new ArrayList<>(); - List columns = new ArrayList<>(); - - public DatabaseRow(List> classes) { - this.classes.addAll(classes); - for (int i = 0; i < classes.size(); ++i) { - columns.add(null); - } - } - - public DatabaseRow() {} - - private void checkBounds(int index) throws IndexOutOfBoundsException { + final List> classes = new ArrayList<>(); + List columns = new ArrayList<>(); + + public DatabaseRow(List> classes) { + this.classes.addAll(classes); + for (int i = 0; i < classes.size(); ++i) { + columns.add(null); + } + } + + public DatabaseRow() {} + + private void checkBounds(int index) throws IndexOutOfBoundsException { if (index < 0 || index >= classes.size()) { throw new IndexOutOfBoundsException(String.format("index out of bound: %d", index)); } } - - private void checkColumnType(int columnIndex, Class actualType) throws ColumnFormatException { + + private void checkColumnType(int columnIndex, Class actualType) throws ColumnFormatException { if (!actualType.isAssignableFrom(classes.get(columnIndex))) { throw new ColumnFormatException(String.format("incorrect type: expected type: %s actual type: %s", classes.get(columnIndex).getName(), actualType.getName())); } } - - public boolean equals(Object obj) { + + public boolean equals(Object obj) { DatabaseRow otherStoreable = (DatabaseRow) obj; return otherStoreable.columns.equals(columns) && otherStoreable.classes.equals(classes); } + + public int hashCode() { + return classes.hashCode() + columns.hashCode() * 17; + } public String getStringAt(int columnIndex) throws ColumnFormatException, IndexOutOfBoundsException { checkBounds(columnIndex); @@ -85,13 +89,13 @@ public Boolean getBooleanAt(int columnIndex) throws ColumnFormatException, Index checkColumnType(columnIndex, Boolean.class); return (Boolean) columns.get(columnIndex); } - + @Override - public String toString() { + public String toString() { return LocalUtils.join(columns); } - - public void setColumns(List values) throws ColumnFormatException, IndexOutOfBoundsException { + + public void setColumns(List values) throws ColumnFormatException, IndexOutOfBoundsException { if (values.size() != classes.size()) { throw new IndexOutOfBoundsException(); } @@ -102,24 +106,24 @@ public void setColumns(List values) throws ColumnFormatException, IndexOutOfB columns.add(values.get(index)); } } - - public void setColumnAt(int columnIndex, Object value) throws ColumnFormatException, IndexOutOfBoundsException { + + public void setColumnAt(int columnIndex, Object value) throws ColumnFormatException, IndexOutOfBoundsException { checkBounds(columnIndex); if (value != null) { checkColumnType(columnIndex, value.getClass()); try { - LocalUtils.checkValue(value, value.getClass()); - } catch(ParseException e) { - throw new IllegalArgumentException("incorrect value: " + value.toString()); + LocalUtils.checkValue(value, value.getClass()); + } catch (ParseException e) { + throw new IllegalArgumentException("incorrect value: " + value.toString()); } } columns.set(columnIndex, value); } - - public void addColumn(Class columnType) { + + public void addColumn(Class columnType) { classes.add(columnType); columns.add(null); } - - + + } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRowTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRowTest.java index bcf15c7e3..da25dfb92 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRowTest.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseRowTest.java @@ -6,7 +6,6 @@ import ru.fizteh.fivt.storage.structured.ColumnFormatException; import ru.fizteh.fivt.storage.structured.Storeable; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.storable.DatabaseRow; import java.util.ArrayList; import java.util.List; diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTable.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTable.java index 1ce958cac..e53f9eae3 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTable.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTable.java @@ -17,35 +17,44 @@ public class DatabaseTable extends SomeStorage implements Table { - DatabaseTableProvider provider; - private List> columnTypes; - - public DatabaseTable(DatabaseTableProvider provider, String databaseDir, String name, List> columnTypes) { - super(databaseDir, name); - if (columnTypes == null || columnTypes.isEmpty()) { - throw new IllegalArgumentException ("column types cannot be null"); - } - this.columnTypes = columnTypes; - this.provider = provider; - try{ - checkTableDirectory(); - load(); - } catch(IOException e) { - throw new IllegalArgumentException("invalid file format"); - } - } - - public Storeable get(String key) { + DatabaseTableProvider provider; + private List> columnTypes; + + public DatabaseTable(DatabaseTableProvider provider, String databaseDir, + String name, List> columnTypes) { + super(databaseDir, name); + if (columnTypes == null || columnTypes.isEmpty()) { + throw new IllegalArgumentException("column types cannot be null"); + } + this.columnTypes = columnTypes; + this.provider = provider; + try { + checkTableDirectory(); + load(); + } catch (IOException e) { + throw new IllegalArgumentException("invalid file format"); + } + } + + public int getNumberOfUncommittedChanges() { + return getChangesCounter(); + } + + public List list() { + return getAllKeys(); + } + + public Storeable get(String key) { return getFromStorage(key); } - - public Storeable put(String key, Storeable value) throws ColumnFormatException { + + public Storeable put(String key, Storeable value) throws ColumnFormatException { if (key != null) { if (LocalUtils.checkStringCorrect(key)) { throw new IllegalArgumentException("key cannot be empty"); } } else if (key == null) { - throw new IllegalArgumentException("key can't be null"); + throw new IllegalArgumentException("key can't be null"); } if (value == null) { @@ -58,103 +67,104 @@ public Storeable put(String key, Storeable value) throws ColumnFormatException { isStoreableCorrect(value); return putIntoStorage(key, value); } - - public Storeable remove(String key) { - return removeFromStorage(key); - } + + public Storeable remove(String key) { + return removeFromStorage(key); + } - public int size() { - return sizeOfStorage(); - } + public int size() { + return sizeOfStorage(); + } - public int commit() throws IOException { - return commitStorage(); - } + public int commit() throws IOException { + return commitStorage(); + } - public int rollback() { - return rollbackStorage(); - } + public int rollback() { + return rollbackStorage(); + } - public int getColumnsCount() { - return columnTypes.size(); - } - - public Class getColumnType(int columnIndex) throws IndexOutOfBoundsException { - if (columnIndex < 0 || columnIndex > getColumnsCount()) { - throw new IndexOutOfBoundsException(); - } - return columnTypes.get(columnIndex); - } + public int getColumnsCount() { + return columnTypes.size(); + } + + public Class getColumnType(int columnIndex) throws IndexOutOfBoundsException { + if (columnIndex < 0 || columnIndex > getColumnsCount()) { + throw new IndexOutOfBoundsException(); + } + return columnTypes.get(columnIndex); + } - protected void load() throws IOException { - if (provider == null) { - return; - } - MultiFileMapReadingUtils.load(new StoreableTableBuilder(provider, this)); - } + protected void load() throws IOException { + if (provider == null) { + return; + } + MultiFileMapReadingUtils.load(new StoreableTableBuilder(provider, this)); + } - protected void save() throws IOException { - MultiFileMapWritingUtils.save(new StoreableTableBuilder(provider, this)); - } + protected void save() throws IOException { + MultiFileMapWritingUtils.save(new StoreableTableBuilder(provider, this)); + } - private void checkTableDirectory() throws IOException { - File tableDirectory = new File(getParentDirectory(), getName()); - if (!tableDirectory.exists()) { - tableDirectory.mkdir(); - writeSignatureFile(); - } else { - File[] children = tableDirectory.listFiles(); - if (children == null || children.length == 0) { - throw new IllegalArgumentException(String.format("table directory: %s is empty", tableDirectory.getAbsolutePath())); - } - } - } + private void checkTableDirectory() throws IOException { + File tableDirectory = new File(getParentDirectory(), getName()); + if (!tableDirectory.exists()) { + tableDirectory.mkdir(); + writeSignatureFile(); + } else { + File[] children = tableDirectory.listFiles(); + if (children == null || children.length == 0) { + throw new IllegalArgumentException(String.format("table directory: %s is empty", + tableDirectory.getAbsolutePath())); + } + } + } - private void writeSignatureFile() throws IOException { - File tableDirectory = new File(getParentDirectory(), getName()); - File signatureFile = new File(tableDirectory, DatabaseTableProvider.SIGNATURE_FILE); - signatureFile.createNewFile(); - BufferedWriter writer = new BufferedWriter(new FileWriter(signatureFile)); - List formattedColumnTypes = LocalUtils.formatColumnTypes(columnTypes); - String signature = LocalUtils.join(formattedColumnTypes); - writer.write(signature); - writer.close(); - } - - - public boolean checkAlienStoreable(Storeable storeable) { - for (int index = 0; index < getColumnsCount(); ++index) { - try { - Object o = storeable.getColumnAt(index); - if (o == null) { - continue; - } - if (!o.getClass().equals(getColumnType(index))) { - return false; - } - } catch (IndexOutOfBoundsException e) { - return false; - } - } - try { - storeable.getColumnAt(getColumnsCount()); - } catch (IndexOutOfBoundsException e) { - return true; - } - return false; - } + private void writeSignatureFile() throws IOException { + File tableDirectory = new File(getParentDirectory(), getName()); + File signatureFile = new File(tableDirectory, DatabaseTableProvider.SIGNATURE_FILE); + signatureFile.createNewFile(); + BufferedWriter writer = new BufferedWriter(new FileWriter(signatureFile)); + List formattedColumnTypes = LocalUtils.formatColumnTypes(columnTypes); + String signature = LocalUtils.join(formattedColumnTypes); + writer.write(signature); + writer.close(); + } + + + public boolean checkAlienStoreable(Storeable storeable) { + for (int index = 0; index < getColumnsCount(); ++index) { + try { + Object o = storeable.getColumnAt(index); + if (o == null) { + continue; + } + if (!o.getClass().equals(getColumnType(index))) { + return false; + } + } catch (IndexOutOfBoundsException e) { + return false; + } + } + try { + storeable.getColumnAt(getColumnsCount()); + } catch (IndexOutOfBoundsException e) { + return true; + } + return false; + } - Set rawGetKeys() { - return unchangedOldData.keySet(); - } - - public void isStoreableCorrect(Storeable storeable) { - for (int index = 0; index < getColumnsCount(); ++index) { - try { - LocalUtils.checkValue(storeable.getColumnAt(index), columnTypes.get(index)); - } catch (ParseException e) { - throw new IllegalArgumentException(e); - } - } - } + Set rawGetKeys() { + return unchangedOldData.keySet(); + } + + public void isStoreableCorrect(Storeable storeable) { + for (int index = 0; index < getColumnsCount(); ++index) { + try { + LocalUtils.checkValue(storeable.getColumnAt(index), columnTypes.get(index)); + } catch (ParseException e) { + throw new IllegalArgumentException(e); + } + } + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java index 879d3ec11..eb40486b8 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java @@ -14,7 +14,6 @@ import java.util.concurrent.locks.ReentrantLock; import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap.MultifileTable; import ru.fizteh.fivt.storage.structured.ColumnFormatException; import ru.fizteh.fivt.storage.structured.Storeable; import ru.fizteh.fivt.storage.structured.Table; @@ -22,112 +21,118 @@ public class DatabaseTableProvider implements TableProvider { - static final String SIGNATURE_FILE = "signature.tsv"; - private static final String CHECKER = "[0-9A-Za-zА-Яа-я]+"; - private final Lock tableLock = new ReentrantLock(true); - - HashMap tables = new HashMap(); - private String databaseDirPath; - private DatabaseTable currentTable = null; - - public DatabaseTableProvider(String databaseDirPath) { - if (databaseDirPath == null) { - throw new IllegalArgumentException ("path to database can not be null"); - } - - this.databaseDirPath = databaseDirPath; - File databaseDir = new File(databaseDirPath); - if (databaseDir.isFile()) { - throw new IllegalArgumentException("database dir cannot be file"); - } - for (File tableFile : databaseDir.listFiles()) { - if (tableFile.isFile()) { - continue; - } - List> columnTypes = readTableSignature(tableFile.getName()); - if (columnTypes == null) { - throw new IllegalArgumentException("table directory is empty"); - } - DatabaseTable table = new DatabaseTable(this, databaseDirPath, tableFile.getName(), columnTypes); - tables.put(table.getName(), table); - } - } - - public Table getTable(String name) { - try { - tableLock.lock(); - if (name == null || name.isEmpty()) { - throw new IllegalArgumentException("table cannot be null"); - } - checkTableName(name); - DatabaseTable table = tables.get(name); - if (table == null) { - return null; - } - if (currentTable != null && currentTable.getChangesCounter() > 0) { - throw new IllegalStateException (currentTable.getChangesCounter() + " unsaved changes"); - } - currentTable = table; - return table; - } finally { - tableLock.unlock(); - } - } - - public Table createTable(String name, List> columnTypes) throws IOException { - try { - tableLock.lock(); - if (name == null || name.isEmpty()) { - throw new IllegalArgumentException("table's name cannot be null"); - } - checkTableName(name); - if (columnTypes == null || columnTypes.isEmpty()) { - throw new IllegalArgumentException("wrong type ()"); - } - checkColumnTypes(columnTypes); - if (tables.containsKey(name)) { + static final String SIGNATURE_FILE = "signature.tsv"; + private static final String CHECKER = "[0-9A-Za-zА-Яа-я]+"; + private final Lock tableLock = new ReentrantLock(true); + + HashMap tables = new HashMap(); + private String databaseDirPath; + private DatabaseTable currentTable = null; + + public DatabaseTableProvider(String databaseDirPath) { + if (databaseDirPath == null) { + throw new IllegalArgumentException("path to database can not be null"); + } + + this.databaseDirPath = databaseDirPath; + File databaseDir = new File(databaseDirPath); + if (databaseDir.isFile()) { + throw new IllegalArgumentException("database dir cannot be file"); + } + for (File tableFile : databaseDir.listFiles()) { + if (tableFile.isFile()) { + continue; + } + List> columnTypes = readTableSignature(tableFile.getName()); + if (columnTypes == null) { + throw new IllegalArgumentException("table directory is empty"); + } + DatabaseTable table = new DatabaseTable(this, databaseDirPath, tableFile.getName(), + columnTypes); + tables.put(table.getName(), table); + } + } + + public List getTableNames() { + List toReturnSafe = new LinkedList(tables.keySet()); + return toReturnSafe; + } + + public Table getTable(String name) { + try { + tableLock.lock(); + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("table cannot be null"); + } + checkTableName(name); + DatabaseTable table = tables.get(name); + if (table == null) { + return null; + } + if (currentTable != null && currentTable.getChangesCounter() > 0) { + throw new IllegalStateException(currentTable.getChangesCounter() + " unsaved changes"); + } + currentTable = table; + return table; + } finally { + tableLock.unlock(); + } + } + + public Table createTable(String name, List> columnTypes) throws IOException { + try { + tableLock.lock(); + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("table's name cannot be null"); + } + checkTableName(name); + if (columnTypes == null || columnTypes.isEmpty()) { + throw new IllegalArgumentException("wrong type ()"); + } + checkColumnTypes(columnTypes); + if (tables.containsKey(name)) { return null; } - DatabaseTable table = new DatabaseTable(this, databaseDirPath, name, columnTypes); - tables.put(name, table); - return table; - } finally { - tableLock.unlock(); - } - } - - public void removeTable(String name) throws IOException { - try { - tableLock.lock(); - if (name == null || name.isEmpty()) { - throw new IllegalArgumentException("table's name cannot be null"); - } - - if (!tables.containsKey(name)) { - throw new IllegalStateException(name + " not exists"); - } - if (currentTable != null) { - if (currentTable.getName().equals(name)) { - currentTable = null; - } - } - tables.remove(name); - File tableFile = new File(databaseDirPath, name); - GlobalUtils.deleteFile(tableFile); - } finally { - tableLock.unlock(); - } - } - - public HashMap showTables() { - HashMap content = new HashMap(); - for (Entry contents : tables.entrySet()) { - content.put(contents.getKey(), contents.getValue().size()); - } - return content; - } - - public String serialize(Table table, Storeable value) throws ColumnFormatException { + DatabaseTable table = new DatabaseTable(this, databaseDirPath, name, columnTypes); + tables.put(name, table); + return table; + } finally { + tableLock.unlock(); + } + } + + public void removeTable(String name) throws IOException { + try { + tableLock.lock(); + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("table's name cannot be null"); + } + + if (!tables.containsKey(name)) { + throw new IllegalStateException(name + " not exists"); + } + if (currentTable != null) { + if (currentTable.getName().equals(name)) { + currentTable = null; + } + } + tables.remove(name); + File tableFile = new File(databaseDirPath, name); + GlobalUtils.deleteFile(tableFile); + } finally { + tableLock.unlock(); + } + } + + public HashMap showTables() { + HashMap content = new HashMap(); + for (Entry contents : tables.entrySet()) { + content.put(contents.getKey(), contents.getValue().size()); + } + return content; + } + + public String serialize(Table table, Storeable value) throws ColumnFormatException { if (value == null) { throw new IllegalArgumentException("value cannot be null"); } @@ -146,8 +151,8 @@ public String serialize(Table table, Storeable value) throws ColumnFormatExcepti return null; } - - public Storeable deserialize(Table table, String val) throws ParseException { + + public Storeable deserialize(Table table, String val) throws ParseException { if (val == null || val.isEmpty()) { throw new IllegalArgumentException("value cannot be null or empty"); } @@ -178,12 +183,13 @@ public Storeable deserialize(Table table, String val) throws ParseException { } return result; } - - public Storeable createFor(Table table) { + + public Storeable createFor(Table table) { return rawCreateFor(table); } - - public Storeable createFor(Table table, List values) throws ColumnFormatException, IndexOutOfBoundsException { + + public Storeable createFor(Table table, List values) + throws ColumnFormatException, IndexOutOfBoundsException { if (values == null) { throw new IllegalArgumentException("values cannot be null"); } @@ -191,32 +197,32 @@ public Storeable createFor(Table table, List values) throws ColumnFormatExcep row.setColumns(values); return row; } - - private DatabaseRow rawCreateFor(Table table) { + + private DatabaseRow rawCreateFor(Table table) { DatabaseRow row = new DatabaseRow(); for (int index = 0; index < table.getColumnsCount(); ++index) { row.addColumn(table.getColumnType(index)); } return row; } - - - private List> readTableSignature(String tableName) { - File tableDirectory = new File(databaseDirPath, tableName); - File signatureFile = new File(tableDirectory, SIGNATURE_FILE); - String signature = null; - if (!signatureFile.exists()) { - return null; - } - try (BufferedReader reader = new BufferedReader(new FileReader(signatureFile))) { - signature = reader.readLine(); - } catch (IOException e) { - System.err.println("error loading signature file: " + e.getMessage()); - return null; - } + + + private List> readTableSignature(String tableName) { + File tableDirectory = new File(databaseDirPath, tableName); + File signatureFile = new File(tableDirectory, SIGNATURE_FILE); + String signature = null; + if (!signatureFile.exists()) { + return null; + } + try (BufferedReader reader = new BufferedReader(new FileReader(signatureFile))) { + signature = reader.readLine(); + } catch (IOException e) { + System.err.println("error loading signature file: " + e.getMessage()); + return null; + } if (signature == null) { throw new IllegalArgumentException("incorrect signature file"); - } + } List> columnTypes = new ArrayList>(); for (final String columnType : signature.split("\\s+")) { Class type = StoreableTypes.getTypeByName(columnType); @@ -227,13 +233,13 @@ private List> readTableSignature(String tableName) { } return columnTypes; } - - private boolean checkCorrectTable(File tableDirectory) { - File signatureFile = new File(tableDirectory, SIGNATURE_FILE); - return signatureFile.exists(); - } - - private void checkColumnTypes(List> columnTypes) { + + private boolean checkCorrectTable(File tableDirectory) { + File signatureFile = new File(tableDirectory, SIGNATURE_FILE); + return signatureFile.exists(); + } + + private void checkColumnTypes(List> columnTypes) { for (final Class columnType : columnTypes) { if (columnType == null) { throw new IllegalArgumentException("wrong type ()"); @@ -241,8 +247,8 @@ private void checkColumnTypes(List> columnTypes) { StoreableTypes.getSimpleName(columnType); } } - - private void checkTableName(String name) { + + private void checkTableName(String name) { if (!name.matches(CHECKER)) { throw new IllegalArgumentException("Bad symbol!"); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactory.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactory.java index c4e20c3c8..ea5d7ffc1 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactory.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactory.java @@ -9,7 +9,7 @@ public class DatabaseTableProviderFactory implements TableProviderFactory { - public synchronized TableProvider create(String directory) throws IOException { + public synchronized TableProvider create(String directory) throws IOException { if (directory == null) { throw new IllegalArgumentException("directory cannot be null"); } @@ -31,3 +31,4 @@ public synchronized TableProvider create(String directory) throws IOException { return new DatabaseTableProvider(databaseDirectory.getAbsolutePath()); } } + diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactoryTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactoryTest.java index 3b5b2ea76..9fd2c369c 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactoryTest.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderFactoryTest.java @@ -3,7 +3,6 @@ import org.junit.Test; import ru.fizteh.fivt.storage.structured.TableProviderFactory; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.storable.DatabaseTableProviderFactory; import java.io.IOException; @@ -17,4 +16,4 @@ public void createProviderNullDirectoryTest() { // } } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderTest.java index a64438d5c..5cb401948 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderTest.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProviderTest.java @@ -4,7 +4,6 @@ import org.junit.Test; import ru.fizteh.fivt.storage.structured.TableProviderFactory; -import ru.fizteh.fivt.students.NikolaiKrivchanskii.storable.DatabaseTableProviderFactory; import java.io.IOException; @@ -21,7 +20,7 @@ public void createProviderEmptyShouldFail() { try { factory.create(""); } catch (IOException e) { - + System.out.println("Exception caught"); } } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableTest.java index f7f717b78..ccc5a53b8 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableTest.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableTest.java @@ -2,10 +2,12 @@ import org.junit.*; + import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; + import ru.fizteh.fivt.storage.structured.Storeable; import ru.fizteh.fivt.storage.structured.Table; import ru.fizteh.fivt.storage.structured.TableProvider; @@ -21,17 +23,17 @@ public void beforeTest() { try { provider = factory.create(DATABASE); } catch (IOException e) { - + System.out.println("Exception caught"); } List> columnTypes = new ArrayList<>(); columnTypes.add(Integer.class); columnTypes.add(String.class); try { - currentTable = provider.createTable("testTable", columnTypes); - } catch (IOException e) { - e.printStackTrace(); - } + currentTable = provider.createTable("testTable", columnTypes); + } catch (IOException e) { + e.printStackTrace(); + } } @After diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/LocalUtils.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/LocalUtils.java index b1544fa23..91e2f8863 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/LocalUtils.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/LocalUtils.java @@ -10,11 +10,13 @@ import ru.fizteh.fivt.storage.structured.Table; public class LocalUtils { - public static List parseValues(List valuesRepresentation, Table table) throws ColumnFormatException { + public static List parseValues(List valuesRepresentation, Table table) + throws ColumnFormatException { List values = new ArrayList<>(valuesRepresentation.size() - 1); for (int index = 1; index < valuesRepresentation.size(); ++index) { - Object value = StoreableTypes.parseByClass(valuesRepresentation.get(index), table.getColumnType(index - 1)); + Object value = StoreableTypes.parseByClass(valuesRepresentation.get(index), + table.getColumnType(index - 1)); values.add(value); } return values; @@ -75,11 +77,13 @@ public static void checkValue(Object value, Class type) throws ParseException /*if (checkStringCorrect(stringValue)) throw new ParseException("value cannot be null", 0);*/ break; + default: + break; } } public static boolean checkStringCorrect(String string) { - + return (string.matches("\\s*") || string.split("\\s+").length != 1); } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableMain.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableMain.java index 73b8ee831..fbfca4fc7 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableMain.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableMain.java @@ -20,22 +20,22 @@ import ru.fizteh.fivt.storage.structured.Table; public class StorableMain { - public static void main(String[] args) { - List> commands = new ArrayList>(); - HashSet> com = new HashSet>() {{ - add(new ExitCommand()); - add(new RollbackCommand()); - add(new CommitCommand()); + public static void main(String[] args) { + List> commands = new ArrayList>(); + HashSet> com = new HashSet>() { { + add(new ExitCommand()); + add(new RollbackCommand()); + add(new CommitCommand()); add(new PutCommand()); add(new GetCommand()); add(new RemoveKeyCommand()); add(new DropCommand()); add(new UseCommand()); - add(new CreateCommand());}}; + add(new CreateCommand()); }}; commands.addAll(com); HashSet> actualResult = new HashSet>(commands); - Shell shell = new Shell(actualResult); - String databaseDirectory = System.getProperty("fizteh.db.dir"); + Shell shell = new Shell(actualResult); + String databaseDirectory = System.getProperty("fizteh.db.dir"); if (databaseDirectory == null) { System.err.println("You haven't set database directory"); @@ -54,5 +54,5 @@ public static void main(String[] args) { System.exit(1); } shell.run(args, shell); - } + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableShellState.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableShellState.java index 76599dec7..2b60e8ae2 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableShellState.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StorableShellState.java @@ -11,95 +11,95 @@ import ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap.MultifileMapShellStateInterface; public class StorableShellState implements MultifileMapShellStateInterface { - Table table; - TableProvider tableProvider; - - public StorableShellState(TableProvider provider) { - tableProvider = provider; - } - - - public Storeable put(String key, Storeable value) { - return table.put(key, value); - } - - public Storeable get(String key) { - return table.get(key); - } - - public int commit() { - try { - return table.commit(); - } catch (IOException e) { - return -1; - } - } - - public int rollback() { - return table.rollback(); - } - - public int size() { - return table.size(); - } - - public Storeable remove(String key) { - return table.remove(key); - } - - public Table getTable() { - return table; - } - - public String keyToString(String key) { - return key; - } - - public String valueToString(Storeable value) { - String string = tableProvider.serialize(table, value); - return string; - } - - public String parseKey(String key) { - return key; - } - - public Storeable parseValue(String value) { - try { + Table table; + TableProvider tableProvider; + + public StorableShellState(TableProvider provider) { + tableProvider = provider; + } + + + public Storeable put(String key, Storeable value) { + return table.put(key, value); + } + + public Storeable get(String key) { + return table.get(key); + } + + public int commit() { + try { + return table.commit(); + } catch (IOException e) { + return -1; + } + } + + public int rollback() { + return table.rollback(); + } + + public int size() { + return table.size(); + } + + public Storeable remove(String key) { + return table.remove(key); + } + + public Table getTable() { + return table; + } + + public String keyToString(String key) { + return key; + } + + public String valueToString(Storeable value) { + String string = tableProvider.serialize(table, value); + return string; + } + + public String parseKey(String key) { + return key; + } + + public Storeable parseValue(String value) { + try { return tableProvider.deserialize(table, value); } catch (ParseException e) { return null; } - } - - public Table useTable(String name) { - Table temp = tableProvider.getTable(name); - if (temp != null) { - table = temp; - } - return temp; - } - - public Table createTable(String arguments) { - TableInfo info = null; + } + + public Table useTable(String name) { + Table temp = tableProvider.getTable(name); + if (temp != null) { + table = temp; + } + return temp; + } + + public Table createTable(String arguments) { + TableInfo info = null; info = LocalUtils.parseCreateCommand(arguments); try { return tableProvider.createTable(info.getName(), info.getColumnsTypes()); } catch (IOException e) { return null; } - } - - public void dropTable(String name) throws IOException { - tableProvider.removeTable(name); - if (table.getName().equals(name)) { - table = null; - } - - } - - public String getCurrentTableName() { - return table.getName(); - } + } + + public void dropTable(String name) throws IOException { + tableProvider.removeTable(name); + if (table.getName().equals(name)) { + table = null; + } + + } + + public String getCurrentTableName() { + return table.getName(); + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTableBuilder.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTableBuilder.java index ee5380c63..39a0d36a1 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTableBuilder.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTableBuilder.java @@ -10,29 +10,29 @@ import ru.fizteh.fivt.storage.structured.Storeable; public class StoreableTableBuilder implements TableBuilder { - DatabaseTableProvider provider; - DatabaseTable table; - - private int currentDir; - private int currentFile; - - public StoreableTableBuilder(DatabaseTableProvider provider, DatabaseTable table) { + DatabaseTableProvider provider; + DatabaseTable table; + + private int currentDir; + private int currentFile; + + public StoreableTableBuilder(DatabaseTableProvider provider, DatabaseTable table) { this.provider = provider; this.table = table; } - - public String get(String key) { - Storeable val = table.get(key); + + public String get(String key) { + Storeable val = table.get(key); try { String presentation = provider.serialize(table, val); return presentation; } catch (ColumnFormatException e) { return null; } - } + } - public void put(String key, String value) { - GlobalUtils.checkKeyPlacement(key, currentDir, currentFile); + public void put(String key, String value) { + GlobalUtils.checkKeyPlacement(key, currentDir, currentFile); Storeable objectValue = null; try { @@ -41,21 +41,21 @@ public void put(String key, String value) { System.err.println(e.getMessage()); } table.put(key, objectValue); - - } + + } - public Set getKeys() { - return table.rawGetKeys(); - } + public Set getKeys() { + return table.rawGetKeys(); + } - public File getTableDirectory() { - return new File(table.getParentDirectory(), table.getName()); - } + public File getTableDirectory() { + return new File(table.getParentDirectory(), table.getName()); + } - public void setCurrentFile(File curFile) { - currentDir = GlobalUtils.parseDirNumber(curFile.getParentFile()); + public void setCurrentFile(File curFile) { + currentDir = GlobalUtils.parseDirNumber(curFile.getParentFile()); currentFile = GlobalUtils.parseFileNumber(curFile); - - } - + + } + } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTypes.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTypes.java index 956b531dc..c04554121 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTypes.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/StoreableTypes.java @@ -5,93 +5,93 @@ import java.util.Map; public enum StoreableTypes { - - INTEGER("int", Integer.class) { - public Object ParseValue(String arg) { - return Integer.parseInt(arg); - } - }, - - LONG("long", Long.class) { - public Object ParseValue(String arg) { - return Long.parseLong(arg); - } - }, - - FLOAT("float", Float.class) { - public Object ParseValue(String arg) { - return Float.parseFloat(arg); - } - }, - - DOUBLE("double", Double.class) { - public Object ParseValue(String arg) { - return Double.parseDouble(arg); - } - }, - - STRING("String", String.class) { - public Object ParseValue(String arg) { - return arg; - } - }, - - BYTE("byte", Byte.class) { - public Object ParseValue(String arg) { - return Byte.parseByte(arg); - } - }, - - BOOLEAN("boolean", Boolean.class) { - public Object ParseValue(String arg) { - return Boolean.parseBoolean(arg); - } - }; - - private final String name; - private final Class type; - - private StoreableTypes(String name, Class type) { - this.name = name; - this.type = type; - } - - private static final Map typesByName; - private static final Map, StoreableTypes> typesByClass; - - static { - HashMap tempByName = new HashMap<>(); - HashMap, StoreableTypes> tempByClass = new HashMap<>(); - for (StoreableTypes value : values()) { - tempByName.put(value.name, value); - tempByClass.put(value.type, value); - } - typesByName = Collections.unmodifiableMap(tempByName); - typesByClass = Collections.unmodifiableMap(tempByClass); - } - public static Class getTypeByName(String name) { - StoreableTypes formatter = typesByName.get(name); - if (formatter == null) { - throw new IllegalArgumentException("wrong type (" + name + ')'); - } - return formatter.type; - } - - public static String getSimpleName(Class type) { - StoreableTypes formatter = typesByClass.get(type); - if (formatter == null) { - throw new IllegalArgumentException("unknown format"); - } - return formatter.name; - } - - public abstract Object ParseValue(String string); - - public static Object parseByClass(String string, Class type) { - StoreableTypes formatter = typesByClass.get(type); - if (formatter == null) { - throw new IllegalArgumentException ("wrong type (" + type + ')'); - } - return formatter.ParseValue(string); - } + + INTEGER("int", Integer.class) { + public Object parseValue(String arg) { + return Integer.parseInt(arg); + } + }, + + LONG("long", Long.class) { + public Object parseValue(String arg) { + return Long.parseLong(arg); + } + }, + + FLOAT("float", Float.class) { + public Object parseValue(String arg) { + return Float.parseFloat(arg); + } + }, + + DOUBLE("double", Double.class) { + public Object parseValue(String arg) { + return Double.parseDouble(arg); + } + }, + + STRING("String", String.class) { + public Object parseValue(String arg) { + return arg; + } + }, + + BYTE("byte", Byte.class) { + public Object parseValue(String arg) { + return Byte.parseByte(arg); + } + }, + + BOOLEAN("boolean", Boolean.class) { + public Object parseValue(String arg) { + return Boolean.parseBoolean(arg); + } + }; + + private final String name; + private final Class type; + + private StoreableTypes(String name, Class type) { + this.name = name; + this.type = type; + } + + private static final Map TYPES_BY_NAME; + private static final Map, StoreableTypes> TYPES_BY_CLASS; + + static { + HashMap tempByName = new HashMap<>(); + HashMap, StoreableTypes> tempByClass = new HashMap<>(); + for (StoreableTypes value : values()) { + tempByName.put(value.name, value); + tempByClass.put(value.type, value); + } + TYPES_BY_NAME = Collections.unmodifiableMap(tempByName); + TYPES_BY_CLASS = Collections.unmodifiableMap(tempByClass); + } + public static Class getTypeByName(String name) { + StoreableTypes formatter = TYPES_BY_NAME.get(name); + if (formatter == null) { + throw new IllegalArgumentException("wrong type (" + name + ')'); + } + return formatter.type; + } + + public static String getSimpleName(Class type) { + StoreableTypes formatter = TYPES_BY_CLASS.get(type); + if (formatter == null) { + throw new IllegalArgumentException("unknown format"); + } + return formatter.name; + } + + public abstract Object parseValue(String string); + + public static Object parseByClass(String string, Class type) { + StoreableTypes formatter = TYPES_BY_CLASS.get(type); + if (formatter == null) { + throw new IllegalArgumentException("wrong type (" + type + ')'); + } + return formatter.parseValue(string); + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/TableInfo.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/TableInfo.java index 66d82981a..86e3666d6 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/TableInfo.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/TableInfo.java @@ -4,24 +4,24 @@ import java.util.List; public class TableInfo { - private String name; - private List> typesOfColumns; - - public TableInfo(String name) { - this.name = name; - this.typesOfColumns = new ArrayList>(); - } - - public void addColumn(Class columnType) { - typesOfColumns.add(columnType); - } - - public List> getColumnsTypes() { - return typesOfColumns; - } - - public String getName() { - return name; - } - + private String name; + private List> typesOfColumns; + + public TableInfo(String name) { + this.name = name; + this.typesOfColumns = new ArrayList>(); + } + + public void addColumn(Class columnType) { + typesOfColumns.add(columnType); + } + + public List> getColumnsTypes() { + return typesOfColumns; + } + + public String getName() { + return name; + } + } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlDeserializer.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlDeserializer.java index 36983b7cc..01b182b42 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlDeserializer.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlDeserializer.java @@ -11,66 +11,66 @@ import ru.fizteh.fivt.storage.structured.ColumnFormatException; public class XmlDeserializer { - String representation; - XMLStreamReader reader; - - public XmlDeserializer(String representation) throws ParseException { - this.representation = representation; - try { - reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(representation)); - if (!reader.hasNext()) { - throw new ParseException("xml presentation is empty", 0); - } - int type = reader.next(); - if (type != XMLStreamConstants.START_ELEMENT) { - throw new ParseException("incorrect xml", 0); - } - if (!reader.getName().getLocalPart().equals("row")) { - throw new ParseException("incorrect xml", 0); - } - - } catch (XMLStreamException e) { - throw new ParseException("error in deserializer: " + e.getMessage(), 0); - } - } - - public Object getNext(Class typeExpected) throws ColumnFormatException, ParseException { - Object val = null; - try { - int type = reader.next(); - String k = reader.getName().getLocalPart(); - if(type != XMLStreamConstants.START_ELEMENT || !k.equals("col")) { - if (type == XMLStreamConstants.START_ELEMENT && k.equals("null")) { - reader.next(); - return val; - } - throw new ParseException ("incorrect xml", 0); - } - type = reader.next(); - if (type == XMLStreamConstants.CHARACTERS) { - val = StoreableTypes.parseByClass(reader.getText(), typeExpected); - } else { - if (!reader.getName().getLocalPart().equals("null")) { + String representation; + XMLStreamReader reader; + + public XmlDeserializer(String representation) throws ParseException { + this.representation = representation; + try { + reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(representation)); + if (!reader.hasNext()) { + throw new ParseException("xml presentation is empty", 0); + } + int type = reader.next(); + if (type != XMLStreamConstants.START_ELEMENT) { + throw new ParseException("incorrect xml", 0); + } + if (!reader.getName().getLocalPart().equals("row")) { + throw new ParseException("incorrect xml", 0); + } + + } catch (XMLStreamException e) { + throw new ParseException("error in deserializer: " + e.getMessage(), 0); + } + } + + public Object getNext(Class typeExpected) throws ColumnFormatException, ParseException { + Object val = null; + try { + int type = reader.next(); + String k = reader.getName().getLocalPart(); + if (type != XMLStreamConstants.START_ELEMENT || !k.equals("col")) { + if (type == XMLStreamConstants.START_ELEMENT && k.equals("null")) { + reader.next(); + return val; + } + throw new ParseException("incorrect xml", 0); + } + type = reader.next(); + if (type == XMLStreamConstants.CHARACTERS) { + val = StoreableTypes.parseByClass(reader.getText(), typeExpected); + } else { + if (!reader.getName().getLocalPart().equals("null")) { + throw new ParseException("incorrect xml", 0); + } + val = null; + type = reader.next(); + if (type != XMLStreamConstants.END_ELEMENT) { throw new ParseException("incorrect xml", 0); } - val = null; - type = reader.next(); - if (type != XMLStreamConstants.END_ELEMENT) { - throw new ParseException("incorrect xml", 0); - } - } - type = reader.next(); - if (type != XMLStreamConstants.END_ELEMENT) { - throw new ParseException("incorrect xml", 0); - } - } catch (XMLStreamException e) { - throw new ParseException("error in deserializer: " + e.getMessage(), 0); - } - return val; - } - - public void close() throws ParseException, IOException { - try { + } + type = reader.next(); + if (type != XMLStreamConstants.END_ELEMENT) { + throw new ParseException("incorrect xml", 0); + } + } catch (XMLStreamException e) { + throw new ParseException("error in deserializer: " + e.getMessage(), 0); + } + return val; + } + + public void close() throws ParseException, IOException { + try { int type = reader.next(); if (type != XMLStreamConstants.END_ELEMENT && type != XMLStreamConstants.END_DOCUMENT) { throw new ParseException("incorrect xml", 0); @@ -78,5 +78,5 @@ public void close() throws ParseException, IOException { } catch (XMLStreamException e) { throw new IOException("error while deserializing: " + e.getMessage()); } - } + } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlSerializer.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlSerializer.java index 0c9958ef2..ca913ce56 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlSerializer.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/XmlSerializer.java @@ -9,12 +9,12 @@ import javax.xml.stream.XMLStreamWriter; public class XmlSerializer { - StringWriter strWriter = new StringWriter(); - XMLStreamWriter writer = null; - - public XmlSerializer() throws IOException { - XMLOutputFactory factory = XMLOutputFactory.newInstance(); - try { + StringWriter strWriter = new StringWriter(); + XMLStreamWriter writer = null; + + public XmlSerializer() throws IOException { + XMLOutputFactory factory = XMLOutputFactory.newInstance(); + try { writer = factory.createXMLStreamWriter(strWriter); writer.writeStartElement("row"); } catch (XMLStreamException e) { From 0636a72126b5f67bdef1c92efc91e94d0bc70a1e Mon Sep 17 00:00:00 2001 From: isItJavaOrSomething Date: Tue, 23 Dec 2014 17:56:16 +0400 Subject: [PATCH 14/14] Fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Если я правильно понял -- более гранулярный означал менее общий. Добавил удаление папки после её создания. Добавил локи там где их не хватало. --- .../multifilemap/DatabaseTest.java | 4 +++ .../storable/DatabaseTableProvider.java | 27 +++++++++++++------ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java index 2ebc9132b..63932ea70 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/multifilemap/DatabaseTest.java @@ -1,6 +1,8 @@ package ru.fizteh.fivt.students.NikolaiKrivchanskii.multifilemap; +import java.io.File; + import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -84,5 +86,7 @@ public void testRemoveTableIllegalStateException() { public void testAfter() { provider.removeTable("table1"); provider.removeTable("table2"); + File f = new File("C:\\temp\\database_test"); + f.delete(); } } diff --git a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java index eb40486b8..81d5d5f78 100644 --- a/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java +++ b/src/ru/fizteh/fivt/students/NikolaiKrivchanskii/storable/DatabaseTableProvider.java @@ -12,6 +12,7 @@ import java.util.Map.Entry; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; import ru.fizteh.fivt.students.NikolaiKrivchanskii.filemap.GlobalUtils; import ru.fizteh.fivt.storage.structured.ColumnFormatException; @@ -54,8 +55,13 @@ public DatabaseTableProvider(String databaseDirPath) { } public List getTableNames() { - List toReturnSafe = new LinkedList(tables.keySet()); - return toReturnSafe; + try { + tableLock.lock(); + List toReturnSafe = new LinkedList(tables.keySet()); + return toReturnSafe; + } finally { + tableLock.unlock(); + } } public Table getTable(String name) { @@ -81,7 +87,6 @@ public Table getTable(String name) { public Table createTable(String name, List> columnTypes) throws IOException { try { - tableLock.lock(); if (name == null || name.isEmpty()) { throw new IllegalArgumentException("table's name cannot be null"); } @@ -94,6 +99,7 @@ public Table createTable(String name, List> columnTypes) throws IOExcep return null; } DatabaseTable table = new DatabaseTable(this, databaseDirPath, name, columnTypes); + tableLock.lock(); tables.put(name, table); return table; } finally { @@ -125,11 +131,16 @@ public void removeTable(String name) throws IOException { } public HashMap showTables() { - HashMap content = new HashMap(); - for (Entry contents : tables.entrySet()) { - content.put(contents.getKey(), contents.getValue().size()); - } - return content; + try { + tableLock.lock(); + HashMap content = new HashMap(); + for (Entry contents : tables.entrySet()) { + content.put(contents.getKey(), contents.getValue().size()); + } + return content; + } finally { + tableLock.unlock(); + } } public String serialize(Table table, Storeable value) throws ColumnFormatException {