diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Functional.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Functional.java deleted file mode 100644 index 582fdc942..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Functional.java +++ /dev/null @@ -1,56 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap; - -import java.util.*; - -class Functional { - private Map map; - - public Functional(Map map) { - this.map = map; - } - - void put(String key, String value) { - if (map.containsKey(key)) { - System.out.println("overwrite"); - System.out.println(map.get(key)); - } else { - System.out.println("new"); - } - map.put(key, value); - } - - void get(String key) { - if (map.containsKey(key)) { - System.out.println("found"); - System.out.println(map.get(key)); - } else { - System.out.println("not found"); - } - } - - void remove(String key) { - if (map.containsKey(key)) { - map.remove(key); - } else { - System.out.println("not found"); - } - - } - - void list() { - Set st = map.keySet(); - int counterKeys = 0; - if (st.size() == 0) { - System.out.println(); - } else { - for (String key : st) { - System.out.print(key); - if (st.size() > 1 && (counterKeys + 1) != st.size()) { - System.out.print(", "); - counterKeys++; - } - } - System.out.println(); - } - } -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/MainClass.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/MainClass.java deleted file mode 100644 index d5d98742c..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/MainClass.java +++ /dev/null @@ -1,23 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap; - -import java.io.*; -import java.util.*; - -public class MainClass { - - public static void main(String[] args) { - Reader rd = new Reader(System.getProperty("db.file").toString()); - Map coll = new HashMap(); - coll = rd.read(); - Set show = coll.keySet(); - ModeWork mw = new ModeWork(coll); - if (args.length == 0) { - mw.usermode(); - } else { - mw.interactive(args); - } - Functional fn = new Functional(coll); - Write wr = new Write(System.getProperty("db.file").toString()); - wr.write(coll); - } -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/ModeWork.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/ModeWork.java deleted file mode 100644 index 20adc4774..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/ModeWork.java +++ /dev/null @@ -1,68 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap; - -import java.util.*; - -class ModeWork { - private Map map; - - public ModeWork(Map time) { - map = time; - } - - int stepMode(String[] array, Functional f, int index) { - switch (array[0 + index]) { - case "put": - f.put(array[1 + index], array[2 + index]); - return 2; - case "get": - f.get(array[1 + index]); - return 1; - case "remove": - f.remove(array[1 + index]); - return 1; - case "list": - f.list(); - return 1; - case "exit": - return -1; - default: - return -1; - } - } - - void usermode() { - Functional func = new Functional(map); - String str = new String(); - String[] array; - Scanner rd = new Scanner(System.in); - while (true) { - System.out.print("$ "); - str = rd.nextLine().toString(); - array = str.trim().split(" "); - if (stepMode(array, func, 0) == -1) { - break; - } - } - - } - - void interactive(String[] mass) { - int offset = 0; - Functional func = new Functional(map); - int i = 0; - while (true) { - if (i < mass.length) { - offset = stepMode(mass, func, i); - i += offset; - if (offset == -1) { - break; - } - i++; - } else { - break; - } - } - - } - -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Reader.java deleted file mode 100644 index c4ac69481..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Reader.java +++ /dev/null @@ -1,57 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap; - -import java.util.*; -import java.io.*; - -public class Reader { - private String filepath; - private HashMap map; - - public Reader(String path) { - filepath = path; - map = new HashMap(); - } - - public HashMap read() { - StringBuilder keyBuilder = new StringBuilder(); - StringBuilder valueBuilder = new StringBuilder(); - int length = 0; - try (DataInputStream rd = new DataInputStream(new FileInputStream( - filepath))) { - while (true) { - try { - length = rd.readInt(); - for (int i = 0; i < length; i++) { - keyBuilder.append(rd.readChar()); - - } - length = rd.readInt(); - for (int i = 0; i < length; i++) { - valueBuilder.append(rd.readChar()); - - } - map.put(keyBuilder.toString(), valueBuilder.toString()); - keyBuilder.replace(0, keyBuilder.length(), ""); - valueBuilder.replace(0, valueBuilder.length(), ""); - - } catch (EOFException e) { - break; - } - - } - - } catch (FileNotFoundException e) { - try { - File newdb = new File(filepath); - newdb.createNewFile(); - } catch (IOException err) { - System.err.print(err.toString()); - } - } catch (IOException e) { - System.err.print(e.toString()); - } - - return map; - } - -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Write.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Write.java deleted file mode 100644 index 1b04179cc..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Write.java +++ /dev/null @@ -1,31 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap; - -import java.util.*; -import java.io.*; - -public class Write { - private String filepath; - - public Write(String path) { - filepath = path; - } - - public void write(Map map) { - try (DataOutputStream out = new DataOutputStream(new FileOutputStream( - filepath))) { - Set st = map.keySet(); - for (String time : st) { - out.writeInt(time.length()); - out.writeChars(time); - out.writeInt(map.get(time).length()); - out.writeChars(map.get(time)); - - } - - } catch (FileNotFoundException e) { - System.err.print("Not Found " + e.toString()); - } catch (IOException e) { - System.err.print("IOException " + e.toString()); - } - } -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/ConstantValue.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/ConstantValue.java new file mode 100644 index 000000000..900759075 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/ConstantValue.java @@ -0,0 +1,16 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; + +/** + * + * @author Андрей + */ +public interface ConstantValue { + + static final int TOTAL_SUB_STRING = 16; + static final String DIRECTORY_SUFFIX = ".dir"; +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/DeleteAlgorithm.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/DeleteAlgorithm.java new file mode 100644 index 000000000..2e2672264 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/DeleteAlgorithm.java @@ -0,0 +1,28 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; + +import java.io.File; + +/** + * + * @author Андрей + */ +public interface DeleteAlgorithm { + + default public void deleteDirectory(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + for (String child : children) { + File tmpFile = new File(dir, child); + deleteDirectory(tmpFile); + } + dir.delete(); + } else { + dir.delete(); + } + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/FactoryImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/FactoryImplements.java new file mode 100644 index 000000000..f96850c3e --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/FactoryImplements.java @@ -0,0 +1,26 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; + +import java.io.IOException; + +/** + * Класс @class FactoryImplements отвечает за фабрику по созданию таблиц. + * Имплиментируя интерфейс TableProviderFactory, переопределяет метод по + * созданию провайдера базы данных. + * + * @author Timokhin Andrew + */ +public class FactoryImplements implements TableProviderFactory { + + @Override + public TableProvider create(String dir) { + if (dir == null) { + throw new IllegalArgumentException( + "String representing directory is null"); + } + try { + return new TableProviderImplements(dir); + } catch (IOException exception) { + throw new RuntimeException(exception); + } + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java new file mode 100644 index 000000000..e21aa3a50 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java @@ -0,0 +1,8 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; + +public class KeyNullAndNotFound extends Exception { + + public KeyNullAndNotFound(String description) { + super(description); + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Reader.java new file mode 100644 index 000000000..28816afeb --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Reader.java @@ -0,0 +1,85 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; + +import java.io.DataInputStream; +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Класс @class Reader отвечает за физическое чтение данных из файловой системы. + * + * + * @author Timokhin Andrew + */ +public class Reader implements ConstantValue { + + private StringBuilder readKeyValue(DataInputStream rd) throws IOException { + StringBuilder string = new StringBuilder(); + int length = rd.readInt(); + for (int k = 0; k < length; k++) { + string.append(rd.readChar()); + } + return string; + } + + public void read(TableProviderImplements tp) throws IOException { + StringBuilder keyBuilder; + StringBuilder valueBuilder; + String path = tp.getDir(); + File testDir = new File(path); + if (testDir.list() != null) { + for (String time : testDir.list()) { + Path pathToFile = Paths.get(path, time); + File checkDir = new File(pathToFile.toString()); + if (checkDir.isDirectory()) { + tp.createTable(time); + TableImplement dataBase = (TableImplement) tp.getTable(time); + dataBase.setPath(tp.getDir()); + for (int i = 0; i < TOTAL_SUB_STRING; i++) { + Path pathToDb = Paths.get(path, time, + i + DIRECTORY_SUFFIX); + File locDB = new File(pathToDb.toString()); + if (locDB.exists()) { + for (String file : locDB.list()) { + Path pathToLocalDb = Paths.get( + locDB.getAbsolutePath(), file); + try (DataInputStream rd = new DataInputStream( + new FileInputStream( + pathToLocalDb.toString()))) { + while (true) { + try { + keyBuilder = readKeyValue(rd); + valueBuilder = readKeyValue(rd); + + dataBase.put( + keyBuilder.toString(), + valueBuilder.toString()); + dataBase.getBackup().put( + keyBuilder.toString(), + valueBuilder.toString()); + keyBuilder.replace(0, + keyBuilder.length(), ""); + valueBuilder.replace(0, + valueBuilder.length(), ""); + } catch (EOFException e) { + rd.close(); + break; + } + + } + } catch (FileNotFoundException exceptionFileNotFound) { + throw new RuntimeException( + exceptionFileNotFound); + } + } + } + } + } + } + } + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Table.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Table.java new file mode 100644 index 000000000..1e48afe75 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Table.java @@ -0,0 +1,77 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; + +import java.util.List; + +public interface Table { + + /** + * Возвращает название базы данных. + * + * @return name representing database + */ + String getName(); + + /** + * Получает значение по указанному ключу. + * + * @param key Ключ. + * @return Значение. Если не найдено, возвращает null. + * @throws KeyNullAndNotFound + * + * @throws IllegalArgumentException Если значение параметра key является + * null. + */ + String get(String key) throws IllegalArgumentException, KeyNullAndNotFound; + + /** + * Устанавливает значение по указанному ключу. + * + * @param key Ключ. + * @param value Значение. + * @return Значение, которое было записано по этому ключу ранее. Если ранее + * значения не было записано, возвращает null. + * + * @throws IllegalArgumentException Если значение параметров key или value + * является null. + */ + String put(String key, String value); + + /** + * Удаляет значение по указанному ключу. + * + * @param key Ключ. + * @return Значение. Если не найдено, возвращает null. + * + * @throws IllegalArgumentException Если значение параметра key является + * null. + */ + String remove(String key); + + /** + * Возвращает количество ключей в таблице. + * + * @return Количество ключей в таблице. + */ + int size(); + + /** + * Выполняет фиксацию изменений. + * + * @return Количество сохранённых ключей. + */ + int commit(); + + /** + * Выполняет откат изменений с момента последней фиксации. + * + * @return Количество отменённых ключей. + */ + int rollback(); + + /** + * Выводит список ключей таблицы + * + * @return Список ключей. + */ + List list(); +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableImplement.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableImplement.java new file mode 100644 index 000000000..910fbe776 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableImplement.java @@ -0,0 +1,203 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; + +/** + * Класс TableImplement содержит логику работы таблицы базы данных. В нем + * переопределены все методы, которые заявлены в интерфейсе Table + * + * @author Timokhin Andrew + */ +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class TableImplement implements Table { + + private String name; + private String path; + private Map map; + private Map backup; + + public TableImplement(String name, String path) { + this.path = path; + this.name = name; + map = new HashMap<>(); + backup = new HashMap<>(); + } + + public String getPath() { + return path; + } + + public void setPath(String newPath) { + this.path = newPath; + } + + public Map getBackup() { + return backup; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public int size() { + return map.size(); + } + + @Override + public String get(String key) throws KeyNullAndNotFound { + if (key == null) { + throw new KeyNullAndNotFound("Key is null"); + } + if (map.containsKey(key)) { + return map.get(key); + } + return null; + } + + @Override + public String put(String key, String value) throws IllegalArgumentException { + String previousValue = null; + if (key == null || value == null) { + throw new IllegalArgumentException( + "Key or (and) value is wrong."); + } + { + if (map.containsKey(key)) { + previousValue = map.get(key); + } + } + map.put(key, value); + return previousValue; + } + + @Override + public String remove(String key) throws IllegalArgumentException { + String time = null; + if (key == null) { + throw new IllegalArgumentException("Key shouldn't be null"); + } + if (map.containsKey(key)) { + time = map.get(key); + map.remove(key); + } + return time; + } + + @Override + public List list() { + return new ArrayList<>(map.keySet()); + } + + public int totalChanges() { + int counter = 0; + if (backup == null && map != null) { + return map.size(); + } + if (backup != null && map != null) { + Set backupKey = backup.keySet(); + for (String timeKey : backupKey) { + if ((map.containsKey(timeKey) + && !(backup.get(timeKey).equals(map.get(timeKey)))) || !map.containsKey(timeKey)) { + counter++; + } + } + backupKey = map.keySet(); + for (String timeKey : backupKey) { + if (!backup.containsKey(timeKey)) { + counter++; + } + } + } + return counter; + + } + + @Override + public int commit() { + try { + return this.writeToDisk(); + } catch (IOException exception) { + throw new RuntimeException(exception); + } + } + + public int writeToDisk() throws IOException, IllegalArgumentException { + Reader reader = new Reader(); + FactoryImplements factory = new FactoryImplements(); + TableProviderImplements tableProvider = (TableProviderImplements) factory + .create(path); + reader.read(tableProvider); + copyOfMap(this.map, this.backup); + Writer writer = new Writer(); + + { + if (tableProvider.getAvailableTables().contains(this.getName())) { + Map tmp = new HashMap<>(); + List copy = tableProvider.getTable(this.getName()).list(); + for (String copyString : copy) { + try { + tmp.put(new String(copyString), + new String( + tableProvider.getTable(this.getName()).get(copyString))); + } catch (KeyNullAndNotFound exception) { + continue; + } + } + this.backup = new HashMap<>(tmp); + } else { + tableProvider.createTable(this.name); + this.backup = new HashMap<>(); + } + + tableProvider.removeTable(this.getName()); + tableProvider.createTable(this.getName()); + for (String timeString : this.list()) { + try { + tableProvider.getTable(this.getName()).put(new String(timeString), new String(this.get(timeString))); + } catch (KeyNullAndNotFound ex) { + continue; + } + } + } + + if (this.totalChanges() > 0) { + try { + writer.write(tableProvider); + } catch (KeyNullAndNotFound nullKey) { + System.out.println(nullKey.toString()); + } + } + return this.totalChanges(); + } + + @Override + public int rollback() throws NullPointerException { + Map copyMap = new HashMap<>(this.map); + if (this.backup != null) { + this.map = new HashMap<>(this.backup); + } else { + this.map = new HashMap<>(); + } + this.backup = copyMap; + return this.commit(); + } + + private void copyOfMap(Map from, Map to) { + Map timeMap = new HashMap<>(); + for (String timeKey : from.keySet()) { + timeMap.put(new String(timeKey), new String(from.get(timeKey))); + } + to = new HashMap(timeMap); + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProvider.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProvider.java new file mode 100644 index 000000000..152e8c771 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProvider.java @@ -0,0 +1,37 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; + +public interface TableProvider { + + /** + * Возвращает таблицу с указанным названием. + * + * @param name Название таблицы. + * @return Объект, представляющий таблицу. Если таблицы с указанным именем + * не существует, возвращает null. + * @throws IllegalArgumentException Если название таблицы null или имеет + * недопустимое значение. + */ + Table getTable(String name); + + /** + * Создаёт таблицу с указанным названием. + * + * @param name Название таблицы. + * @return Объект, представляющий таблицу. Если таблица уже существует, + * возвращает null. + * @throws IllegalArgumentException Если название таблицы null или имеет + * недопустимое значение. + */ + Table createTable(String name); + + /** + * Удаляет таблицу с указанным названием. + * + * @param name Название таблицы. + * @throws IllegalArgumentException Если название таблицы null или имеет + * недопустимое значение. + * @throws IllegalStateException Если таблицы с указанным названием не + * существует. + */ + void removeTable(String name); +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderFactory.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderFactory.java new file mode 100644 index 000000000..85fbc2af8 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderFactory.java @@ -0,0 +1,14 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; + +public interface TableProviderFactory { + + /** + * Возвращает объект для работы с базой данных. + * + * @param dir Директория с файлами базы данных. + * @return Объект для работы с базой данных. + * @throws IllegalArgumentException Если значение директории null или имеет + * недопустимое значение. + */ + TableProvider create(String dir); +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderImplements.java new file mode 100644 index 000000000..455b49972 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderImplements.java @@ -0,0 +1,86 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * @author Timokhin Andrew + */ +public class TableProviderImplements implements TableProvider, DeleteAlgorithm { + + private final Map collection; + private final String dir; + + public TableProviderImplements(String dir) throws IOException { + this.dir = dir; + collection = new HashMap<>(); + Reader rd = new Reader(); + rd.read(this); + } + + public Set getAvailableTables() { + return collection.keySet(); + } + + @Override + public Table getTable(String name) throws IllegalArgumentException { + if (name == null) { + throw new IllegalArgumentException( + "Name of DataBase is null"); + } + if (collection.containsKey(name)) { + return collection.get(name); + } + return null; + } + + @Override + public Table createTable(String name) throws IllegalArgumentException { + if (name == null) { + throw new IllegalArgumentException( + "Name of DataBase is null. Please, enter correct name"); + } + + if (collection.containsKey(name)) { + return null; + } + collection.put(name, new TableImplement(name, dir)); + return collection.get(name); + + } + + @Override + public void removeTable(String name) throws IllegalArgumentException, + IllegalStateException { + if (name == null) { + throw new IllegalArgumentException( + "Name of DataBase is null. Please, enter correct name"); + } + if (collection.containsKey(name)) { + Path path = Paths.get(collection.get(name).getPath(), collection + .get(name).getName()); + File file = new File(path.toString()); + this.deleteDirectory(file); + collection.remove(name); + return; + } + throw new IllegalStateException("Requested database don't exist"); + } + + public int size() { + int size = 0; + for (String nameTable : collection.keySet()) { + size += collection.get(nameTable).size(); + } + return size; + } + + public String getDir() { + return dir; + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Writer.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Writer.java new file mode 100644 index 000000000..f8d91d242 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Writer.java @@ -0,0 +1,89 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Set; +import static java.lang.Math.abs; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; + +/** + * Класс @class Writer отвечает за физическую запись информации с на жесткий + * диск или другой носитель информации. Логика работы устойчива к новым папкам и + * т.д. + * + * @author Timokhin Andrew + */ +public class Writer implements ConstantValue, DeleteAlgorithm { + + boolean checkDir(String name) { + File tmpFile = new File(name); + return tmpFile.exists(); + + } + + void createDir(String path) { + File tmpDir = new File(path); + tmpDir.mkdir(); + } + + void createFile(String path) throws IOException { + + File tmpFile = new File(path); + File prepareToMakeDir = new File(tmpFile.getParent()); + prepareToMakeDir.mkdirs(); + tmpFile.createNewFile(); + } + + public void write(TableProviderImplements tp) throws IOException, KeyNullAndNotFound { + this.deleteDirectory(new File(tp.getDir())); + File baseDir = new File(tp.getDir()); + baseDir.mkdir(); + Set dataBase = tp.getAvailableTables(); + for (String name : dataBase) { + TableImplement ti = (TableImplement) tp.getTable(name); + Path pathToDb = Paths.get(tp.getDir(), ti.getName()); + File dataBaseDir = new File(pathToDb.toString()); + dataBaseDir.mkdir(); + { + ArrayList keyList; + keyList = (ArrayList) ti.list(); + for (String keyFind : keyList) { + Integer dirToWrite = new Integer(abs(keyFind.hashCode() + % TOTAL_SUB_STRING)); + Path localPath = Paths.get(tp.getDir(), ti.getName(), + dirToWrite.toString() + DIRECTORY_SUFFIX); + if (!this.checkDir(localPath.toString())) { + this.createDir(localPath.toString()); + } + dirToWrite = new Integer((ti.get(keyFind) + .hashCode() + % TOTAL_SUB_STRING % TOTAL_SUB_STRING)); + Path localFile = Paths.get(localPath.toString(), + dirToWrite.toString()); + File checkIfExist = new File(localFile.toString()); + if (!this.checkDir(localFile.toString()) + && !checkIfExist.exists()) { + + this.createFile(localFile.toString()); + } + try (DataOutputStream outStream = new DataOutputStream( + new FileOutputStream(localFile.toString(), true))) { + + outStream.writeInt(keyFind.length()); + outStream.writeChars(keyFind); + + outStream.writeInt(ti.get(keyFind).toString() + .length()); + outStream.writeChars(ti.get(keyFind) + .toString()); + } + } + + } + } + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/Commands.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/Commands.java new file mode 100644 index 000000000..39dd55a02 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/Commands.java @@ -0,0 +1,36 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public abstract class Commands { + + int numberOfArguments; + + public Commands(int numberOfArgumentsSet) { + numberOfArguments = numberOfArgumentsSet; + + } + + public abstract TableImplement execute(String[] command, TableProviderImplements table, TableImplement nextTable) throws ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.ExitException; + + public boolean invitationToRepeat(String[] args) { + + if (args.length != numberOfArguments) { + System.out + .println("Current command was not recognized or not complete. Please, try again"); + return true; + } + return false; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/InteractiveMode.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/InteractiveMode.java new file mode 100644 index 000000000..547a70937 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/InteractiveMode.java @@ -0,0 +1,37 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator; + +import java.util.Map; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.KeyNullAndNotFound; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.UnknowCommand; + +/** + * + * @author Timokhin Andrew + * + */ +public class InteractiveMode { + + private final Map allCommand; + private final Commands fail; + + public InteractiveMode(Map allCommand) { + this.allCommand = allCommand; + fail = new UnknowCommand(); + } + + public Commands runCommand(String textToParser) throws UnknownCommandException, + IllegalArgumentException, KeyNullAndNotFound { + String[] commands = textToParser.trim().split(" "); + if (commands.length < 1 || !allCommand.containsKey(commands[0])) { + System.out.println("Details: Wrong command!"); + return fail; + } + return allCommand.get(commands[0]); + + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/UnknownCommandException.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/UnknownCommandException.java new file mode 100644 index 000000000..49704d61a --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/UnknownCommandException.java @@ -0,0 +1,18 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator; + +/** + * + * @author Андрей + */ +public class UnknownCommandException extends Exception { + + public UnknownCommandException(String description) { + super(description); + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CommitCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CommitCommand.java new file mode 100644 index 000000000..209a23d2c --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CommitCommand.java @@ -0,0 +1,35 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class CommitCommand extends Commands { + + public CommitCommand() { + super(1); + } + + @Override + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + + if (invitationToRepeat(commands)) { + return currentTable; + } + if (currentTable != null) { + System.out.println("Total changes -> " + currentTable.commit()); + } else { + System.out.println("No table"); + } + return currentTable; + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CreateCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CreateCommand.java new file mode 100644 index 000000000..2452cc8fb --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CreateCommand.java @@ -0,0 +1,35 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class CreateCommand extends Commands { + + public CreateCommand() { + super(2); + } + + @Override + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } + if (tableProvider.createTable(commands[1]) == null) { + System.out.println("Exist!"); + } else { + System.out.println("created"); + } + return currentTable; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/DropCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/DropCommand.java new file mode 100644 index 000000000..6477940ce --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/DropCommand.java @@ -0,0 +1,36 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class DropCommand extends Commands { + + public DropCommand() { + super(2); + } + + @Override + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) throws IllegalStateException { + if (invitationToRepeat(commands)) { + return currentTable; + } + try { + tableProvider.removeTable(commands[1]); + System.out.println("dropped"); + } catch (IllegalStateException | IllegalArgumentException error) { + throw error; + } + return currentTable; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitCommand.java new file mode 100644 index 000000000..f8fb8d792 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitCommand.java @@ -0,0 +1,40 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class ExitCommand extends Commands { + + public ExitCommand() { + super(1); + } + + /** + * This command needed to exit. + * + * @param commands parsed user input + * @param tableProvider object representing current database + * @param currentTable current Table + * @return always return Exception to close, because customer wish is law + * @throws + * ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.ExitException + */ + @Override + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) throws ExitException { + if (invitationToRepeat(commands)) { + return currentTable; + } + throw new ExitException("Programm ended"); + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitException.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitException.java new file mode 100644 index 000000000..7ee2d7305 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitException.java @@ -0,0 +1,17 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +/** + * + * @author Андрей + */ +public class ExitException extends Exception { + + public ExitException(String description) { + super(description); + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/GetCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/GetCommand.java new file mode 100644 index 000000000..f4aa6d36f --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/GetCommand.java @@ -0,0 +1,48 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.KeyNullAndNotFound; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class GetCommand extends Commands { + + public GetCommand() { + super(2); + } + + @Override + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } + if (currentTable == null) { + System.out.println("No table"); + return null; + } else { + String value; + try { + value = currentTable.get(commands[1]); + if (value != null) { + System.out.println("*value* -> " + value); + } else { + System.out.println("*not exist*"); + } + } catch (KeyNullAndNotFound ex) { + System.out.println("Key is Null. Enter correct key"); + } + + } + return currentTable; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ListCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ListCommand.java new file mode 100644 index 000000000..5e2760aa0 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ListCommand.java @@ -0,0 +1,46 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import java.util.ArrayList; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.KeyNullAndNotFound; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class ListCommand extends Commands { + + public ListCommand() { + super(1); + } + + @Override + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } + if (currentTable == null) { + System.out.println("No table"); + return null; + } else { + ArrayList set; + set = (ArrayList) currentTable.list(); + for (String key : set) { + try { + System.out.println(key + " " + currentTable.get(key)); + } catch (KeyNullAndNotFound ex) { + System.out.println("Null key is wrong!"); + } + } + } + return currentTable; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/Main.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/Main.java new file mode 100644 index 000000000..830dbc19f --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/Main.java @@ -0,0 +1,78 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.InteractiveMode; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; +import java.util.logging.Level; +import java.util.logging.Logger; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.FactoryImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.KeyNullAndNotFound; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.Writer; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.UnknownCommandException; + +public class Main { + + protected static TableImplement table = null; + protected static TableProviderImplements provider; + + static { + try { + provider = new TableProviderImplements(System.getProperty("fizteh.db.dir")); + } catch (IOException ex) { + Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public static void main(String[] args) throws IOException, + IllegalArgumentException, KeyNullAndNotFound, UnknownCommandException { + + Map totalCommands; + + totalCommands = new HashMap<>(); + totalCommands.put("create", new CreateCommand()); + totalCommands.put("put", new PutCommand()); + totalCommands.put("get", new GetCommand()); + totalCommands.put("remove", new RemoveCommand()); + totalCommands.put("drop", new DropCommand()); + totalCommands.put("commit", new CommitCommand()); + totalCommands.put("rollback", new RollbackCommand()); + totalCommands.put("use", new UseCommand()); + totalCommands.put("size", new SizeCommand()); + totalCommands.put("list", new ListCommand()); + totalCommands.put("exit", new ExitCommand()); + + String path = "C:\\DataBase"; + FactoryImplements factory = new FactoryImplements(); + provider = (TableProviderImplements) factory.create(path); + InteractiveMode user = new InteractiveMode(totalCommands); + Scanner sc = new Scanner(System.in); + System.out.print("$ "); + try { + while (true) { + String commands = sc.nextLine(); + + Main.table = user.runCommand(commands).execute(commands.trim().split(" "), Main.provider, Main.table); + System.out.print("$ "); + } + + } catch (ExitException ex) { + System.out.println("Save all changes to the disc? [YES/NO]"); + String userAnswer = sc.nextLine(); + while (!userAnswer.equals("YES") && !userAnswer.equals("NO")) { + System.out.println("try again"); + userAnswer = sc.nextLine(); + } + if (userAnswer.equals("YES")) { + Writer writeToFileSystem = new Writer(); + writeToFileSystem.write(provider); + } + System.out.println("Exited"); + } + + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/PutCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/PutCommand.java new file mode 100644 index 000000000..17704b198 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/PutCommand.java @@ -0,0 +1,41 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class PutCommand extends Commands { + + public PutCommand() { + super(3); + } + + @Override + public TableImplement execute(String[] commands, TableProviderImplements provider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } + if (currentTable == null) { + System.out.println("No table"); + return null; + } else { + String oldValue = currentTable.put(commands[1], commands[2]); + if (oldValue != null) { + System.out.println("*old* -> " + oldValue); + } else { + System.out.println("*new*"); + } + } + return currentTable; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RemoveCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RemoveCommand.java new file mode 100644 index 000000000..972b38685 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RemoveCommand.java @@ -0,0 +1,45 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class RemoveCommand extends Commands { + + public RemoveCommand() { + super(2); + } + + @Override + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } + if (currentTable == null) { + System.out.println("No table"); + return null; + } else { + if (commands[1] == null) { + System.out.println("*wrong key"); + return currentTable; + } + String value = currentTable.remove(commands[1]); + if (value != null) { + System.out.println("*value* -> " + value); + } else { + System.out.println("*not removed, because not exist*"); + } + } + return currentTable; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RollbackCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RollbackCommand.java new file mode 100644 index 000000000..d5591b7fc --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RollbackCommand.java @@ -0,0 +1,36 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class RollbackCommand extends Commands { + + public RollbackCommand() { + super(1); + } + + @Override + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } + + if (currentTable != null) { + System.out.println("Total changes -> " + currentTable.rollback()); + } else { + System.out.println("No table"); + } + return currentTable; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/SizeCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/SizeCommand.java new file mode 100644 index 000000000..640bbf4ed --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/SizeCommand.java @@ -0,0 +1,31 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class SizeCommand extends Commands { + + public SizeCommand() { + super(1); + } + + @Override + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } + System.out.println(tableProvider.size()); + return currentTable; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UnknowCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UnknowCommand.java new file mode 100644 index 000000000..8cb6587cf --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UnknowCommand.java @@ -0,0 +1,29 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; + +/** + * + * @author Андрей + */ +public class UnknowCommand extends Commands { + + public UnknowCommand() { + super(0); + } + + @Override + public TableImplement execute(String[] command, TableProviderImplements table, TableImplement currentTable) throws ExitException { + super.invitationToRepeat("not null".split(" ")); + return currentTable; + + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UseCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UseCommand.java new file mode 100644 index 000000000..3578d2f72 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UseCommand.java @@ -0,0 +1,42 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class UseCommand extends Commands { + + public UseCommand() { + super(2); + } + + @Override + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } + + currentTable = (TableImplement) tableProvider.getTable(commands[1]); + + if (currentTable == null) { + System.out.println("Not exists"); + } else { + if (currentTable.totalChanges() > 0) { + System.out.println("Need commit->" + currentTable.totalChanges()); + } else { + System.out.println("Using"); + } + } + return currentTable; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/FactoryImplementsTest.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/FactoryImplementsTest.java new file mode 100644 index 000000000..de9fba647 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/FactoryImplementsTest.java @@ -0,0 +1,29 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.FactoryImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProvider; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; +import java.io.IOException; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Timokhin Andrew + */ +public class FactoryImplementsTest { + + @Test + public void testCreate() throws IOException { + TableProviderImplements resultOne = (TableProviderImplements) new FactoryImplements() + .create("test"); + assertEquals("test", resultOne.getDir()); + } + + @Test(expected = IllegalArgumentException.class) + public void testCreateIncorrect() { + String dir = null; + TableProvider result = new FactoryImplements().create(dir); + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableImplementTest.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableImplementTest.java new file mode 100644 index 000000000..7ef43ddb6 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableImplementTest.java @@ -0,0 +1,267 @@ +/* + * Модульные тесты базы данных. + * + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.KeyNullAndNotFound; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.FactoryImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProvider; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.Table; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderFactory; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author Timokhin Andrew + */ +public class TableImplementTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + public TableProvider tableProvider; + public String path; + public Table table; + + @Before + public void setUp() { + TableProviderFactory tableProviderFactory = new FactoryImplements(); + path = tmp.newFolder("time").getAbsolutePath(); + tableProvider = tableProviderFactory.create(path); + table = tableProvider.createTable("testing"); + + FactoryImplements factory = new FactoryImplements(); + TableProviderImplements tableProvider = (TableProviderImplements) factory + .create("test"); + Table time = tableProvider.createTable("new"); + time = tableProvider.getTable("new"); + + } + + /** + * Тестирование getName (большо одного нет смысла) + */ + @Test + public void testGetName() { + assertTrue("testing".equals(table.getName())); + } + + @Test(expected = KeyNullAndNotFound.class) + public void testGetNullKey() throws KeyNullAndNotFound { + table.get(null); + } + + /** + * Тесты на size method + */ + @Test + public void testSizeByDefault() { + assertEquals(0, table.size()); + } + + @Test + public void testSizeAfterAddedAndDel() { + table.put("1", "11"); + table.put("2", "22"); + int result = table.size(); + assertEquals(2, result); + table.remove("2"); + result = table.size(); + assertEquals(1, result); + table.remove("1"); + result = table.size(); + assertEquals(0, result); + } + + /** + * Тестирование put метода + */ + @Test(expected = IllegalArgumentException.class) + public void testPutIfKeyIsNull() { + String value = "test_value"; + table.put(null, value); + } + + @Test(expected = IllegalArgumentException.class) + public void testPutIfValueIsNull() { + String key = "test_key"; + table.put(key, null); + } + + @Test(expected = IllegalArgumentException.class) + public void testPutIfValueAndKeyIsNull() { + table.put(null, null); + } + + @Test + public void testPutIfKeyDnHaveInDataBase() { + String key = "test_key"; + String value = "test_value"; + assertNull(table.put(key, value)); + } + + @Test + public void testPutIfKeyHaveInDataBase() { + String key = "test_key"; + String valueOld = "test_value_old"; + String valueNew = "test_value_new"; + + assertNull(table.put(key, valueOld)); + assertEquals(valueOld, table.put(key, valueNew)); + } + + /** + * Тестирование remove метода + */ + @Test(expected = IllegalArgumentException.class) + public void testRemoveIfKeyNull() { + table.remove(null); + } + + @Test + public void testRemoveIfKeyExist() { + String key = "key_test"; + String value = "value_test"; + table.put(key, value); + + assertEquals(value, table.remove(key)); + try { + assertNull(table.get(key)); + } catch (IllegalArgumentException ex) { + Logger.getLogger(TableImplementTest.class.getName()).log(Level.SEVERE, null, ex); + } catch (KeyNullAndNotFound ex) { + Logger.getLogger(TableImplementTest.class.getName()).log(Level.SEVERE, null, ex); + } + } + + @Test + public void testRemoveIfKeyDnExist() { + String key = "key_test"; + + assertNull(table.remove(key)); + } + + /** + * Тестирование метода commit + */ + @Test + public void testCommitIfEmpty() { + assertEquals(0, table.commit()); + } + + @Test + public void testCommitIfFullAnything() { + table.put("id564", "989"); + table.put("id988", "123"); + table.put("id123", "766"); + assertEquals(3, table.commit()); + } + + public void testCommitIfWasRollback() { + table.put("id564", "989"); + table.put("id988", "123"); + table.put("id123", "766"); + table.rollback(); + + assertEquals(0, table.commit()); + } + + public void testCommitAndCommit() { + table.put("id1", "1"); + table.put("id2", "2"); + table.put("id3", "3"); + table.commit(); + table.commit(); + assertEquals(0, table.commit()); + } + + /** + * Тестирование rollback метода + */ + @Test + public void testRollbackIfStateEmpty() { + assertEquals(0, table.rollback()); + } + + @Test() + public void testRollbackNullPointer() { + table.put("id564", "989"); + table.put("id988", "123"); + table.put("id123", "766"); + table.commit(); + table.rollback(); + assertEquals(0, table.size()); + } + + @Test + public void testRollbackSomeChainChanges() { + table.put("1", "1"); + table.put("2", "2"); + table.put("3", "3"); + table.commit(); + table.put("4", "4"); + table.put("54", "54"); + table.commit(); + assertEquals(2, table.rollback()); + } + + @Test + public void testCommitCheckRollbackCheck() throws IllegalArgumentException, KeyNullAndNotFound { + table.put("1", "11"); + table.put("2", "22"); + table.put("3", "33"); + table.commit(); + assertEquals("11", table.get("1")); + assertEquals("22", table.get("2")); + assertEquals("33", table.get("3")); + table.put("4", "44"); + table.put("5", "55"); + table.commit(); + assertEquals("44", table.get("4")); + assertEquals("55", table.get("5")); + table.rollback(); + assertEquals(null, table.get("4")); + assertEquals(null, table.get("5")); + assertEquals("33", table.get("3")); + assertEquals(3, table.size()); + + } + + @Test + public void testCommitCheckChangesRollbackCheck() throws IllegalArgumentException, KeyNullAndNotFound { + table.put("1", "11"); + table.put("2", "22"); + table.put("3", "33"); + table.commit(); + assertEquals("11", table.get("1")); + assertEquals("22", table.get("2")); + assertEquals("33", table.get("3")); + table.put("4", "44"); + table.put("5", "55"); + assertEquals("11", table.remove("1")); + assertEquals("22", table.remove("2")); + assertEquals(null, table.remove("66")); + table.commit(); + table.rollback(); + assertEquals("11", table.get("1")); + assertEquals(3, table.size()); + + } + + @Test + public void extraCheck() throws IllegalArgumentException, KeyNullAndNotFound { + table.put("a", "b"); + table.commit(); + table.put("a", "c"); + table.rollback(); + assertEquals(null, table.get("a")); + + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableProviderImplementsTest.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableProviderImplementsTest.java new file mode 100644 index 000000000..b95c8b2ca --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableProviderImplementsTest.java @@ -0,0 +1,91 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.FactoryImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProvider; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderFactory; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; + +/** + * + * @author Андрей + */ +public class TableProviderImplementsTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + public TableProvider tp; + + @Before + public void setUp() { + TableProviderFactory tpv = new FactoryImplements(); + tp = tpv.create(tmp.newFolder("time").getAbsolutePath()); + } + + /** + * Следующие тесты полностью тестируют реализацию интерфейса + */ + /** + * Тесты getTable метода + */ + @Test(expected = IllegalArgumentException.class) + public void testGetTable() { + tp.getTable(null); + } + + @Test + public void testGetTableNormal() { + tp.createTable("test"); + assertNotNull(tp.getTable("test")); + } + + @Test + public void testGetTableIfDnExist() { + tp.createTable("test"); + assertNull(tp.getTable("blablabla")); + } + + /** + * Тесты createTable метода + */ + @Test(expected = IllegalArgumentException.class) + public void testCreateTable() { + tp.createTable(null); + } + + @Test + // в данном тесте логично объединено два теста + public void testCreateTableIfExist() { + assertNotNull(tp.createTable("test")); + assertNull(tp.createTable("test")); + } + + /** + * Тесты removeTable метода + */ + @Test(expected = IllegalArgumentException.class) + public void testRemoveTable() { + tp.removeTable(null); + + } + + @Test(expected = IllegalStateException.class) + public void testRemoveTableDnExist() { + tp.removeTable("notexist"); + } + + @Test + public void testRemoveTableIfExist() { + tp.createTable("testdb"); + tp.removeTable("testdb"); + assertNull(tp.getTable("testdb")); + } +}