From da7a17c54e2e768893ab06b909e5c96c1150c1ae Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Sun, 2 Nov 2014 01:38:54 +0300 Subject: [PATCH 01/18] MultiDataBase v1.0 --- .../MultiDataBase/Functional.java | 73 ++++++++++++ .../MultiDataBase/MainClass.java | 32 +++++ .../MultiDataBase/ModeWork.java | 82 +++++++++++++ .../AndrewTimokhin/MultiDataBase/Reader.java | 79 +++++++++++++ .../MultiDataBase/TableWork.java | 111 ++++++++++++++++++ .../AndrewTimokhin/MultiDataBase/Write.java | 59 ++++++++++ 6 files changed, 436 insertions(+) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Functional.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/MainClass.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/ModeWork.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Reader.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/TableWork.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Write.java diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Functional.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Functional.java new file mode 100644 index 000000000..577df5d48 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Functional.java @@ -0,0 +1,73 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; + +import java.util.*; + +class Functional { + public Map[] map; + + public Functional(Map[] map) { + this.map = map; + } + + void put(Map[] map, int i, String key, String value) { + if (i == -1) { + System.out.println("NotDefBD#"); + return; + } + + if (map[i].containsKey(key)) { + System.out.println("overwrite"); + System.out.println(map[i].get(key)); + } else { + System.out.println("new"); + } + map[i].put(key, value); + } + + void get(Map[] map, int i, String key) { + if (i == -1) { + System.out.println("NotDefBD#"); + return; + } + if (map[i] != null) { + if (map[i].containsKey(key)) { + System.out.println("found"); + System.out.println(map[i].get(key)); + } else { + System.out.println("not found"); + } + } + } + + void remove(Map[] map, int i, String key) { + if (i == -1) { + System.out.println("NotDefBD#"); + return; + } + if (map[i] != null) { + if (map[i].containsKey(key)) { + map[i].remove(key); + } else { + System.out.println("not found"); + } + } + } + + void showtables() { + for (int i = 0; i < 16; i++) { + if (map[i] != null) { + if (map[i].size() == 0) { + map[i] = null; + } + } + } + for (int i = 0; i < 16; i++) { + if (map[i] != null) { + + System.out.println("table " + i + " " + map[i].size()); + } + } + + } +} + diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/MainClass.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/MainClass.java new file mode 100644 index 000000000..3e0d27cbf --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/MainClass.java @@ -0,0 +1,32 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; + +import java.io.*; +import java.util.*; + +public class MainClass { + + public static void main(String[] args) { + @SuppressWarnings("unchecked") + Map[] map = (Map[]) new Map[16]; + for (int i = 0; i < 16; i++) { + map[i] = new HashMap(); + } + + Reader rd = new Reader(System.getProperty("fizteh.db.dir").toString()); + map = rd.read(); + Write wr = new Write(System.getProperty("fizteh.db.dir").toString()); + Functional fn = new Functional(map); + ModeWork mw = new ModeWork(map, System.getProperty("fizteh.db.dir") + .toString()); + mw.usermode(fn); + + try { + wr.write(map); + + } catch (IOException e) { + System.out.println(e.toString()); + } + + } +} + diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/ModeWork.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/ModeWork.java new file mode 100644 index 000000000..eb5261a61 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/ModeWork.java @@ -0,0 +1,82 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; + +import java.util.*; + +class ModeWork { + String dir; + TableWork tw = new TableWork(); + + public ModeWork(Map[] time, String direct) { + dir = direct; + } + + int stepMode(String[] array, Functional f, int index) { + + switch (array[0 + index]) { + case "put": + f.put(f.map, tw.setDir, array[1 + index], array[2 + index]); + return 2; + case "get": + f.get(f.map, tw.setDir, array[1 + index]); + return 1; + case "remove": + f.remove(f.map, tw.setDir, array[1 + index]); + return 1; + case "create": + tw.create(f.map, dir, array[1 + index]); + tw.createforUser(f.map, Integer.parseInt(array[1 + index])); + return 1; + case "drop": + tw.drop(dir, array[1 + index]); + tw.dropForUser(f.map, Integer.parseInt(array[1 + index])); + return 1; + case "use": + if (tw.userUse(dir, array[1 + index]) == 0) { + System.out.println("not exist"); + } else { + System.out.println("using " + array[1 + index]); + } + tw.setDir = Integer.parseInt(array[1 + index] + .replaceAll(".dat", "")); + return 1; + + case "showtables": + f.showtables(); + return 1; + case "exit": + return -1; + default: + System.out.println("Unknow operation. Fail."); + return -1; + } + } + + void usermode(Functional func) { + + 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; + } + } + rd.close(); + + } + + /* + * void interactive( Map[] time , String[] mass) { int + * offset = 0; Functional func = new Functional(time); int i = 0; while + * (true) { if (i < mass.length) { offset = stepMode(time,mass, func, i); i + * += offset; if (offset == -1) { break; } i++; } else { break; } } + * + * } + */ + +} + diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Reader.java new file mode 100644 index 000000000..ebdaaab85 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Reader.java @@ -0,0 +1,79 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; + +import java.util.*; +import java.io.*; + +public class Reader { + private TableWork tw = new TableWork(); + private String filepath; + + private Map[] map; + + public Reader(String path) { + filepath = path; + + map = (Map[]) new Map[16]; + + } + + public Map[] read() { + for (Integer i = 0; i < 16; i++) { + if (tw.useForReader(filepath, i.toString()) == 1) { + map[i] = new HashMap(); + StringBuilder keyBuilder = new StringBuilder(); + StringBuilder valueBuilder = new StringBuilder(); + File localbase = new File(filepath + "/" + i.toString()); + String[] list = localbase.list(); + if (list != null) { + for (String currentDat : list) { + int length = 0; + try (DataInputStream rd = new DataInputStream( + new FileInputStream(filepath + "/" + + i.toString() + "/" + currentDat))) { + while (true) { + try { + length = rd.readInt(); + for (int k = 0; k < length; k++) { + keyBuilder.append(rd.readChar()); + + } + length = rd.readInt(); + for (int k = 0; k < length; k++) { + valueBuilder.append(rd.readChar()); + + } + map[i].put(keyBuilder.toString(), + valueBuilder.toString()); + keyBuilder.replace(0, keyBuilder.length(), + ""); + valueBuilder.replace(0, + valueBuilder.length(), ""); + if (i == 15) { + tw.setDir = -1; + } + } 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/MultiDataBase/TableWork.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/TableWork.java new file mode 100644 index 000000000..0abe22833 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/TableWork.java @@ -0,0 +1,111 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; + +import java.io.*; +import java.util.*; + +public class TableWork { + public int setDir = -1; // by default + + public int getset() { + return setDir; + } + + public void createforUser(Map[] agr, int numdir) { + if (agr[numdir] != null) { + + return; + } + agr[numdir] = new HashMap(); + return; + } + + public int create(Map[] agr, String homeDir, + String tableToAdd) { + + File local = new File(homeDir); + String[] list; + list = local.list(); + if (list != null) { + for (int i = 0; i < list.length; i++) { + if (list[i].equals(tableToAdd)) { + System.out.println(tableToAdd + " exists"); + return 1; // if exist + } + + } + } + File newtable = new File(homeDir + "/" + tableToAdd); + newtable.mkdirs(); + if (agr[Integer.parseInt(tableToAdd)] == null) { + agr[Integer.parseInt(tableToAdd)] = new HashMap(); + } + System.out.println("created"); + return 0; // if added + } + + public void dropForUser(Map[] agr, int numdir) { + if (agr[numdir] == null) { + return; + } + agr[numdir] = null; + return; + + } + + public int drop(String homeDir, String tableToDel) { + int haveDir = 0; + File local = new File(homeDir); + String[] list; + list = local.list(); + if (list != null) { + for (int i = 0; i < list.length; i++) { + if (list[i].equals(tableToDel)) { + haveDir = 1; // if exist + } + } + } + if (haveDir == 0) { + System.out.println("not exists"); + return 0; + } + + File delTable = new File(homeDir + "/" + tableToDel); + for (File file : new File(homeDir + "/" + tableToDel).listFiles()) { + if (file.isFile()) { + file.delete(); + } + } + delTable.delete(); + System.out.println(tableToDel + " dropped"); + return 1; // if was deleted + } + + public int useForReader(String homeDir, String numDir) { + File local = new File(homeDir); + String[] list; + list = local.list(); + if (list != null) { + for (int i = 0; i < list.length; i++) { + if (list[i].equals(numDir)) { + return 1; // if exist + } + } + } + return 0; // if n + } + + public int userUse(String homeDir, String table) { + File local = new File(homeDir); + String[] list; + list = local.list(); + if (list != null) { + for (int i = 0; i < list.length; i++) { + if (list[i].equals(table)) { + return 1; // if exist + } + } + } + return 0; // if added + } +} + diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Write.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Write.java new file mode 100644 index 000000000..1260b4be4 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Write.java @@ -0,0 +1,59 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; + +import java.util.*; +import java.io.*; +import java.util.regex.*; + +public class Write { + private String filepath; + + public Write(String path) { + filepath = path; + } + + public void write(Map[] map) throws IOException { + for (Integer i = 0; i < 16; i++) { + if (map[i] != null) { + + for (Integer j = 0; j < 16; j++) { + String local = j.toString() + ".dat"; + File tmp = new File(filepath + "/" + i.toString() + "/" + + local); + tmp.createNewFile(); + try (DataOutputStream out = new DataOutputStream( + new FileOutputStream(filepath + "/" + i.toString() + + "/" + local))) { + Set st = map[i].keySet(); + for (String time : st) { + + String tm = local.replaceAll(".dat", ""); + if ((time.hashCode() / 16 % 16) == Integer + .parseInt(tm)) { + + out.writeInt(time.length()); + out.writeChars(time); + out.writeInt(((String) map[i].get(time)) + .length()); + out.writeChars((String) map[i].get(time)); + } + + } + + } catch (FileNotFoundException e) { + System.err.print("Not Found " + e.toString()); + } catch (IOException e) { + System.err.print("IOException " + e.toString()); + } + if (tmp.length() == 0) { + tmp.delete(); + } + } + } + if (map[i] == null) { + File delTable = new File(filepath + "/" + i.toString()); + + delTable.delete(); + } + } + } +} From 5e0ca7b354d3bf772e8e62c945539c38c1947171 Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Sat, 20 Dec 2014 12:32:22 +0300 Subject: [PATCH 02/18] v2 --- .../MultiFileHashMap v2.0/Functional.java | 58 +++++++ .../MultiFileHashMap v2.0/JUnit.java | 23 +++ .../MultiFileHashMap v2.0/ModeWork.java | 94 +++++++++++ .../MultiFileHashMap v2.0/Reader.java | 95 +++++++++++ .../MultiFileHashMap v2.0/TableDriver.java | 37 +++++ .../MultiFileHashMap v2.0/TableWork.java | 157 ++++++++++++++++++ .../MultiFileHashMap v2.0/Write.java | 72 ++++++++ 7 files changed, 536 insertions(+) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Functional.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/JUnit.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/ModeWork.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Reader.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableDriver.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableWork.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Write.java diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Functional.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Functional.java new file mode 100644 index 000000000..252b9f1db --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Functional.java @@ -0,0 +1,58 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; + +import java.io.IOException; +import java.util.*; + +public class Functional { + + void put(Map[] map, int i, String key, String value) { + if (i == -1) { + System.out.println("NotDefBD#"); + return; + } + + if (map[i].containsKey(key)) { + System.out.println("overwrite"); + System.out.println(map[i].get(key)); + } else { + System.out.println("new"); + } + map[i].put(key, value); + } + + void get(Map[] map, int i, String key) { + if (i == -1) { + System.out.println("NotDefBD#"); + return; + } + if (map[i] != null) { + if (map[i].containsKey(key)) { + System.out.println("found"); + System.out.println(map[i].get(key)); + } else { + System.out.println("not found"); + } + } + } + + void remove(Map[] map, int i, String key) { + if (i == -1) { + System.out.println("NotDefBD#"); + return; + } + if (map[i] != null) { + if (map[i].containsKey(key)) { + map[i].remove(key); + } else { + System.out.println("not found"); + } + } + } + + void showtables(TableDriver[] td) throws NullPointerException, IOException { + for (TableDriver time : td) { + + System.out.println("table " + time.getName() + " " + time.size()); + } + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/JUnit.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/JUnit.java new file mode 100644 index 000000000..29641658e --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/JUnit.java @@ -0,0 +1,23 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; + +import java.io.*; +import java.util.*; + +public class JUnit { + public static void main(String[] args) throws IOException { + String path = System.getProperty("fizteh.db.dir").toString(); + TableWork tb = new TableWork(0, path); + Functional fn = new Functional(); + + ModeWork mw = new ModeWork(); + + mw.usermode(fn, tb); + Write wr = new Write(); + for (int i = 0; i < tb.t.length; i++) { + + wr.write(tb.t[i], tb); + } + + }; + +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/ModeWork.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/ModeWork.java new file mode 100644 index 000000000..edc6c5fbd --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/ModeWork.java @@ -0,0 +1,94 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; + +import java.io.IOException; +import java.util.*; + +class ModeWork { + Functional fn; + + ModeWork() { + fn = new Functional(); + } + + int stepMode(String[] array, TableWork f, int index) + throws NullPointerException, IOException { + + switch (array[0 + index]) { + case "put": + if (f.indicator == -1) + System.out.println("UNDEF"); + else + fn.put(f.t[f.indicator].map, array[1 + index].hashCode() % 16, + array[1 + index], array[2 + index]); + return 2; + case "get": + if (f.indicator == -1) + System.out.println("UNDEF"); + else + fn.get(f.t[f.indicator].map, array[1 + index].hashCode() % 16, + array[1 + index]); + return 1; + case "remove": + if (f.indicator == -1) + System.out.println("UNDEF"); + else + fn.remove(f.t[f.indicator].map, + array[1 + index].hashCode() % 16, array[1 + index]); + return 1; + case "create": + f.create(array[1 + index]); + + return 1; + case "drop": + f.drop(array[1 + index]); + + return 1; + case "use": + if (f.userUse(array[1 + index]) == 0) { + + } else { + + } + + return 1; + + case "showtables": + fn.showtables(f.t); + return 1; + case "exit": + return -1; + default: + System.out.println("Unknow operation. Fail."); + return -1; + } + } + + void usermode(Functional func, TableWork t) throws NullPointerException, + IOException { + + 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, t, 0) == -1) { + break; + } + } + rd.close(); + + } + + /* + * void interactive( Map[] time , String[] mass) { int + * offset = 0; Functional func = new Functional(time); int i = 0; while + * (true) { if (i < mass.length) { offset = stepMode(time,mass, func, i); i + * += offset; if (offset == -1) { break; } i++; } else { break; } } + * + * } + */ + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Reader.java new file mode 100644 index 000000000..5c991effd --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Reader.java @@ -0,0 +1,95 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; + +import java.util.*; +import java.io.*; + +public class Reader { + + private Map[] map; + + public Reader() { + + } + + public Map[] read(String filepath) { + + map = (Map[]) new Map[16]; + for (int ind = 0; ind < 16; ind++) { + map[ind] = new HashMap(); + } + + int flag = 0; + File alldir = new File(filepath); + String file[] = alldir.list(); + + for (Integer i = 0; i < 16; i++) { + for (int j = 0; j < file.length; j++) { + if (i.toString().equals(file[j].toString())) { + flag = 1; + break; + } + } + if (flag == 1) + + { + + StringBuilder keyBuilder = new StringBuilder(); + StringBuilder valueBuilder = new StringBuilder(); + File localbase = new File(filepath + "\\" + i.toString()); + + String[] list = localbase.list(); + + if (list != null) { + for (String currentDat : list) { + + int length = 0; + try (DataInputStream rd = new DataInputStream( + new FileInputStream(filepath + "\\" + + i.toString() + "\\" + currentDat))) { + while (true) { + try { + length = rd.readInt(); + for (int k = 0; k < length; k++) { + keyBuilder.append(rd.readChar()); + + } + length = rd.readInt(); + for (int k = 0; k < length; k++) { + valueBuilder.append(rd.readChar()); + + } + map[i].put(keyBuilder.toString(), + valueBuilder.toString()); + keyBuilder.replace(0, keyBuilder.length(), + ""); + valueBuilder.replace(0, + valueBuilder.length(), ""); + if (i == 15) { + + } + } 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()); + } + } + } + } + flag = 0; + } + + return map; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableDriver.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableDriver.java new file mode 100644 index 000000000..115cba42e --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableDriver.java @@ -0,0 +1,37 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; + +import java.util.HashMap; +import java.util.Map; + +public class TableDriver { + private String name; + public Map[] map; + + TableDriver() { + + } + + TableDriver(String name) { + this.name = name; + map = (Map[]) new Map[16]; + for (int i = 0; i < 16; i++) { + map[i] = new HashMap(); + } + + } + + public int size() { + int summ = 0; + if (map != null) { + for (int i = 0; i < 16; i++) { + if (map[i] != null) + summ += map[i].size(); + } + } + return summ; + } + + public String getName() { + return name; + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableWork.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableWork.java new file mode 100644 index 000000000..59b62cbea --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableWork.java @@ -0,0 +1,157 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; + +import java.io.*; +import java.util.*; + +public class TableWork { + public TableDriver t[]; + String homeDir; + int indicator; + int size; + + TableWork(int size, String homeDir) { + Reader rd = new Reader(); + this.size = 0; + File input = new File(homeDir); + String[] st; + st = input.list(); + if (st != null) { + for (String path : st) { + + File tm2 = new File(homeDir + "\\" + path); + + if (tm2.list() != null) { + + if (size == 0) { + t = new TableDriver[1]; + t[0] = new TableDriver(path); + t[0].map = rd.read(homeDir + "\\" + path); + + } else { + TableDriver temp[] = new TableDriver[t.length + 1]; + for (int k = 0; k < t.length; k++) + temp[k] = t[k]; + + temp[t.length] = new TableDriver(path); + temp[t.length].map = rd.read(homeDir + "\\" + path); + + t = temp; + } + size++; + } + + } + } + + this.homeDir = homeDir; + + indicator = -1; + } + + public int setDir = -1; // by default + + public int getset() { + return setDir; + } + + public int create(String tableToAdd) throws NullPointerException { + + if (t != null) { + for (int i = 0; i < t.length; i++) { + if (tableToAdd.equals(t[i].getName())) { + System.out.println("exist!"); + return 1; + } + } + ; + { + + TableDriver temp[] = new TableDriver[t.length + 1]; + for (int k = 0; k < t.length; k++) + temp[k] = t[k]; + + temp[t.length] = new TableDriver(tableToAdd); + t = temp; + System.out.println("created"); + } + } + + if (t == null || size == 0) { + t = new TableDriver[1]; + t[0] = new TableDriver(tableToAdd); + } + System.out.println("created"); + size++; + return 0; // if added + } + + public void remove(File anyfile) { + if (!anyfile.exists()) + return; + if (anyfile.isDirectory()) { + for (File f : anyfile.listFiles()) + remove(f); + anyfile.delete(); + } else { + anyfile.delete(); + } + } + + public void drop(String tableToDel) throws NullPointerException, + IOException { + int haveDir = 0; + for (int i = 0; i < t.length; i++) { + if (t[i] != null && tableToDel.equals(t[i].getName()) == true) { + + if (t.length != 1) { + TableDriver tm = new TableDriver(); + t[i] = t[t.length - 1]; + t[t.length - 1] = null; + + } else + t[i] = null; + size--; + System.out.println(tableToDel + " dropped"); + File in = new File(homeDir); + String st[] = in.list(); + + if (st != null) { + for (String time : st) { + if (time.equals(tableToDel)) { + + in = new File(homeDir + "\\" + tableToDel); + + remove(in); + + } + + } + } + + // if was deleted + break; + } + + } + if (haveDir == 0) { + System.out.println("not exists"); + + } + + } + + public int userUse(String tablename) throws NullPointerException { + if (t != null && t[0] != null) + for (int i = 0; i < t.length; i++) { + if (t[i].getName().equals(tablename)) { + indicator = i; + System.out.println("use"); + return 0; + } + } + System.out.println("not exist"); + return 1; + + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Write.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Write.java new file mode 100644 index 000000000..ef81ade64 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Write.java @@ -0,0 +1,72 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; + +import java.util.*; +import java.io.*; +import java.util.regex.*; + +public class Write { + private String filepath; + + public Write() { + + } + + public void write(TableDriver tm, TableWork tb) throws IOException { + if (tm != null) { + filepath = tb.homeDir + "\\" + tm.getName(); + File time2 = new File(filepath); + time2.mkdir(); + + for (Integer i = 0; i < 16; i++) { + if (tm.map[i] != null) { + + for (Integer j = 0; j < 16; j++) { + String local = j.toString() + ".dat"; + + File tmp0 = new File(filepath + "\\" + i.toString()); + tmp0.mkdir(); + + File tmp = new File(filepath + "\\" + i.toString() + + "\\" + local); + tmp.createNewFile(); + try (DataOutputStream out = new DataOutputStream( + new FileOutputStream(filepath + "\\" + + i.toString() + "\\" + local))) { + Set st = tm.map[i].keySet(); + for (String time : st) { + + String tr = local.replaceAll(".dat", ""); + if ((time.hashCode() / 16 % 16) == Integer + .parseInt(tr)) { + + out.writeInt(time.length()); + out.writeChars(time); + out.writeInt(((String) tm.map[i].get(time)) + .length()); + out.writeChars((String) tm.map[i].get(time)); + } + + } + + } catch (FileNotFoundException e) { + System.err.print("Not Found " + e.toString()); + } catch (IOException e) { + System.err.print("IOException " + e.toString()); + } + if (tmp.length() == 0) { + tmp.delete(); + } + } + File tmp0 = new File(filepath + "\\" + i.toString()); + if (tmp0.list().length == 0) + tmp0.delete(); + } + if (tm.map[i] == null) { + File delTable = new File(filepath + "\\" + i.toString()); + + delTable.delete(); + } + } + } + } +} From 895e6fe5519bba908e230d89a43e5eee083bc0ac Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Tue, 20 Jan 2015 00:13:33 +0300 Subject: [PATCH 03/18] v1 --- .../FileMap/JUnit/FactoryImplements.java | 33 +++ .../AndrewTimokhin/FileMap/JUnit/JUnit.java | 28 +++ .../AndrewTimokhin/FileMap/JUnit/Reader.java | 137 ++++++++++ .../AndrewTimokhin/FileMap/JUnit/Table.java | 78 ++++++ .../FileMap/JUnit/TableImplement.java | 237 ++++++++++++++++++ .../FileMap/JUnit/TableProvider.java | 40 +++ .../FileMap/JUnit/TableProviderFactory.java | 16 ++ .../JUnit/TableProviderImplements.java | 141 +++++++++++ .../JUnit/Test/FactoryImplementsTest.java | 43 ++++ .../JUnit/Test/TableImplementTest.java | 203 +++++++++++++++ .../Test/TableProviderImplementsTest.java | 96 +++++++ .../AndrewTimokhin/FileMap/JUnit/Writer.java | 106 ++++++++ 12 files changed, 1158 insertions(+) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java new file mode 100644 index 000000000..b71942171 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java @@ -0,0 +1,33 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +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("Error in create-meth."); // если + // в + // параметрах + // указана + // неверный путь к директории, + // генерируется исключение + try { + return new TableProviderImplements(dir); // иначе, предпринимаеться + // попытка по созданию + // провайдера базы данных + } catch (IOException e) { + // do nothing + } + return null; + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java new file mode 100644 index 000000000..d096d8ce3 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java @@ -0,0 +1,28 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class JUnit { + public static void main(String[] args) throws IOException { + FactoryImplements tb = new FactoryImplements(); + TableProviderImplements tp = (TableProviderImplements) tb + .create("C:\\DataBase"); + Table time = tp.createTable("new"); + time=tp.getTable("new"); + + time.put("1", "1" ); + time.put("2", "2" ); + time.put("3", "3" ); + time.commit(); + time.put("4", "4"); + time.put("5", "5"); + time.put("6", "6"); + time.put("7", "7"); + time.commit(); + time.rollback(); + + + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java new file mode 100644 index 000000000..b383e1fc9 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java @@ -0,0 +1,137 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +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.util.Iterator; +import java.util.Vector; + +import javax.naming.ldap.Rdn; + +/** + * Класс @class Reader отвечает за физическое чтение данных с жесткого диска или + * другого физического носителя информации. + * + * + * @author Timokhin Andrew + */ + +public class Reader { + public void read(TableProviderImplements tp) throws IOException { + int i; + StringBuilder keyBuilder = new StringBuilder(); // буфер для чтения + // ключей + StringBuilder valueBuilder = new StringBuilder(); // буфер для чтения + // значений + int length; // длина ключа/значения + String path = tp.dir; // корень хранилища + Vector agregat = new Vector(); + int validator = 0; + File testDir = new File(path); + if (testDir.list() != null) + for (String time : testDir.list()) { + File checkDir = new File(path + "\\" + time); + + if (checkDir.isDirectory()) { + validator++; + TableImplement database = new TableImplement(time, tp.dir); + for (i = 0; i < 16; i++) { // сканируеться максимально + // возможное число директорий = + // 16 + Integer numberDir = new Integer(i); + File locDB = new File(path + "\\" + time + "\\" + + numberDir.toString() + ".dir"); + if (locDB.exists()) { + for (String file : locDB.list()) { + + try (DataInputStream rd = new DataInputStream( + new FileInputStream( + locDB.getAbsolutePath() + "\\" + + file))) { + + while (true) { + + try { + length = rd.readInt(); // на 1 шаге + // алгоритм + // считывает + // размер + // ключа + for (int k = 0; k < length; k++) { // читается + // ключ + keyBuilder + .append(rd.readChar()); + + } + length = rd.readInt(); // на 2 шаге + // алгоритм + // считывает + // размер + // значения + for (int k = 0; k < length; k++) { // считывается + // значение + valueBuilder.append(rd + .readChar()); + + } + + database.map.put( + keyBuilder.toString(), // добавление + // ключа/значения + // в + // карту + valueBuilder.toString()); + database.backup.put( + keyBuilder.toString(), + valueBuilder.toString()); + keyBuilder.replace(0, + keyBuilder.length(), // сохранение + // начальных + // данных + // в + // бэкап + ""); + valueBuilder.replace(0, + valueBuilder.length(), ""); // сброс + // буфера + } catch (EOFException e) { + + break; + } + + } + + } catch (FileNotFoundException e) { + // do nothing + + } + + } + } + } + + agregat.add(database); + + } + + } + + if (validator == 0) + return; // загружаем ранее сохраненные базы данных в нашу базу + // данных + TableImplement[] copy = new TableImplement[agregat.size()]; + i = 0; + Iterator it = agregat.iterator(); + while (it.hasNext()) { + + copy[i] = it.next(); + } + tp.t = copy; + return; + + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java new file mode 100644 index 000000000..ced884c3b --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java @@ -0,0 +1,78 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +import java.util.List; + +public interface Table { + + /** + * Возвращает название базы данных. + */ + String getName(); + + /** + * Получает значение по указанному ключу. + * + * @param key + * Ключ. + * @return Значение. Если не найдено, возвращает null. + * + * @throws IllegalArgumentException + * Если значение параметра key является null. + */ + String get(String key); + + /** + * Устанавливает значение по указанному ключу. + * + * @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/JUnit/TableImplement.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java new file mode 100644 index 000000000..bb728b815 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java @@ -0,0 +1,237 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +/** + * Класс 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 { + + public String name; // содержит имя таблицы + public String path; // путь к таблице + public Map map; // real-time версию карты + public Map backup; // бэкапнутую версию базы данных + + public TableImplement(String name, String path) { + this.path = path; // устанавливает путь к базе данных + this.name = name; // устанавливает имя базы данных + map = new HashMap(); // выделение место под real-time + // карту + backup = new HashMap(); // выделение места под + // backup-карту + + } + + @Override + public String getName() { // возвращает имя базы данных + return name; + } + + @Override + public int size() { // Возврат числа ключей, хранимых в базе данных. + // Исключения не вырабатываються. + int summ = 0; // изначальный размер базы данных полагает равным 0. + if (map != null) { + summ += map.size();// сохраняем реальное число записей, хранимых в + // базе данных. + } + return summ; + } + + @Override + public String get(String key) throws IllegalArgumentException { // возврашает + // значение + // по + // указанному + // ключу + if (key == null) + throw new IllegalArgumentException( + "Error in get-meth. Key is wrong!"); // если ключ null, + // тогда возбуждается + // исключение + if (map != null) + if (map.containsKey(key)) + return (String) map.get(key); + return null; + + } + + @Override + public String put(String key, String value) throws IllegalArgumentException { // метод + // создан + // для + // записи + // ключа + // и + // значения + // в + // базу + // данных + String time = null; + if (key == null || value == null) + throw new IllegalArgumentException( + "Error in put-meth. Key or (and) value is wrong."); // если + // неверно + // заданы + // аргументы + // возбуждает исключение + if (map != null) // случай, если база данных была непуста + if (map.containsKey(key)) + time = (String) map.get(key); + map.put(key, value); + return time; // возращает значение ранее ассоциированное с данным ключом + // null- если не было ранее никаких ассоциаций + } + + @Override + public String remove(String key) throws IllegalArgumentException // удаляем + // значение + // ассоциированное + // с + // ключом, + // переданным + // в + // параметрах + { + String time = null; + if (key == null) + throw new IllegalArgumentException( + "Error in remove-meth. Key is wrong."); + if (map != null) + if (map.containsKey(key)) { + time = (String) map.get(key); + map.remove(key); + } + return time; + + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public List list() { // возврат списка, содержащего ключи базы + // данных + Set time; + if (map != null) { + time = map.keySet(); // получение ключей, имеющхся в базе данных в + // данный момент + List list = new ArrayList(time); + return (List) list; + } + return (List) (new ArrayList()); + } + + @Override + public int commit() { + int counter = 0; + if (backup == null && map == null) + return 0; // изменений нет, не нужно коммитеть + if (backup != null && map == null) + counter= backup.size(); // текущее состояние базы данных пусто, в + // бекапе есть записи, выполняеться перезапись + if (backup == null && map != null) + counter = map.size(); // аналогично + if (backup != null && map != null) { + Set time = backup.keySet(); + for (String time1 : time) { + + if (backup.get(time1).equals(map.get(time1)) == false) + counter++; // если одному и тому же ключу соответствуют разные + // значения + // то метод считает, что нужно изменить + else if (backup.containsKey(time1) + && map.containsKey(time1) == false) + counter++; + } + time = map.keySet(); + for (String time1 : time) { + + if ((backup.containsKey(time1) && map.containsKey(time1)) == false) { + // аналогично, однако, если один ключ был удален, а другой был + // добавлен, то считаеться что было произведено 2 изменения + counter++; + } + }} + System.out.println("in this method counter is ==> " + counter); + if (counter != 0) // если есть изменения вызывается физичекая запись на + // жесткий диск + try { + + this.writeToDisk(); + } catch (IOException e) { + // do nothing + } + + return counter; // возвращаеться общий счетчик числа изменений + } + + public void writeToDisk() throws IOException { // метод, реально + // записывающий сделанные + // изменения на диск + int flag = 0; + Reader rd = new Reader(); + TableProviderImplements tpi = new TableProviderImplements(path); + rd.read(tpi); // считываем, имеющееся на диске + Writer writer = new Writer(); + if (tpi.t != null) { + for (int i = 0; i < tpi.t.length; i++) { + if (tpi.t[i].getName().equals(this.getName())) { + + { + Map tmp = new HashMap(); + @SuppressWarnings("unchecked") + Set copy = tpi.t[i].map.keySet(); + for (String time : copy) { + + tmp.put(new String(time), + new String(tpi.t[i].map.get(time))); + } + this.backup = new HashMap(tmp); + ; + + } + + tpi.t[i] = this; + flag = 1; + } + + } + + } + if (flag == 0) { + tpi.createTable(this.name); + this.backup = null; + } + for (int i = 0; i < tpi.t.length; i++) { + if (tpi.t[i].getName().equals(this.getName())) + tpi.t[i] = this; + + } + + writer.write(tpi); + if (this.map == null) { + this.commit(); + + } + + } + + @Override + public int rollback() { // отвечает за откат к предыдущему состоянию (к + // самому последнему коммиту) + Map time = new HashMap(this.map); + this.map = new HashMap(this.backup); + this.backup = time; + this.commit(); + + return 0; + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java new file mode 100644 index 000000000..7f8b327db --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java @@ -0,0 +1,40 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +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); +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java new file mode 100644 index 000000000..c09997ab1 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java @@ -0,0 +1,16 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +public interface TableProviderFactory { + + /** + * Возвращает объект для работы с базой данных. + * + * @param dir + * Директория с файлами базы данных. + * @return Объект для работы с базой данных. + * @throws IllegalArgumentException + * Если значение директории null или имеет недопустимое + * значение. + */ + TableProvider create(String dir); +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java new file mode 100644 index 000000000..bc7883cda --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java @@ -0,0 +1,141 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +import java.io.IOException; + +/** + * Класс @class TableProviderImplements содержит логику по работе провайдера + * базы данных. В нем переопределены все методы, заявленные в интерфейсе + * TableProvider + * + * @author Timokhin Andrew + */ + +public class TableProviderImplements implements TableProvider { + + public TableImplement[] t; + public final String dir; + + TableProviderImplements(String dir) throws IOException { + this.dir = dir; + t = null; + Reader rd = new Reader(); + rd.read(this); + } + + public void writer() throws IOException { + Writer writer = new Writer(); + writer.write(this); + } + + @Override + public Table getTable(String name) throws IllegalArgumentException { // получение + // таблицы + // по + // ее + // имени + if (name == null) + throw new IllegalArgumentException("Error in getTable-meth"); // вырабатывает + // исключение, + // если + // имя + // таблицы + // задано + // некорректно + if (t != null) { + for (int i = 0; i < t.length; i++) { + if (t[i].getName().equals(name)) + return t[i]; // возврат таблицы, если такая существует + + } + } + return null; // возврат null в случае, если таблицу с указанным + // названием невозможно найти + } + + @Override + public Table createTable(String name) throws IllegalArgumentException { // создает + // таблицу + // с + // указанным + // именем + if (name == null) + throw new IllegalArgumentException("Error in createTable-meth"); // вырабатывает + // исключение, + // если + // имя + // таблицы + // задано + // некорректно + if (t != null) { + for (int i = 0; i < t.length; i++) { + if (name.equals(t[i].getName())) { + return null; // если таблица с указанным именем содержиться + // в агрегате, тогда возврат null + } + } + { + TableImplement[] temp = new TableImplement[t.length + 1]; + for (int k = 0; k < t.length; k++) { + temp[k] = t[k]; + } + + temp[t.length] = new TableImplement(name, dir); + t = temp; + return t[t.length - 1]; + } + } + + if (t == null) { // на случай пустого агрегата, сразу создаем таблицу + // (без копирующего с пропуском алгоритма) + t = new TableImplement[1]; + t[0] = new TableImplement(name, dir); + return t[0]; + } + return null; + } + + @Override + public void removeTable(String name) throws IllegalArgumentException, + IllegalStateException { // удаление таблицы с указанным именем, + // возможна + // выроботка двух видов исключений + if (name == null) + throw new IllegalArgumentException("Error in removeTable-meth"); // если + // название + // таблицы + // неверно, + // тогда + // возбуждает + // исключение + if (t != null) { + for (int i = 0; i < t.length; i++) { // использует алгоритм + // копирования с пропусками + if (t[i].getName().equals(name)) { + t[i].backup = null; + t[i].map = null; + t[i].name = null; + TableImplement[] temp = new TableImplement[t.length - 1]; + for (int j = 0; j < i; j++) { + temp[j] = t[j]; + } + + for (int j = i + 1; j < t.length; j++) { + temp[j - 1] = t[j]; + } + t = temp; + return; + } + } + throw new IllegalStateException("Error in removeTable-meth"); // если + // таблицы, + // соответствующей + // параметру + // name + // не + // существовало + // то генерация исключения неверного состояния + } + + } + +} 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..52d0536ac --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java @@ -0,0 +1,43 @@ +/* + * Создание тестов для класса FactoryImplements + * Данные тесты в полном объеме проверяют функциональность + * соответствующего класса, включая граничные случаи + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Test; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Андрей + */ +public class FactoryImplementsTest { + private final Map agregaret = new HashMap(); + + /** + * Тест работает на проверку генерации исключения IllegalArgumentException + * при попытке создать провайдера базы данных с пустой корневой директорией. + * Также тестируеться создание провайдера базы данных с корректной + * директорией. + * + * @throws java.io.IOException + */ + + @Test + public void testCreate() throws IOException { + TableProviderImplements resultOne = (TableProviderImplements) new FactoryImplements() + .create("C:\\DataBase"); + assertEquals("C:\\DataBase", resultOne.dir); + } + + @Test(expected = IllegalArgumentException.class) + public void testCreateCorrect() { + 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..80ff9283d --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java @@ -0,0 +1,203 @@ +/* + * Модульные тесты базы данных. + * + */ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Test; + +import java.util.List; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; +import java.lang.IllegalArgumentException; + +/** + * + * @author Timokhin Andrew + */ +public class TableImplementTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + public TableProvider tp; + public String path; + public Table tb; + + @Before + public void setUp() { + TableProviderFactory tpv = new FactoryImplements(); + path = tmp.newFolder("C:\\time").getAbsolutePath(); + tp = tpv.create(path); + tb = tp.createTable("testing"); + + FactoryImplements tb = new FactoryImplements(); + TableProviderImplements tp = (TableProviderImplements) tb + .create("C:\\DataBase"); + Table time = tp.createTable("new"); + time = tp.getTable("new"); + + } + + /** + * Тестирование getName (большо одного нет смысла) + */ + @Test + public void testGetName() { + String result = tb.getName(); + assertTrue("testing".equals(result)); + } + + /** + * Тесты на size method + */ + @Test + public void testSizeByDefault() { + int result = tb.size(); + assertEquals(0, result); + } + + @Test + public void testSizeAfterAddedAndDel() { + tb.put("1", "11"); + tb.put("2", "22"); + int result = tb.size(); + assertEquals(2, result); + tb.remove("2"); + result = tb.size(); + assertEquals(1, result); + tb.remove("1"); + result = tb.size(); + assertEquals(0, result); + } + + /** + * Test of get method + */ + @Test(expected = IllegalArgumentException.class) + public void testGet() { + tb.get(null); + } + + /** + * Тестирование put метода + */ + @Test(expected = IllegalArgumentException.class) + public void testPutIfKeyIsNull() { + String value = "test_value"; + tb.put(null, value); + } + + @Test(expected = IllegalArgumentException.class) + public void testPutIfValueIsNull() { + String key = "test_key"; + tb.put(key, null); + } + + @Test(expected = IllegalArgumentException.class) + public void testPutIfValueAndKeyIsNull() { + tb.put(null, null); + } + + @Test + public void testPutIfKeyDnHaveInDataBase() { + String key = "test_key"; + String value = "test_value"; + assertNull(tb.put(key, value)); + } + + @Test + public void testPutIfKeyHaveInDataBase() { + String key = "test_key"; + String valueOld = "test_value_old"; + String valueNew = "test_value_new"; + + assertNull(tb.put(key, valueOld)); + assertEquals(valueOld, tb.put(key, valueNew)); + } + + /** + * Тестирование remove метода + */ + @Test(expected = IllegalArgumentException.class) + public void testRemoveIfKeyNull() { + tb.remove(null); + } + + @Test + public void testRemoveIfKeyExist() { + String key = "key_test"; + String value = "value_test"; + tb.put(key, value); + + assertEquals(value, tb.remove(key)); + assertNull(tb.get(key)); + } + + @Test + public void testRemoveIfKeyDnExist() { + String key = "key_test"; + + assertNull(tb.remove(key)); + } + + /** + * Тестирование метода commit + */ + @Test + public void testCommitIfEmpty() { + assertEquals(0, tb.commit()); + } + + @Test + public void testCommitIfFullAnything() { + tb.put("id564", "989"); + tb.put("id988", "123"); + tb.put("id123", "766"); + assertEquals(3, tb.commit()); + } + + public void testCommitIfWasRollback() { + tb.put("id564", "989"); + tb.put("id988", "123"); + tb.put("id123", "766"); + tb.rollback(); + + assertEquals(0, tb.commit()); + } + + /** + * Тестирование rollback метода + */ + @Test + public void testRollbackIfStateEmpty() { + assertEquals(0, tb.rollback()); + } + + @Test(expected = NullPointerException.class) + public void testRollbackNullPointer() { + tb.put("id564", "989"); + tb.put("id988", "123"); + tb.put("id123", "766"); + tb.commit(); + tb.rollback(); + + } + + @Test + public void testRollbackSomeChainChanges() { + tb.put("1", "1"); + tb.put("2", "2"); + tb.put("3", "3"); + tb.commit(); + tb.put("4", "4"); + tb.put("54", "54"); + tb.commit(); + assertEquals(2, tb.rollback()); + + } + +} 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..9b8a53ee8 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java @@ -0,0 +1,96 @@ +/* + * 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.Test; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +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("test"); + + } + + @Test + public void testRemoveTableIfExist() { + tp.createTable("test"); + tp.removeTable("test"); + assertNull(tp.getTable("test")); + + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java new file mode 100644 index 000000000..ba3eea43d --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java @@ -0,0 +1,106 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.Set; + +/** + * Класс @class Writer отвечает за физическую запись информации с на жесткий + * диск или другой носитель информации. Логика работы устойчива к новым папкам и + * т.д. + * + * @author Timokhin Andrew + */ + +public class Writer { + + boolean checkDir(String name) { + File time = new File(name); + return time.exists(); + + } + + void createDir(String path) { + File time = new File(path); + time.mkdir(); + //System.out.println(path); + return; + } + + void createFile(String path) throws IOException { + + File time = new File(path); + + File prepareToMakeDir = new File(time.getParent().toString()); + prepareToMakeDir.mkdirs(); + //System.out.println(prepareToMakeDir.getAbsolutePath()); + time.createNewFile(); + return; + } + + public void deleteDirectory(File dir) { + + if (dir.isDirectory()) { + String[] children = dir.list(); + for (int i = 0; i < children.length; i++) { + File f = new File(dir, children[i]); + deleteDirectory(f); + } + dir.delete(); + } else + dir.delete(); + } + + public int abs(int digital) { + if (digital < 0) + return -digital; + return digital; + } + + public void write(TableProviderImplements tp) throws IOException { + + this.deleteDirectory(new File(tp.dir)); + File fl = new File(tp.dir); + fl.mkdir(); + if (tp.t != null) + for (TableImplement ti : tp.t) { + File db = new File(tp.dir + "\\" + ti.name); + db.mkdir(); + if (ti.map != null) { + Set keyList; + keyList = ti.map.keySet(); + for (String keyFind : keyList) { + Integer dirToWrite = new Integer( + abs(keyFind.hashCode() % 16)); // номер + // директории для + // записи + String localPath = tp.dir + "\\" + ti.name + "\\" + + dirToWrite.toString() + ".dir"; + if (this.checkDir(localPath) == false) + this.createDir(localPath); + dirToWrite = new Integer(abs(ti.map.get(keyFind) + .hashCode() % 16 % 16)); // номер файла для + // записи + String localfile = localPath + "\\" + + dirToWrite.toString(); + if (this.checkDir(localfile) == false) { + this.createFile(localfile); + } + DataOutputStream out = new DataOutputStream( + new FileOutputStream(localfile)); + out.writeInt(keyFind.length()); + out.writeChars(keyFind); + out.writeInt(ti.map.get(keyFind).length()); + out.writeChars(ti.map.get(keyFind)); + out.close(); + } + + } + } + return; + } + +} From 1cbccabd24ef7f15715becfcb1fe08155741721b Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Fri, 30 Jan 2015 00:44:19 +0300 Subject: [PATCH 04/18] *new* --- .../FileMap/JUnit/FactoryImplements.java | 15 +- .../AndrewTimokhin/FileMap/JUnit/JUnit.java | 78 +++++++-- .../FileMap/JUnit/KeyNullAndNotFound.java | 13 ++ .../AndrewTimokhin/FileMap/JUnit/Reader.java | 23 +-- .../AndrewTimokhin/FileMap/JUnit/Table.java | 3 +- .../FileMap/JUnit/TableImplement.java | 148 ++++++++++-------- .../FileMap/JUnit/TableProvider.java | 2 +- .../FileMap/JUnit/TableProviderFactory.java | 2 +- .../JUnit/TableProviderImplements.java | 56 ++++--- .../JUnit/Test/FactoryImplementsTest.java | 2 +- .../JUnit/Test/TableImplementTest.java | 2 +- .../Test/TableProviderImplementsTest.java | 2 +- .../AndrewTimokhin/FileMap/JUnit/Writer.java | 19 ++- 13 files changed, 223 insertions(+), 142 deletions(-) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java index b71942171..2f5ba837b 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java @@ -14,17 +14,12 @@ public class FactoryImplements implements TableProviderFactory { @Override public TableProvider create(String dir) { - if (dir == null) - throw new IllegalArgumentException("Error in create-meth."); // если - // в - // параметрах - // указана - // неверный путь к директории, - // генерируется исключение + if (dir == null) { + throw new IllegalArgumentException("Error in create-meth."); + } + // then, generate exception try { - return new TableProviderImplements(dir); // иначе, предпринимаеться - // попытка по созданию - // провайдера базы данных + return new TableProviderImplements(dir); } catch (IOException e) { // do nothing } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java index d096d8ce3..ab7904577 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java @@ -1,28 +1,72 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; import java.io.IOException; -import java.util.List; -import java.util.concurrent.TimeUnit; public class JUnit { - public static void main(String[] args) throws IOException { + public static void main(String[] args) throws IOException, + IllegalArgumentException, KeyNullAndNotFound { FactoryImplements tb = new FactoryImplements(); TableProviderImplements tp = (TableProviderImplements) tb .create("C:\\DataBase"); - Table time = tp.createTable("new"); - time=tp.getTable("new"); - - time.put("1", "1" ); - time.put("2", "2" ); - time.put("3", "3" ); - time.commit(); - time.put("4", "4"); - time.put("5", "5"); - time.put("6", "6"); - time.put("7", "7"); - time.commit(); - time.rollback(); - + Table tableA1 = tp.createTable("A1"); + tableA1 = tp.getTable("A1"); + + /* + * Uncomment to see, that we have, when we run this programm twice. A1 + * must be : (1,1); (2,2); (3,3); A2 must be : all changes + */ + /* + * System.out.println("<===twice===>\n"); for (String tm : + * tableA1.list()) { System.out.println("key -> " + tm + " value -> " + + * tableA1.get(tm) ); } System.out.println("\n<===twice===>\n"); + */ + + tableA1.put("1", "1"); + tableA1.put("2", "2"); + tableA1.put("3", "3"); + tableA1.commit(); + tableA1.put("4", "4"); + tableA1.put("5", "5"); + tableA1.put("6", "6"); + tableA1.put("7", "7"); + tableA1.commit(); + tableA1.rollback(); + + for (String tm : tableA1.list()) { + System.out.println("key -> " + tm + " value -> " + tableA1.get(tm)); + } + + Table tableA2 = tp.createTable("A2"); + tableA2 = tp.getTable("A2"); + + /* + * System.out.println("<===twice===> \n"); for (String time: + * tableA2.list()){ System.out.println("key -> " + time + " value -> " + + * tableA2.get(time) ); } System.out.println("\n<===twice===> \n"); + */ + + tableA2.put("1", "green"); + tableA2.put("2", "blue"); + + System.out.println("<========NEXT========>\n"); + tableA2.remove("1"); + + for (String time : tableA2.list()) { + System.out.println("key -> " + time + " value -> " + + tableA2.get(time)); + } + + tableA2.commit(); + tableA2.put("3", "green"); + tableA2.put("4", "black"); + tableA2.put("5", "red"); + tableA2.commit(); + try { + tableA2.get(null); + } catch (IllegalArgumentException e) { + System.out.println("\n" + e + "\n" + e.getCause() + "\n"); + } + System.out.println(tableA2.get("4")); } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java new file mode 100644 index 000000000..96b15f664 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java @@ -0,0 +1,13 @@ +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; + +public class KeyNullAndNotFound extends Exception { + private String description; + + public KeyNullAndNotFound(String description) { + this.description = description; + } + + public String toString() { + return "key was not found because it is null!"; + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java index b383e1fc9..02f8cb191 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java @@ -9,8 +9,6 @@ import java.util.Iterator; import java.util.Vector; -import javax.naming.ldap.Rdn; - /** * Класс @class Reader отвечает за физическое чтение данных с жесткого диска или * другого физического носителя информации. @@ -31,13 +29,14 @@ public void read(TableProviderImplements tp) throws IOException { Vector agregat = new Vector(); int validator = 0; File testDir = new File(path); - if (testDir.list() != null) + if (testDir.list() != null) { for (String time : testDir.list()) { File checkDir = new File(path + "\\" + time); - + if (checkDir.isDirectory()) { validator++; TableImplement database = new TableImplement(time, tp.dir); + agregat.add(database); for (i = 0; i < 16; i++) { // сканируеться максимально // возможное число директорий = // 16 @@ -77,7 +76,7 @@ public void read(TableProviderImplements tp) throws IOException { .readChar()); } - + database.map.put( keyBuilder.toString(), // добавление // ключа/значения @@ -113,21 +112,23 @@ public void read(TableProviderImplements tp) throws IOException { } } - agregat.add(database); - } } - - if (validator == 0) - return; // загружаем ранее сохраненные базы данных в нашу базу - // данных + } + if (validator == 0) { + return; + }// загружаем ранее сохраненные базы данных в нашу базу + // данных + TableImplement[] copy = new TableImplement[agregat.size()]; i = 0; Iterator it = agregat.iterator(); + while (it.hasNext()) { copy[i] = it.next(); + i++; } tp.t = copy; return; diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java index ced884c3b..abcf1dbc1 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java @@ -15,11 +15,12 @@ public interface Table { * @param key * Ключ. * @return Значение. Если не найдено, возвращает null. + * @throws KeyNullAndNotFound * * @throws IllegalArgumentException * Если значение параметра key является null. */ - String get(String key); + String get(String key) throws IllegalArgumentException, KeyNullAndNotFound; /** * Устанавливает значение по указанному ключу. diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java index bb728b815..f8b7b9227 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java @@ -21,7 +21,7 @@ public class TableImplement implements Table { public Map map; // real-time версию карты public Map backup; // бэкапнутую версию базы данных - public TableImplement(String name, String path) { + public TableImplement(String name, String path) { this.path = path; // устанавливает путь к базе данных this.name = name; // устанавливает имя базы данных map = new HashMap(); // выделение место под real-time @@ -41,26 +41,29 @@ public int size() { // Возврат числа ключей, хранимых // Исключения не вырабатываються. int summ = 0; // изначальный размер базы данных полагает равным 0. if (map != null) { - summ += map.size();// сохраняем реальное число записей, хранимых в - // базе данных. + summ += map.size(); // сохраняем реальное число записей, хранимых в БД } return summ; } @Override - public String get(String key) throws IllegalArgumentException { // возврашает - // значение - // по - // указанному - // ключу - if (key == null) - throw new IllegalArgumentException( - "Error in get-meth. Key is wrong!"); // если ключ null, - // тогда возбуждается - // исключение - if (map != null) - if (map.containsKey(key)) + public String get(String key) throws IllegalArgumentException, + KeyNullAndNotFound { // возврашает + // значение + // по + // указанному + // ключу + if (key == null) { + IllegalArgumentException exception = new IllegalArgumentException( + "Error in get meth!"); + exception.initCause(new KeyNullAndNotFound("Error!")); + throw exception; // если ключ null, тогда возбуждается + } // исключение + if (map != null) { + if (map.containsKey(key)) { return (String) map.get(key); + } + } return null; } @@ -77,16 +80,19 @@ public String put(String key, String value) throws IllegalArgumentException { // // базу // данных String time = null; - if (key == null || value == null) + if (key == null || value == null) { throw new IllegalArgumentException( - "Error in put-meth. Key or (and) value is wrong."); // если - // неверно - // заданы - // аргументы + "Error in put-meth. Key or (and) value is wrong."); + } // если + // неверно + // заданы + // аргументы // возбуждает исключение - if (map != null) // случай, если база данных была непуста - if (map.containsKey(key)) + if (map != null) { // случай, если база данных была непуста + if (map.containsKey(key)) { time = (String) map.get(key); + } + } map.put(key, value); return time; // возращает значение ранее ассоциированное с данным ключом // null- если не было ранее никаких ассоциаций @@ -103,14 +109,16 @@ public String remove(String key) throws IllegalArgumentException // удаляе // параметрах { String time = null; - if (key == null) + if (key == null) { throw new IllegalArgumentException( "Error in remove-meth. Key is wrong."); - if (map != null) + } + if (map != null) { if (map.containsKey(key)) { time = (String) map.get(key); map.remove(key); } + } return time; } @@ -129,47 +137,57 @@ public List list() { // возврат списка, содержаще return (List) (new ArrayList()); } - @Override - public int commit() { + public int totalChanges() { int counter = 0; - if (backup == null && map == null) - return 0; // изменений нет, не нужно коммитеть - if (backup != null && map == null) - counter= backup.size(); // текущее состояние базы данных пусто, в - // бекапе есть записи, выполняеться перезапись - if (backup == null && map != null) - counter = map.size(); // аналогично - if (backup != null && map != null) { - Set time = backup.keySet(); - for (String time1 : time) { - - if (backup.get(time1).equals(map.get(time1)) == false) - counter++; // если одному и тому же ключу соответствуют разные - // значения - // то метод считает, что нужно изменить - else if (backup.containsKey(time1) - && map.containsKey(time1) == false) - counter++; - } - time = map.keySet(); - for (String time1 : time) { - if ((backup.containsKey(time1) && map.containsKey(time1)) == false) { - // аналогично, однако, если один ключ был удален, а другой был - // добавлен, то считаеться что было произведено 2 изменения - counter++; + if (backup == null && map == null) { + return 0; + }// изменений нет, не нужно коммитеть + if (backup != null && map == null) { + return backup.size(); + }// текущее состояние базы данных пусто, в + // бекапе есть записи, выполняеться перезапись + if (backup == null && map != null) { + return map.size(); + } // аналогично + if (backup != null && map != null) { + Set time = backup.keySet(); + for (String time1 : time) { + + if (!(backup.get(time1).equals(map.get(time1)))) { + counter++; } + else if (!map.containsKey(time1)) { + counter++; + } } - }} + time = map.keySet(); + for (String time1 : time) { + + if (!backup.containsKey(time1)) { + // аналогично, однако, если один ключ был удален, а другой + // был + // добавлен, то считаеться что было произведено 2 изменения + counter++; + } + } + } + return counter; + } + + @Override + public int commit() { + int counter = this.totalChanges(); System.out.println("in this method counter is ==> " + counter); - if (counter != 0) // если есть изменения вызывается физичекая запись на - // жесткий диск + if (counter != 0) { // если есть изменения вызывается физичекая запись + // на + // жесткий диск try { this.writeToDisk(); } catch (IOException e) { // do nothing } - + } return counter; // возвращаеться общий счетчик числа изменений } @@ -178,11 +196,16 @@ public void writeToDisk() throws IOException { // метод, реально // изменения на диск int flag = 0; Reader rd = new Reader(); - TableProviderImplements tpi = new TableProviderImplements(path); + + FactoryImplements tb = new FactoryImplements(); + TableProviderImplements tpi = (TableProviderImplements) tb.create(path); + rd.read(tpi); // считываем, имеющееся на диске + Writer writer = new Writer(); if (tpi.t != null) { for (int i = 0; i < tpi.t.length; i++) { + // System.out.println(tpi.t[i].getName()); if (tpi.t[i].getName().equals(this.getName())) { { @@ -195,11 +218,8 @@ public void writeToDisk() throws IOException { // метод, реально new String(tpi.t[i].map.get(time))); } this.backup = new HashMap(tmp); - ; - - } - - tpi.t[i] = this; + } + tpi.t[i] = this; flag = 1; } @@ -211,14 +231,15 @@ public void writeToDisk() throws IOException { // метод, реально this.backup = null; } for (int i = 0; i < tpi.t.length; i++) { - if (tpi.t[i].getName().equals(this.getName())) + if (tpi.t[i].getName().equals(this.getName())) { tpi.t[i] = this; + } } writer.write(tpi); if (this.map == null) { - this.commit(); + // this.commit(); } @@ -231,7 +252,6 @@ public int rollback() { // отвечает за откат к предыдущ this.map = new HashMap(this.backup); this.backup = time; this.commit(); - return 0; } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java index 7f8b327db..0170b90b9 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java @@ -37,4 +37,4 @@ public interface TableProvider { * Если таблицы с указанным названием не существует. */ void removeTable(String name); -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java index c09997ab1..8f5860f47 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java @@ -13,4 +13,4 @@ public interface TableProviderFactory { * значение. */ TableProvider create(String dir); -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java index bc7883cda..e67e08f64 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java @@ -33,18 +33,20 @@ public Table getTable(String name) throws IllegalArgumentException { // полу // по // ее // имени - if (name == null) - throw new IllegalArgumentException("Error in getTable-meth"); // вырабатывает - // исключение, - // если - // имя - // таблицы - // задано - // некорректно + if (name == null) { + throw new IllegalArgumentException("Error in getTable-meth"); + } // вырабатывает + // исключение, + // если + // имя + // таблицы + // задано + // некорректно if (t != null) { for (int i = 0; i < t.length; i++) { - if (t[i].getName().equals(name)) - return t[i]; // возврат таблицы, если такая существует + if (t[i].getName().equals(name)) { + return t[i]; + }// возврат таблицы, если такая существует } } @@ -58,14 +60,15 @@ public Table createTable(String name) throws IllegalArgumentException { // со // с // указанным // именем - if (name == null) - throw new IllegalArgumentException("Error in createTable-meth"); // вырабатывает - // исключение, - // если - // имя - // таблицы - // задано - // некорректно + if (name == null) { + throw new IllegalArgumentException("Error in createTable-meth"); + } // вырабатывает + // исключение, + // если + // имя + // таблицы + // задано + // некорректно if (t != null) { for (int i = 0; i < t.length; i++) { if (name.equals(t[i].getName())) { @@ -99,14 +102,15 @@ public void removeTable(String name) throws IllegalArgumentException, IllegalStateException { // удаление таблицы с указанным именем, // возможна // выроботка двух видов исключений - if (name == null) - throw new IllegalArgumentException("Error in removeTable-meth"); // если - // название - // таблицы - // неверно, - // тогда - // возбуждает - // исключение + if (name == null) { + throw new IllegalArgumentException("Error in removeTable-meth"); + }// если + // название + // таблицы + // неверно, + // тогда + // возбуждает + // исключение if (t != null) { for (int i = 0; i < t.length; i++) { // использует алгоритм // копирования с пропусками 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 index 52d0536ac..b16f477f7 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java @@ -3,7 +3,7 @@ * Данные тесты в полном объеме проверяют функциональность * соответствующего класса, включая граничные случаи */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Test; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; import java.io.IOException; import java.util.HashMap; 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 index 80ff9283d..ebbf516c5 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java @@ -2,7 +2,7 @@ * Модульные тесты базы данных. * */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Test; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; import java.util.List; import org.junit.After; 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 index 9b8a53ee8..a7e77f009 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java @@ -3,7 +3,7 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Test; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; import org.junit.After; import org.junit.AfterClass; diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java index ba3eea43d..af63c91fe 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java @@ -4,7 +4,6 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.util.List; import java.util.Set; /** @@ -26,7 +25,7 @@ boolean checkDir(String name) { void createDir(String path) { File time = new File(path); time.mkdir(); - //System.out.println(path); + // System.out.println(path); return; } @@ -36,7 +35,7 @@ void createFile(String path) throws IOException { File prepareToMakeDir = new File(time.getParent().toString()); prepareToMakeDir.mkdirs(); - //System.out.println(prepareToMakeDir.getAbsolutePath()); + // System.out.println(prepareToMakeDir.getAbsolutePath()); time.createNewFile(); return; } @@ -50,13 +49,15 @@ public void deleteDirectory(File dir) { deleteDirectory(f); } dir.delete(); - } else + } else { dir.delete(); + } } public int abs(int digital) { - if (digital < 0) + if (digital < 0) { return -digital; + } return digital; } @@ -65,7 +66,7 @@ public void write(TableProviderImplements tp) throws IOException { this.deleteDirectory(new File(tp.dir)); File fl = new File(tp.dir); fl.mkdir(); - if (tp.t != null) + if (tp.t != null) { for (TableImplement ti : tp.t) { File db = new File(tp.dir + "\\" + ti.name); db.mkdir(); @@ -79,14 +80,15 @@ public void write(TableProviderImplements tp) throws IOException { // записи String localPath = tp.dir + "\\" + ti.name + "\\" + dirToWrite.toString() + ".dir"; - if (this.checkDir(localPath) == false) + if (!this.checkDir(localPath)) { this.createDir(localPath); + } dirToWrite = new Integer(abs(ti.map.get(keyFind) .hashCode() % 16 % 16)); // номер файла для // записи String localfile = localPath + "\\" + dirToWrite.toString(); - if (this.checkDir(localfile) == false) { + if (!this.checkDir(localfile)) { this.createFile(localfile); } DataOutputStream out = new DataOutputStream( @@ -100,6 +102,7 @@ public void write(TableProviderImplements tp) throws IOException { } } + } return; } From 7cbea81d207763a1be1b804e52656e42700b8b05 Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Fri, 30 Jan 2015 05:03:23 +0300 Subject: [PATCH 05/18] *v2.2* --- .../FileMap/JUnit/FactoryImplements.java | 11 +- .../FileMap/JUnit/KeyNullAndNotFound.java | 8 +- .../AndrewTimokhin/FileMap/JUnit/Reader.java | 69 ++----- .../AndrewTimokhin/FileMap/JUnit/Table.java | 46 ++--- .../FileMap/JUnit/TableImplement.java | 193 ++++++++---------- .../FileMap/JUnit/TableProvider.java | 28 +-- .../FileMap/JUnit/TableProviderFactory.java | 10 +- .../JUnit/TableProviderImplements.java | 130 ++++-------- .../JUnit/Test/FactoryImplementsTest.java | 4 +- .../JUnit/Test/TableImplementTest.java | 65 ++++-- .../Test/TableProviderImplementsTest.java | 6 +- .../AndrewTimokhin/FileMap/JUnit/Writer.java | 81 ++++---- 12 files changed, 298 insertions(+), 353 deletions(-) diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java index 2f5ba837b..c891e4c42 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java @@ -3,9 +3,9 @@ import java.io.IOException; /** - * Класс @class FactoryImplements отвечает за фабрику по созданию таблиц. - * Имплиментируя интерфейс TableProviderFactory, переопределяет метод по - * созданию провайдера базы данных. + * @class FactoryImplements . + * TableProviderFactory, + * . * * @author Timokhin Andrew */ @@ -17,11 +17,10 @@ public TableProvider create(String dir) { if (dir == null) { throw new IllegalArgumentException("Error in create-meth."); } - // then, generate exception try { return new TableProviderImplements(dir); - } catch (IOException e) { - // do nothing + } catch (IOException xcpt) { + System.out.println(xcpt.toString()); } return null; } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java index 96b15f664..c8e01d8cc 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java @@ -1,13 +1,9 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +@SuppressWarnings("serial") public class KeyNullAndNotFound extends Exception { - private String description; - public KeyNullAndNotFound(String description) { - this.description = description; + super(description); } - public String toString() { - return "key was not found because it is null!"; - } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java index 02f8cb191..4a20dc40a 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java @@ -10,8 +10,8 @@ import java.util.Vector; /** - * Класс @class Reader отвечает за физическое чтение данных с жесткого диска или - * другого физического носителя информации. + * @class Reader + * . * * * @author Timokhin Andrew @@ -20,12 +20,10 @@ public class Reader { public void read(TableProviderImplements tp) throws IOException { int i; - StringBuilder keyBuilder = new StringBuilder(); // буфер для чтения - // ключей - StringBuilder valueBuilder = new StringBuilder(); // буфер для чтения - // значений - int length; // длина ключа/значения - String path = tp.dir; // корень хранилища + StringBuilder keyBuilder = new StringBuilder(); + StringBuilder valueBuilder = new StringBuilder(); + int length; + String path = tp.dir; Vector agregat = new Vector(); int validator = 0; File testDir = new File(path); @@ -35,11 +33,9 @@ public void read(TableProviderImplements tp) throws IOException { if (checkDir.isDirectory()) { validator++; - TableImplement database = new TableImplement(time, tp.dir); - agregat.add(database); - for (i = 0; i < 16; i++) { // сканируеться максимально - // возможное число директорий = - // 16 + TableImplement dataBase = new TableImplement(time, tp.dir); + agregat.add(dataBase); + for (i = 0; i < 16; i++) { Integer numberDir = new Integer(i); File locDB = new File(path + "\\" + time + "\\" + numberDir.toString() + ".dir"); @@ -54,48 +50,29 @@ public void read(TableProviderImplements tp) throws IOException { while (true) { try { - length = rd.readInt(); // на 1 шаге - // алгоритм - // считывает - // размер - // ключа - for (int k = 0; k < length; k++) { // читается - // ключ + length = rd.readInt(); + for (int k = 0; k < length; k++) { keyBuilder .append(rd.readChar()); } - length = rd.readInt(); // на 2 шаге - // алгоритм - // считывает - // размер - // значения - for (int k = 0; k < length; k++) { // считывается - // значение + length = rd.readInt(); + for (int k = 0; k < length; k++) { valueBuilder.append(rd .readChar()); } - database.map.put( - keyBuilder.toString(), // добавление - // ключа/значения - // в - // карту + dataBase.getMap().put( + keyBuilder.toString(), valueBuilder.toString()); - database.backup.put( + dataBase.getBackup().put( keyBuilder.toString(), valueBuilder.toString()); keyBuilder.replace(0, - keyBuilder.length(), // сохранение - // начальных - // данных - // в - // бэкап - ""); + keyBuilder.length(), ""); valueBuilder.replace(0, - valueBuilder.length(), ""); // сброс - // буфера + valueBuilder.length(), ""); } catch (EOFException e) { break; @@ -103,8 +80,8 @@ public void read(TableProviderImplements tp) throws IOException { } - } catch (FileNotFoundException e) { - // do nothing + } catch (FileNotFoundException fnfe) { + System.out.println(fnfe.toString()); } @@ -118,9 +95,7 @@ public void read(TableProviderImplements tp) throws IOException { } if (validator == 0) { return; - }// загружаем ранее сохраненные базы данных в нашу базу - // данных - + } TableImplement[] copy = new TableImplement[agregat.size()]; i = 0; Iterator it = agregat.iterator(); @@ -130,7 +105,7 @@ public void read(TableProviderImplements tp) throws IOException { copy[i] = it.next(); i++; } - tp.t = copy; + tp.collection = copy; return; } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java index abcf1dbc1..bcc338f37 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java @@ -5,75 +5,75 @@ public interface Table { /** - * Возвращает название базы данных. + * . */ String getName(); /** - * Получает значение по указанному ключу. + * . * * @param key - * Ключ. - * @return Значение. Если не найдено, возвращает null. + * . + * @return . , null. * @throws KeyNullAndNotFound * * @throws IllegalArgumentException - * Если значение параметра key является null. + * key null. */ String get(String key) throws IllegalArgumentException, KeyNullAndNotFound; /** - * Устанавливает значение по указанному ключу. + * . * * @param key - * Ключ. + * . * @param value - * Значение. - * @return Значение, которое было записано по этому ключу ранее. Если ранее - * значения не было записано, возвращает null. + * . + * @return , . + * , null. * * @throws IllegalArgumentException - * Если значение параметров key или value является null. + * key value null. */ String put(String key, String value); /** - * Удаляет значение по указанному ключу. + * . * * @param key - * Ключ. - * @return Значение. Если не найдено, возвращает null. + * . + * @return . , null. * * @throws IllegalArgumentException - * Если значение параметра key является null. + * key null. */ String remove(String key); /** - * Возвращает количество ключей в таблице. + * . * - * @return Количество ключей в таблице. + * @return . */ int size(); /** - * Выполняет фиксацию изменений. + * . * - * @return Количество сохранённых ключей. + * @return . */ int commit(); /** - * Выполняет откат изменений с момента последней фиксации. + * . * - * @return Количество отменённых ключей. + * @return . */ int rollback(); /** - * Выводит список ключей таблицы + * * - * @return Список ключей. + * @return . */ List list(); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java index f8b7b9227..aff38c87d 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java @@ -1,8 +1,8 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; /** - * Класс TableImplement содержит логику работы таблицы базы данных. - * В нем переопределены все методы, которые заявлены в интерфейсе Table + * TableImplement . + * , Table * * @author Timokhin Andrew */ @@ -14,51 +14,71 @@ import java.util.Map; import java.util.Set; -public class TableImplement implements Table { +public class TableImplement implements Table { - public String name; // содержит имя таблицы - public String path; // путь к таблице - public Map map; // real-time версию карты - public Map backup; // бэкапнутую версию базы данных + 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(); // выделение место под real-time - // карту - backup = new HashMap(); // выделение места под - // backup-карту + this.path = path; + this.name = name; + map = new HashMap(); + backup = new HashMap(); + } + + public String getPath() { + return path; + } + + public Map getMap() { + return map; + } + + public Map getBackup() { + return backup; + } + public void setBackup(Map backup) { + this.backup = backup; + } + + public void setMap(Map map) { + this.map = map; + } + + public void setName(String name) { + this.name = name; + } + + public void setPath(String path) { + this.path = path; } @Override - public String getName() { // возвращает имя базы данных + public String getName() { return name; } @Override - public int size() { // Возврат числа ключей, хранимых в базе данных. - // Исключения не вырабатываються. - int summ = 0; // изначальный размер базы данных полагает равным 0. + public int size() { + int summ = 0; if (map != null) { - summ += map.size(); // сохраняем реальное число записей, хранимых в БД + summ += map.size(); } return summ; } @Override public String get(String key) throws IllegalArgumentException, - KeyNullAndNotFound { // возврашает - // значение - // по - // указанному - // ключу + KeyNullAndNotFound { if (key == null) { IllegalArgumentException exception = new IllegalArgumentException( "Error in get meth!"); exception.initCause(new KeyNullAndNotFound("Error!")); - throw exception; // если ключ null, тогда возбуждается - } // исключение + throw exception; + } if (map != null) { if (map.containsKey(key)) { return (String) map.get(key); @@ -69,45 +89,23 @@ public String get(String key) throws IllegalArgumentException, } @Override - public String put(String key, String value) throws IllegalArgumentException { // метод - // создан - // для - // записи - // ключа - // и - // значения - // в - // базу - // данных + public String put(String key, String value) throws IllegalArgumentException { String time = null; if (key == null || value == null) { throw new IllegalArgumentException( "Error in put-meth. Key or (and) value is wrong."); - } // если - // неверно - // заданы - // аргументы - // возбуждает исключение - if (map != null) { // случай, если база данных была непуста + } + if (map != null) { if (map.containsKey(key)) { time = (String) map.get(key); } } map.put(key, value); - return time; // возращает значение ранее ассоциированное с данным ключом - // null- если не было ранее никаких ассоциаций + return time; } @Override - public String remove(String key) throws IllegalArgumentException // удаляем - // значение - // ассоциированное - // с - // ключом, - // переданным - // в - // параметрах - { + public String remove(String key) throws IllegalArgumentException { String time = null; if (key == null) { throw new IllegalArgumentException( @@ -125,16 +123,14 @@ public String remove(String key) throws IllegalArgumentException // удаляе @SuppressWarnings({ "unchecked", "rawtypes" }) @Override - public List list() { // возврат списка, содержащего ключи базы - // данных + public List list() { Set time; if (map != null) { - time = map.keySet(); // получение ключей, имеющхся в базе данных в - // данный момент - List list = new ArrayList(time); - return (List) list; + time = map.keySet(); + List list = new ArrayList(time); + return list; } - return (List) (new ArrayList()); + return (new ArrayList()); } public int totalChanges() { @@ -142,31 +138,27 @@ public int totalChanges() { if (backup == null && map == null) { return 0; - }// изменений нет, не нужно коммитеть + } if (backup != null && map == null) { return backup.size(); - }// текущее состояние базы данных пусто, в - // бекапе есть записи, выполняеться перезапись + } if (backup == null && map != null) { return map.size(); - } // аналогично + } if (backup != null && map != null) { Set time = backup.keySet(); - for (String time1 : time) { + for (String timeKey : time) { - if (!(backup.get(time1).equals(map.get(time1)))) { - counter++; } - else if (!map.containsKey(time1)) { - counter++; + if (!(backup.get(timeKey).equals(map.get(timeKey)))) { + counter++; + } else if (!map.containsKey(timeKey)) { + counter++; } } time = map.keySet(); - for (String time1 : time) { + for (String timeKey : time) { - if (!backup.containsKey(time1)) { - // аналогично, однако, если один ключ был удален, а другой - // был - // добавлен, то считаеться что было произведено 2 изменения + if (!backup.containsKey(timeKey)) { counter++; } } @@ -177,62 +169,59 @@ else if (!map.containsKey(time1)) { @Override public int commit() { int counter = this.totalChanges(); - System.out.println("in this method counter is ==> " + counter); - if (counter != 0) { // если есть изменения вызывается физичекая запись - // на - // жесткий диск + if (counter != 0) { try { this.writeToDisk(); - } catch (IOException e) { - // do nothing + } catch (IOException ioexcptn) { + System.out.println(ioexcptn.toString()); } } - return counter; // возвращаеться общий счетчик числа изменений + return counter; } - public void writeToDisk() throws IOException { // метод, реально - // записывающий сделанные - // изменения на диск - int flag = 0; + public void writeToDisk() throws IOException { + int flagIfBaseExist = 0; Reader rd = new Reader(); FactoryImplements tb = new FactoryImplements(); TableProviderImplements tpi = (TableProviderImplements) tb.create(path); - rd.read(tpi); // считываем, имеющееся на диске - + rd.read(tpi); Writer writer = new Writer(); - if (tpi.t != null) { - for (int i = 0; i < tpi.t.length; i++) { - // System.out.println(tpi.t[i].getName()); - if (tpi.t[i].getName().equals(this.getName())) { + if (tpi.collection != null) { + for (int i = 0; i < tpi.collection.length; i++) { + if (tpi.collection[i].getName().equals(this.getName())) { { Map tmp = new HashMap(); @SuppressWarnings("unchecked") - Set copy = tpi.t[i].map.keySet(); + Set copy = tpi.collection[i].map.keySet(); for (String time : copy) { tmp.put(new String(time), - new String(tpi.t[i].map.get(time))); + new String((String) tpi.collection[i] + .getMap().get(time))); } this.backup = new HashMap(tmp); - } - tpi.t[i] = this; - flag = 1; + ; + + } + + tpi.collection[i] = this; + flagIfBaseExist = 1; } } } - if (flag == 0) { + if (flagIfBaseExist == 0) { tpi.createTable(this.name); this.backup = null; } - for (int i = 0; i < tpi.t.length; i++) { - if (tpi.t[i].getName().equals(this.getName())) { - tpi.t[i] = this; + for (int i = 0; i < tpi.collection.length; i++) { + if (tpi.collection[i].getName().equals(this.getName())) { + tpi.collection[i] = this; } } @@ -246,12 +235,10 @@ public void writeToDisk() throws IOException { // метод, реально } @Override - public int rollback() { // отвечает за откат к предыдущему состоянию (к - // самому последнему коммиту) + public int rollback() { Map time = new HashMap(this.map); this.map = new HashMap(this.backup); this.backup = time; - this.commit(); - return 0; + return this.commit(); } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java index 0170b90b9..2599098e5 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java @@ -3,38 +3,38 @@ public interface TableProvider { /** - * Возвращает таблицу с указанным названием. + * . * * @param name - * Название таблицы. - * @return Объект, представляющий таблицу. Если таблицы с указанным именем - * не существует, возвращает null. + * . + * @return , . + * , null. * @throws IllegalArgumentException - * Если название таблицы null или имеет недопустимое значение. + * null . */ Table getTable(String name); /** - * Создаёт таблицу с указанным названием. + * . * * @param name - * Название таблицы. - * @return Объект, представляющий таблицу. Если таблица уже существует, - * возвращает null. + * . + * @return , . , + * null. * @throws IllegalArgumentException - * Если название таблицы null или имеет недопустимое значение. + * null . */ Table createTable(String name); /** - * Удаляет таблицу с указанным названием. + * . * * @param name - * Название таблицы. + * . * @throws IllegalArgumentException - * Если название таблицы null или имеет недопустимое значение. + * null . * @throws IllegalStateException - * Если таблицы с указанным названием не существует. + * . */ void removeTable(String name); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java index 8f5860f47..a4629f11b 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java @@ -3,14 +3,14 @@ public interface TableProviderFactory { /** - * Возвращает объект для работы с базой данных. + * . * * @param dir - * Директория с файлами базы данных. - * @return Объект для работы с базой данных. + * . + * @return . * @throws IllegalArgumentException - * Если значение директории null или имеет недопустимое - * значение. + * null + * . */ TableProvider create(String dir); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java index e67e08f64..fb4c754fb 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java @@ -1,10 +1,11 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; import java.io.IOException; +import java.util.Collection; /** - * Класс @class TableProviderImplements содержит логику по работе провайдера - * базы данных. В нем переопределены все методы, заявленные в интерфейсе + * @class TableProviderImplements + * . , * TableProvider * * @author Timokhin Andrew @@ -12,12 +13,13 @@ public class TableProviderImplements implements TableProvider { - public TableImplement[] t; + @SuppressWarnings("rawtypes") + public TableImplement[] collection; public final String dir; TableProviderImplements(String dir) throws IOException { this.dir = dir; - t = null; + collection = null; Reader rd = new Reader(); rd.read(this); } @@ -28,116 +30,72 @@ public void writer() throws IOException { } @Override - public Table getTable(String name) throws IllegalArgumentException { // получение - // таблицы - // по - // ее - // имени + public Table getTable(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("Error in getTable-meth"); - } // вырабатывает - // исключение, - // если - // имя - // таблицы - // задано - // некорректно - if (t != null) { - for (int i = 0; i < t.length; i++) { - if (t[i].getName().equals(name)) { - return t[i]; - }// возврат таблицы, если такая существует + } + if (collection != null) { + for (int i = 0; i < collection.length; i++) { + if (collection[i].getName().equals(name)) { + return collection[i]; + } } } - return null; // возврат null в случае, если таблицу с указанным - // названием невозможно найти + return null; } @Override - public Table createTable(String name) throws IllegalArgumentException { // создает - // таблицу - // с - // указанным - // именем + public Table createTable(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("Error in createTable-meth"); - } // вырабатывает - // исключение, - // если - // имя - // таблицы - // задано - // некорректно - if (t != null) { - for (int i = 0; i < t.length; i++) { - if (name.equals(t[i].getName())) { - return null; // если таблица с указанным именем содержиться - // в агрегате, тогда возврат null + } + if (collection != null) { + for (int i = 0; i < collection.length; i++) { + if (name.equals(collection[i].getName())) { + return null; } } { - TableImplement[] temp = new TableImplement[t.length + 1]; - for (int k = 0; k < t.length; k++) { - temp[k] = t[k]; - } - - temp[t.length] = new TableImplement(name, dir); - t = temp; - return t[t.length - 1]; + TableImplement[] temp = new TableImplement[collection.length + 1]; + System.arraycopy(collection, 0, temp, 0, collection.length); + temp[collection.length] = new TableImplement(name, dir); + collection = temp; + return collection[collection.length - 1]; } } - if (t == null) { // на случай пустого агрегата, сразу создаем таблицу - // (без копирующего с пропуском алгоритма) - t = new TableImplement[1]; - t[0] = new TableImplement(name, dir); - return t[0]; + if (collection == null) { + collection = new TableImplement[1]; + collection[0] = new TableImplement(name, dir); + return collection[0]; } return null; } @Override public void removeTable(String name) throws IllegalArgumentException, - IllegalStateException { // удаление таблицы с указанным именем, - // возможна - // выроботка двух видов исключений + IllegalStateException { if (name == null) { throw new IllegalArgumentException("Error in removeTable-meth"); - }// если - // название - // таблицы - // неверно, - // тогда - // возбуждает - // исключение - if (t != null) { - for (int i = 0; i < t.length; i++) { // использует алгоритм - // копирования с пропусками - if (t[i].getName().equals(name)) { - t[i].backup = null; - t[i].map = null; - t[i].name = null; - TableImplement[] temp = new TableImplement[t.length - 1]; - for (int j = 0; j < i; j++) { - temp[j] = t[j]; - } - - for (int j = i + 1; j < t.length; j++) { - temp[j - 1] = t[j]; + } + if (collection != null) { + for (int i = 0; i < collection.length; i++) { + if (collection[i].getName().equals(name)) { + collection[i].setBackup(null); + collection[i].setMap(null); + collection[i].setName(null); + TableImplement[] temp = new TableImplement[collection.length - 1]; + System.arraycopy(collection, 0, temp, 0, i); + if (i < collection.length) { + System.arraycopy(collection, i + 1, temp, i, + collection.length - i - 1); } - t = temp; + collection = temp; return; } } - throw new IllegalStateException("Error in removeTable-meth"); // если - // таблицы, - // соответствующей - // параметру - // name - // не - // существовало - // то генерация исключения неверного состояния + throw new IllegalStateException("Error in removeTable-meth"); } } 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 index b16f477f7..8c901a407 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java @@ -30,8 +30,8 @@ public class FactoryImplementsTest { @Test public void testCreate() throws IOException { TableProviderImplements resultOne = (TableProviderImplements) new FactoryImplements() - .create("C:\\DataBase"); - assertEquals("C:\\DataBase", resultOne.dir); + .create("test"); + assertEquals("test", resultOne.dir); } @Test(expected = IllegalArgumentException.class) 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 index ebbf516c5..1f22c1c26 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java @@ -14,6 +14,8 @@ import org.junit.Rule; import org.junit.rules.TemporaryFolder; import java.lang.IllegalArgumentException; +import java.util.logging.Level; +import java.util.logging.Logger; /** * @@ -30,13 +32,13 @@ public class TableImplementTest { @Before public void setUp() { TableProviderFactory tpv = new FactoryImplements(); - path = tmp.newFolder("C:\\time").getAbsolutePath(); + path = tmp.newFolder("time").getAbsolutePath(); tp = tpv.create(path); tb = tp.createTable("testing"); FactoryImplements tb = new FactoryImplements(); TableProviderImplements tp = (TableProviderImplements) tb - .create("C:\\DataBase"); + .create("test"); Table time = tp.createTable("new"); time = tp.getTable("new"); @@ -74,14 +76,6 @@ public void testSizeAfterAddedAndDel() { assertEquals(0, result); } - /** - * Test of get method - */ - @Test(expected = IllegalArgumentException.class) - public void testGet() { - tb.get(null); - } - /** * Тестирование put метода */ @@ -134,7 +128,13 @@ public void testRemoveIfKeyExist() { tb.put(key, value); assertEquals(value, tb.remove(key)); - assertNull(tb.get(key)); + try { + assertNull(tb.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 @@ -184,7 +184,6 @@ public void testRollbackNullPointer() { tb.put("id123", "766"); tb.commit(); tb.rollback(); - } @Test @@ -197,6 +196,48 @@ public void testRollbackSomeChainChanges() { tb.put("54", "54"); tb.commit(); assertEquals(2, tb.rollback()); + } + + @Test + public void testCommitCheckRollbackCheck() throws IllegalArgumentException, KeyNullAndNotFound { + tb.put("1", "11"); + tb.put("2", "22"); + tb.put("3", "33"); + tb.commit(); + assertEquals("11", tb.get("1")); + assertEquals("22", tb.get("2")); + assertEquals("33", tb.get("3")); + tb.put("4", "44"); + tb.put("5", "55"); + tb.commit(); + assertEquals("44", tb.get("4")); + assertEquals("55", tb.get("5")); + tb.rollback(); + assertEquals(null, tb.get("4")); + assertEquals(null, tb.get("5")); + assertEquals("33", tb.get("3")); + assertEquals(3, tb.size()); + + } + + @Test + public void testCommitCheckChangesRollbackCheck() throws IllegalArgumentException, KeyNullAndNotFound { + tb.put("1", "11"); + tb.put("2", "22"); + tb.put("3", "33"); + tb.commit(); + assertEquals("11", tb.get("1")); + assertEquals("22", tb.get("2")); + assertEquals("33", tb.get("3")); + tb.put("4", "44"); + tb.put("5", "55"); + assertEquals("11", tb.remove("1")); + assertEquals("22", tb.remove("2")); + assertEquals(null, tb.remove("66")); + tb.commit(); + tb.rollback(); + assertEquals("11", tb.get("1")); + assertEquals(3, tb.size()); } 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 index a7e77f009..fe32b21c2 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java @@ -80,9 +80,7 @@ public void testRemoveTable() { @Test(expected = IllegalStateException.class) public void testRemoveTableDnExist() { - - tp.removeTable("test"); - + tp.removeTable("notexist"); } @Test @@ -90,7 +88,5 @@ public void testRemoveTableIfExist() { tp.createTable("test"); tp.removeTable("test"); assertNull(tp.getTable("test")); - } - } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java index af63c91fe..c457cfce1 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java @@ -5,11 +5,12 @@ import java.io.FileOutputStream; import java.io.IOException; import java.util.Set; +import static java.lang.Math.abs; /** - * Класс @class Writer отвечает за физическую запись информации с на жесткий - * диск или другой носитель информации. Логика работы устойчива к новым папкам и - * т.д. + * @class Writer + * . + * .. * * @author Timokhin Andrew */ @@ -17,26 +18,26 @@ public class Writer { boolean checkDir(String name) { - File time = new File(name); - return time.exists(); + File tmpFile = new File(name); + return tmpFile.exists(); } void createDir(String path) { - File time = new File(path); - time.mkdir(); + File tmpDir = new File(path); + tmpDir.mkdir(); // System.out.println(path); return; } void createFile(String path) throws IOException { - File time = new File(path); + File tmpFile = new File(path); - File prepareToMakeDir = new File(time.getParent().toString()); + File prepareToMakeDir = new File(tmpFile.getParent().toString()); prepareToMakeDir.mkdirs(); // System.out.println(prepareToMakeDir.getAbsolutePath()); - time.createNewFile(); + tmpFile.createNewFile(); return; } @@ -45,8 +46,8 @@ public void deleteDirectory(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { - File f = new File(dir, children[i]); - deleteDirectory(f); + File tmpFile = new File(dir, children[i]); + deleteDirectory(tmpFile); } dir.delete(); } else { @@ -54,50 +55,42 @@ public void deleteDirectory(File dir) { } } - public int abs(int digital) { - if (digital < 0) { - return -digital; - } - return digital; - } - public void write(TableProviderImplements tp) throws IOException { this.deleteDirectory(new File(tp.dir)); - File fl = new File(tp.dir); - fl.mkdir(); - if (tp.t != null) { - for (TableImplement ti : tp.t) { - File db = new File(tp.dir + "\\" + ti.name); - db.mkdir(); - if (ti.map != null) { + File baseDir = new File(tp.dir); + baseDir.mkdir(); + if (tp.collection != null) { + for (TableImplement ti : tp.collection) { + File dataBaseDir = new File(tp.dir + "\\" + ti.getName()); + dataBaseDir.mkdir(); + if (ti.getMap() != null) { Set keyList; - keyList = ti.map.keySet(); + keyList = ti.getMap().keySet(); for (String keyFind : keyList) { Integer dirToWrite = new Integer( - abs(keyFind.hashCode() % 16)); // номер - // директории для - // записи - String localPath = tp.dir + "\\" + ti.name + "\\" + abs(keyFind.hashCode() % 16)); + String localPath = tp.dir + "\\" + ti.getName() + "\\" + dirToWrite.toString() + ".dir"; if (!this.checkDir(localPath)) { this.createDir(localPath); } - dirToWrite = new Integer(abs(ti.map.get(keyFind) - .hashCode() % 16 % 16)); // номер файла для - // записи - String localfile = localPath + "\\" + dirToWrite = new Integer(abs(ti.getMap().get(keyFind) + .hashCode() % 16 % 16)); + String localFile = localPath + "\\" + dirToWrite.toString(); - if (!this.checkDir(localfile)) { - this.createFile(localfile); + if (!this.checkDir(localFile)) { + this.createFile(localFile); } - DataOutputStream out = new DataOutputStream( - new FileOutputStream(localfile)); - out.writeInt(keyFind.length()); - out.writeChars(keyFind); - out.writeInt(ti.map.get(keyFind).length()); - out.writeChars(ti.map.get(keyFind)); - out.close(); + DataOutputStream outStream = new DataOutputStream( + new FileOutputStream(localFile)); + outStream.writeInt(keyFind.length()); + outStream.writeChars(keyFind); + outStream.writeInt(ti.getMap().get(keyFind).toString() + .length()); + outStream.writeChars(ti.getMap().get(keyFind) + .toString()); + outStream.close(); } } From 10bf88b6fcf7d21301f525054c936a90f85bbc40 Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Fri, 30 Jan 2015 05:10:33 +0300 Subject: [PATCH 06/18] *utf-8* --- .../AndrewTimokhin/FileMap/JUnit/FactoryImplements.java | 6 +++--- .../fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java | 4 ++-- .../AndrewTimokhin/FileMap/JUnit/TableImplement.java | 4 ++-- .../FileMap/JUnit/TableProviderImplements.java | 4 ++-- .../fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java | 6 +++--- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java index c891e4c42..48d6464d3 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java @@ -3,9 +3,9 @@ import java.io.IOException; /** - * @class FactoryImplements . - * TableProviderFactory, - * . + * Класс @class FactoryImplements отвечает за фабрику по созданию таблиц. + * Имплиментируя интерфейс TableProviderFactory, переопределяет метод по + * созданию провайдера базы данных. * * @author Timokhin Andrew */ diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java index 4a20dc40a..b0b11eef8 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java @@ -10,8 +10,8 @@ import java.util.Vector; /** - * @class Reader - * . + * Класс @class Reader отвечает за физическое чтение данных с жесткого диска или + * другого физического носителя информации. * * * @author Timokhin Andrew diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java index aff38c87d..1b76c9c3a 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java @@ -1,8 +1,8 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; /** - * TableImplement . - * , Table + * Класс TableImplement содержит логику работы таблицы базы данных. + * В нем переопределены все методы, которые заявлены в интерфейсе Table * * @author Timokhin Andrew */ diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java index fb4c754fb..ce10f755d 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java @@ -4,8 +4,8 @@ import java.util.Collection; /** - * @class TableProviderImplements - * . , + * Класс @class TableProviderImplements содержит логику по работе провайдера + * базы данных. В нем переопределены все методы, заявленные в интерфейсе * TableProvider * * @author Timokhin Andrew diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java index c457cfce1..e886419d3 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java @@ -8,9 +8,9 @@ import static java.lang.Math.abs; /** - * @class Writer - * . - * .. + * Класс @class Writer отвечает за физическую запись информации с на жесткий + * диск или другой носитель информации. Логика работы устойчива к новым папкам и + * т.д. * * @author Timokhin Andrew */ From 1e0693a187a2967efbac9713ab5e595d1a476b1d Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Sun, 1 Feb 2015 05:08:01 +0300 Subject: [PATCH 07/18] *final_version* --- .../FileMap/JUnit/FactoryImplements.java | 7 +- .../FileMap/JUnit/InteractiveMode.java | 187 ++++++++++++++++++ .../AndrewTimokhin/FileMap/JUnit/JUnit.java | 113 +++++------ .../FileMap/JUnit/KeyNullAndNotFound.java | 1 - .../AndrewTimokhin/FileMap/JUnit/Reader.java | 66 +++---- .../AndrewTimokhin/FileMap/JUnit/Table.java | 46 ++--- .../FileMap/JUnit/TableImplement.java | 120 +++++------ .../FileMap/JUnit/TableProvider.java | 28 +-- .../FileMap/JUnit/TableProviderFactory.java | 10 +- .../JUnit/TableProviderImplements.java | 98 +++++---- .../JUnit/Test/FactoryImplementsTest.java | 14 +- .../JUnit/Test/TableImplementTest.java | 181 +++++++++-------- .../Test/TableProviderImplementsTest.java | 6 +- .../FileMap/JUnit/UnknownCommand.java | 16 ++ .../AndrewTimokhin/FileMap/JUnit/Writer.java | 47 +++-- 15 files changed, 548 insertions(+), 392 deletions(-) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/UnknownCommand.java diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java index 48d6464d3..aaac7ac10 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java @@ -15,13 +15,14 @@ public class FactoryImplements implements TableProviderFactory { @Override public TableProvider create(String dir) { if (dir == null) { - throw new IllegalArgumentException("Error in create-meth."); + throw new IllegalArgumentException( + "Info: String representing directory is null"); } try { return new TableProviderImplements(dir); } catch (IOException xcpt) { - System.out.println(xcpt.toString()); + throw new RuntimeException( + "Info: Target directory cannot be created or you don't have access to creating files! Try to run as administrator"); } - return null; } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java new file mode 100644 index 000000000..5bd60cdab --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java @@ -0,0 +1,187 @@ +/* + * 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 java.util.Set; + +/** + * + * @author Timokhin Andrew + * + */ +public class InteractiveMode { + private TableImplement table; + final TableProviderImplements provider; + final FactoryImplements factory; + String currentDir; + + InteractiveMode(String path) { + factory = new FactoryImplements(); + provider = (TableProviderImplements) factory.create(path); + currentDir = null; + } + + private void invitationToRepeat() { + System.out + .println("Current command was not recognized or not complete. Please, try again"); + } + + boolean command(String textToParser) throws UnknownCommand, + IllegalArgumentException, KeyNullAndNotFound { + String[] commands = textToParser.trim().split(" "); + if (commands.length < 1) + throw new UnknownCommand( + "Current command was not recognized. Programm fail"); + switch (commands[0]) { + case "create": + if (commands.length != 2) { + this.invitationToRepeat(); + break; + } + if (provider.createTable(commands[1]) == null) + System.out.println("Exist!"); + else + System.out.println("created"); + break; + case "put": + if (commands.length != 3) { + this.invitationToRepeat(); + break; + } else if (table == null) { + System.out.println("No table"); + break; + } else { + String oldValue = table.put(commands[1], commands[2]); + if (oldValue != null) + System.out.println("*old* -> " + oldValue); + else + System.out.println("*new*"); + break; + } + case "get": + if (commands.length != 2) { + this.invitationToRepeat(); + break; + } else if (table == null) { + System.out.println("No table"); + break; + } else { + String value = table.get(commands[1]); + if (value != null) + System.out.println("*value* -> " + value); + else + System.out.println("*not exist*"); + break; + } + case "remove": + if (commands.length != 2) { + this.invitationToRepeat(); + break; + } else if (table == null) { + System.out.println("No table"); + break; + } else { + if (commands[1] == null) { + System.out.println("*wrong key"); + break; + } + String value = table.remove(commands[1]); + if (value != null) + System.out.println("*value* -> " + value); + else + System.out.println("*not removed, because not exist*"); + break; + } + case "drop": + if (commands.length != 2) { + this.invitationToRepeat(); + break; + } + try { + provider.removeTable(commands[1]); + System.out.println("dropped"); + } catch (IllegalStateException error) { + System.out.println("Not exists"); + } catch (IllegalArgumentException error) { + System.out.println(error); + } + break; + case "commit": + if (commands.length != 1) { + this.invitationToRepeat(); + break; + } + if (table != null) + System.out.println("Total changes -> " + table.commit()); + else + System.out.println("No table"); + break; + + case "rollback": + if (commands.length != 1) { + this.invitationToRepeat(); + break; + } + if (table != null) + System.out.println("Total changes -> " + table.rollback()); + else + System.out.println("No table"); + break; + case "use": + if (commands.length != 2) { + this.invitationToRepeat(); + break; + } + table = (TableImplement) provider.getTable(commands[1]); + if (table == null) + System.out.println("Not exists"); + else { + if (table.totalChanges() > 0) + System.out.println("Need commit->"); + else + System.out.println("Using"); + } + break; + case "size": + if (commands.length != 1) { + this.invitationToRepeat(); + break; + } + { + int totalSize = 0; + Set set = provider.collection.keySet(); + for (String key : set) { + totalSize += provider.collection.get(key).size(); + } + System.out.println(totalSize); + } + break; + case "list": + if (commands.length != 1) { + this.invitationToRepeat(); + break; + } else if (table == null) { + System.out.println("No table"); + break; + } else { + Set set = table.getMap().keySet(); + for (String key : set) { + System.out.println(key + " " + table.get(key)); + } + break; + } + case "exit": { + if (table != null) + table.commit(); + return false; + } + default: + this.invitationToRepeat(); + break; + } + return true; + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java index ab7904577..d11b9ebdb 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java @@ -1,72 +1,67 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; import java.io.IOException; +import java.util.Scanner; +import java.util.logging.Level; +import java.util.logging.Logger; public class JUnit { public static void main(String[] args) throws IOException, IllegalArgumentException, KeyNullAndNotFound { - FactoryImplements tb = new FactoryImplements(); - TableProviderImplements tp = (TableProviderImplements) tb - .create("C:\\DataBase"); - Table tableA1 = tp.createTable("A1"); - tableA1 = tp.getTable("A1"); + InteractiveMode user = new InteractiveMode("C:\\DataBase"); + Scanner sc = new Scanner(System.in); - /* - * Uncomment to see, that we have, when we run this programm twice. A1 - * must be : (1,1); (2,2); (3,3); A2 must be : all changes - */ - /* - * System.out.println("<===twice===>\n"); for (String tm : - * tableA1.list()) { System.out.println("key -> " + tm + " value -> " + - * tableA1.get(tm) ); } System.out.println("\n<===twice===>\n"); - */ - - tableA1.put("1", "1"); - tableA1.put("2", "2"); - tableA1.put("3", "3"); - tableA1.commit(); - tableA1.put("4", "4"); - tableA1.put("5", "5"); - tableA1.put("6", "6"); - tableA1.put("7", "7"); - tableA1.commit(); - tableA1.rollback(); - - for (String tm : tableA1.list()) { - System.out.println("key -> " + tm + " value -> " + tableA1.get(tm)); - } - - Table tableA2 = tp.createTable("A2"); - tableA2 = tp.getTable("A2"); - - /* - * System.out.println("<===twice===> \n"); for (String time: - * tableA2.list()){ System.out.println("key -> " + time + " value -> " + - * tableA2.get(time) ); } System.out.println("\n<===twice===> \n"); - */ - - tableA2.put("1", "green"); - tableA2.put("2", "blue"); + try { + while (user.command(sc.nextLine())); + /* + * FactoryImplements tb = new FactoryImplements(); + * TableProviderImplements tp = (TableProviderImplements) tb + * .create("C:\\DataBase"); Table tableA1 = tp.createTable("A1"); + * tableA1 = tp.getTable("A1"); + * + * /* Uncomment to see, that we have, when we run this programm + * twice. A1 must be : (1,1); (2,2); (3,3); A2 must be : all changes + */ + /* + * System.out.println("<===twice===>\n"); for (String tm : + * tableA1.list()) { System.out.println("key -> " + tm + + * " value -> " + tableA1.get(tm) ); } + * System.out.println("\n<===twice===>\n"); + */ - System.out.println("<========NEXT========>\n"); - tableA2.remove("1"); + /* + * tableA1.put("1", "1"); tableA1.put("2", "2"); tableA1.put("3", + * "3"); tableA1.commit(); tableA1.put("4", "4"); tableA1.put("5", + * "5"); tableA1.put("6", "6"); tableA1.put("7", "7"); + * tableA1.commit(); tableA1.rollback(); + * + * for (String tm : tableA1.list()) { System.out.println("key -> " + + * tm + " value -> " + tableA1.get(tm)); } + * + * Table tableA2 = tp.createTable("A2"); tableA2 = + * tp.getTable("A2"); + * + * /* System.out.println("<===twice===> \n"); for (String time: + * tableA2.list()){ System.out.println("key -> " + time + + * " value -> " + tableA2.get(time) ); } + * System.out.println("\n<===twice===> \n"); + */ - for (String time : tableA2.list()) { - System.out.println("key -> " + time + " value -> " - + tableA2.get(time)); + /* + * tableA2.put("1", "green"); tableA2.put("2", "blue"); + * + * System.out.println("<========NEXT========>\n"); + * tableA2.remove("1"); + * + * for (String time : tableA2.list()) { System.out.println("key -> " + * + time + " value -> " + tableA2.get(time)); } + * + * tableA2.commit(); tableA2.put("3", "green"); tableA2.put("4", + * "black"); tableA2.put("5", "red"); tableA2.commit(); try { + * tableA2.get(null); } catch (KeyNullAndNotFound e) { + * System.out.println(e); } System.out.println(tableA2.get("4")); + */ + } catch (UnknownCommand ex) { } - - tableA2.commit(); - tableA2.put("3", "green"); - tableA2.put("4", "black"); - tableA2.put("5", "red"); - tableA2.commit(); - try { - tableA2.get(null); - } catch (IllegalArgumentException e) { - System.out.println("\n" + e + "\n" + e.getCause() + "\n"); - } - System.out.println(tableA2.get("4")); - } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java index c8e01d8cc..14844565b 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java @@ -5,5 +5,4 @@ public class KeyNullAndNotFound extends Exception { public KeyNullAndNotFound(String description) { super(description); } - } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java index b0b11eef8..0d5ff53a2 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java @@ -6,63 +6,64 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; import java.util.Iterator; +import java.util.Map; import java.util.Vector; /** - * Класс @class Reader отвечает за физическое чтение данных с жесткого диска или - * другого физического носителя информации. + * Класс @class Reader отвечает за физическое чтение данных из файловой системы. * * * @author Timokhin Andrew */ public class Reader { + final int totalSubDir = 16; + final String direct = ".dir"; + public void read(TableProviderImplements tp) throws IOException { - int i; StringBuilder keyBuilder = new StringBuilder(); StringBuilder valueBuilder = new StringBuilder(); int length; String path = tp.dir; - Vector agregat = new Vector(); - int validator = 0; + Vector tables = new Vector(); + boolean dbExist = false; File testDir = new File(path); if (testDir.list() != null) { for (String time : testDir.list()) { - File checkDir = new File(path + "\\" + time); - + Path pathToFile = Paths.get(path, time); + File checkDir = new File(pathToFile.toString()); if (checkDir.isDirectory()) { - validator++; + dbExist = true; TableImplement dataBase = new TableImplement(time, tp.dir); - agregat.add(dataBase); - for (i = 0; i < 16; i++) { + tables.add(dataBase); + for (int i = 0; i < totalSubDir; i++) { Integer numberDir = new Integer(i); - File locDB = new File(path + "\\" + time + "\\" - + numberDir.toString() + ".dir"); + Path pathToDb = Paths.get(path, time, + numberDir.toString() + direct); + 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( - locDB.getAbsolutePath() + "\\" - + file))) { - + pathToLocalDb.toString()))) { while (true) { - try { length = rd.readInt(); for (int k = 0; k < length; k++) { keyBuilder .append(rd.readChar()); - } length = rd.readInt(); for (int k = 0; k < length; k++) { valueBuilder.append(rd .readChar()); - } - dataBase.getMap().put( keyBuilder.toString(), valueBuilder.toString()); @@ -74,40 +75,27 @@ public void read(TableProviderImplements tp) throws IOException { valueBuilder.replace(0, valueBuilder.length(), ""); } catch (EOFException e) { - break; } - } - } catch (FileNotFoundException fnfe) { - System.out.println(fnfe.toString()); - + throw new RuntimeException( + "Info: Target directory cannot be read! Try to run as administrator"); } - } } } - } - } } - if (validator == 0) { + if (!dbExist) { return; } - TableImplement[] copy = new TableImplement[agregat.size()]; - i = 0; - Iterator it = agregat.iterator(); - - while (it.hasNext()) { - - copy[i] = it.next(); - i++; + Map copy = new HashMap<>(); + for (TableImplement table : tables) { + copy.put(table.getName(), table); } tp.collection = copy; return; - } - } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java index bcc338f37..abcf1dbc1 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java @@ -5,75 +5,75 @@ public interface Table { /** - * . + * Возвращает название базы данных. */ String getName(); /** - * . + * Получает значение по указанному ключу. * * @param key - * . - * @return . , null. + * Ключ. + * @return Значение. Если не найдено, возвращает null. * @throws KeyNullAndNotFound * * @throws IllegalArgumentException - * key null. + * Если значение параметра key является null. */ String get(String key) throws IllegalArgumentException, KeyNullAndNotFound; /** - * . + * Устанавливает значение по указанному ключу. * * @param key - * . + * Ключ. * @param value - * . - * @return , . - * , null. + * Значение. + * @return Значение, которое было записано по этому ключу ранее. Если ранее + * значения не было записано, возвращает null. * * @throws IllegalArgumentException - * key value null. + * Если значение параметров key или value является null. */ String put(String key, String value); /** - * . + * Удаляет значение по указанному ключу. * * @param key - * . - * @return . , null. + * Ключ. + * @return Значение. Если не найдено, возвращает null. * * @throws IllegalArgumentException - * key null. + * Если значение параметра key является null. */ String remove(String key); /** - * . + * Возвращает количество ключей в таблице. * - * @return . + * @return Количество ключей в таблице. */ int size(); /** - * . + * Выполняет фиксацию изменений. * - * @return . + * @return Количество сохранённых ключей. */ int commit(); /** - * . + * Выполняет откат изменений с момента последней фиксации. * - * @return . + * @return Количество отменённых ключей. */ int rollback(); /** - * + * Выводит список ключей таблицы * - * @return . + * @return Список ключей. */ List list(); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java index 1b76c9c3a..1d02056d7 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java @@ -10,6 +10,7 @@ import java.io.IOException; import java.util.List; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -20,12 +21,14 @@ public class TableImplement implements Table { private String path; private Map map; private Map backup; + public Map current; public TableImplement(String name, String path) { this.path = path; this.name = name; map = new HashMap(); backup = new HashMap(); + current = new HashMap(); } public String getPath() { @@ -63,29 +66,25 @@ public String getName() { @Override public int size() { - int summ = 0; + int size = 0; if (map != null) { - summ += map.size(); + size += map.size(); } - return summ; + return size; } @Override public String get(String key) throws IllegalArgumentException, KeyNullAndNotFound { if (key == null) { - IllegalArgumentException exception = new IllegalArgumentException( - "Error in get meth!"); - exception.initCause(new KeyNullAndNotFound("Error!")); - throw exception; + throw new KeyNullAndNotFound("Info: Key is null"); } if (map != null) { if (map.containsKey(key)) { - return (String) map.get(key); + return map.get(key); } } return null; - } @Override @@ -93,7 +92,7 @@ public String put(String key, String value) throws IllegalArgumentException { String time = null; if (key == null || value == null) { throw new IllegalArgumentException( - "Error in put-meth. Key or (and) value is wrong."); + "Info: Key or (and) value is wrong."); } if (map != null) { if (map.containsKey(key)) { @@ -108,34 +107,28 @@ public String put(String key, String value) throws IllegalArgumentException { public String remove(String key) throws IllegalArgumentException { String time = null; if (key == null) { - throw new IllegalArgumentException( - "Error in remove-meth. Key is wrong."); + throw new IllegalArgumentException("Info: Key is wrong."); } - if (map != null) { + if (map != null) { // if map is empty, then it is null if (map.containsKey(key)) { time = (String) map.get(key); map.remove(key); } } return time; - } - @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public List list() { Set time; if (map != null) { - time = map.keySet(); - List list = new ArrayList(time); - return list; + return new ArrayList(map.keySet()); } - return (new ArrayList()); + return new ArrayList(); // if map is empty } public int totalChanges() { int counter = 0; - if (backup == null && map == null) { return 0; } @@ -146,18 +139,17 @@ public int totalChanges() { return map.size(); } if (backup != null && map != null) { - Set time = backup.keySet(); - for (String timeKey : time) { - - if (!(backup.get(timeKey).equals(map.get(timeKey)))) { + Set backupKey = backup.keySet(); + for (String timeKey : backupKey) { + if (map.containsKey(timeKey) + && !(backup.get(timeKey).equals(map.get(timeKey)))) { counter++; } else if (!map.containsKey(timeKey)) { counter++; } } - time = map.keySet(); - for (String timeKey : time) { - + backupKey = map.keySet(); + for (String timeKey : backupKey) { if (!backup.containsKey(timeKey)) { counter++; } @@ -168,70 +160,50 @@ public int totalChanges() { @Override public int commit() { - int counter = this.totalChanges(); - if (counter != 0) { - try { - - this.writeToDisk(); - } catch (IOException ioexcptn) { - System.out.println(ioexcptn.toString()); - } + try { + return this.writeToDisk(); + } catch (IOException ioexcptn) { + throw new RuntimeException("Cannot write to the File System"); } - return counter; } - public void writeToDisk() throws IOException { - int flagIfBaseExist = 0; + public int writeToDisk() throws IOException { + boolean flagIfBaseExist = false; Reader rd = new Reader(); - FactoryImplements tb = new FactoryImplements(); - TableProviderImplements tpi = (TableProviderImplements) tb.create(path); - - rd.read(tpi); + TableProviderImplements tableProvider = (TableProviderImplements) tb + .create(path); + rd.read(tableProvider); Writer writer = new Writer(); - if (tpi.collection != null) { - for (int i = 0; i < tpi.collection.length; i++) { - if (tpi.collection[i].getName().equals(this.getName())) { - + if (tableProvider.collection != null) { + { + if (tableProvider.collection.containsKey(this.getName())) { { - Map tmp = new HashMap(); - @SuppressWarnings("unchecked") - Set copy = tpi.collection[i].map.keySet(); + Map tmp = new HashMap<>(); + Set copy = tableProvider.collection.get(name).map + .keySet(); for (String time : copy) { - tmp.put(new String(time), - new String((String) tpi.collection[i] - .getMap().get(time))); + new String( + (String) tableProvider.collection + .get(name).map.get(time))); } this.backup = new HashMap(tmp); - ; - } - - tpi.collection[i] = this; - flagIfBaseExist = 1; + tableProvider.collection.put(this.getName(), this); + flagIfBaseExist = true; } - } - } - if (flagIfBaseExist == 0) { - tpi.createTable(this.name); + if (!flagIfBaseExist) { + tableProvider.createTable(this.name); this.backup = null; } - for (int i = 0; i < tpi.collection.length; i++) { - if (tpi.collection[i].getName().equals(this.getName())) { - tpi.collection[i] = this; - } - - } - - writer.write(tpi); - if (this.map == null) { - // this.commit(); - - } - + if (tableProvider.collection.containsKey(this.getName())) + tableProvider.collection.put(this.getName(), this); + if (this.totalChanges() > 0) + writer.write(tableProvider); + return this.totalChanges(); } @Override diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java index 2599098e5..0170b90b9 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java @@ -3,38 +3,38 @@ public interface TableProvider { /** - * . + * Возвращает таблицу с указанным названием. * * @param name - * . - * @return , . - * , null. + * Название таблицы. + * @return Объект, представляющий таблицу. Если таблицы с указанным именем + * не существует, возвращает null. * @throws IllegalArgumentException - * null . + * Если название таблицы null или имеет недопустимое значение. */ Table getTable(String name); /** - * . + * Создаёт таблицу с указанным названием. * * @param name - * . - * @return , . , - * null. + * Название таблицы. + * @return Объект, представляющий таблицу. Если таблица уже существует, + * возвращает null. * @throws IllegalArgumentException - * null . + * Если название таблицы null или имеет недопустимое значение. */ Table createTable(String name); /** - * . + * Удаляет таблицу с указанным названием. * * @param name - * . + * Название таблицы. * @throws IllegalArgumentException - * null . + * Если название таблицы null или имеет недопустимое значение. * @throws IllegalStateException - * . + * Если таблицы с указанным названием не существует. */ void removeTable(String name); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java index a4629f11b..8f5860f47 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java @@ -3,14 +3,14 @@ public interface TableProviderFactory { /** - * . + * Возвращает объект для работы с базой данных. * * @param dir - * . - * @return . + * Директория с файлами базы данных. + * @return Объект для работы с базой данных. * @throws IllegalArgumentException - * null - * . + * Если значение директории null или имеет недопустимое + * значение. */ TableProvider create(String dir); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java index ce10f755d..86fa7e1ec 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java @@ -1,46 +1,55 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +import java.io.File; import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Collection; +import java.util.HashMap; +import java.util.Map; /** - * Класс @class TableProviderImplements содержит логику по работе провайдера - * базы данных. В нем переопределены все методы, заявленные в интерфейсе - * TableProvider - * * @author Timokhin Andrew */ public class TableProviderImplements implements TableProvider { - @SuppressWarnings("rawtypes") - public TableImplement[] collection; + public static void deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + for (int i = 0; i < children.length; i++) { + File f = new File(dir, children[i]); + deleteDir(f); + } + dir.delete(); + } else + dir.delete(); + } + + protected Map collection; public final String dir; TableProviderImplements(String dir) throws IOException { this.dir = dir; - collection = null; + collection = new HashMap<>(); Reader rd = new Reader(); rd.read(this); } - public void writer() throws IOException { - Writer writer = new Writer(); - writer.write(this); + public void write() throws IOException { + Writer writeToFileSystem = new Writer(); + writeToFileSystem.write(this); } @Override public Table getTable(String name) throws IllegalArgumentException { if (name == null) { - throw new IllegalArgumentException("Error in getTable-meth"); + throw new IllegalArgumentException( + "Info: Name of DataBase is null. Please, enter correct name"); } - if (collection != null) { - for (int i = 0; i < collection.length; i++) { - if (collection[i].getName().equals(name)) { - return collection[i]; - } - - } + if (collection != null) { // if database is created now + if (collection.containsKey(name)) + return collection.get(name); } return null; } @@ -48,27 +57,21 @@ public Table getTable(String name) throws IllegalArgumentException { @Override public Table createTable(String name) throws IllegalArgumentException { if (name == null) { - throw new IllegalArgumentException("Error in createTable-meth"); + throw new IllegalArgumentException( + "Info: Name of DataBase is null. Please, enter correct name"); } if (collection != null) { - for (int i = 0; i < collection.length; i++) { - if (name.equals(collection[i].getName())) { - return null; - } - } + if (collection.containsKey(name)) + return null; { - TableImplement[] temp = new TableImplement[collection.length + 1]; - System.arraycopy(collection, 0, temp, 0, collection.length); - temp[collection.length] = new TableImplement(name, dir); - collection = temp; - return collection[collection.length - 1]; + collection.put(name, new TableImplement(name, dir)); + return collection.get(name); } } - if (collection == null) { - collection = new TableImplement[1]; - collection[0] = new TableImplement(name, dir); - return collection[0]; + collection = new HashMap<>(); + collection.put(name, new TableImplement(name, dir)); + return collection.get(name); } return null; } @@ -77,27 +80,20 @@ public Table createTable(String name) throws IllegalArgumentException { public void removeTable(String name) throws IllegalArgumentException, IllegalStateException { if (name == null) { - throw new IllegalArgumentException("Error in removeTable-meth"); + throw new IllegalArgumentException( + "Info: Name of DataBase is null. Please, enter correct name"); } if (collection != null) { - for (int i = 0; i < collection.length; i++) { - if (collection[i].getName().equals(name)) { - collection[i].setBackup(null); - collection[i].setMap(null); - collection[i].setName(null); - TableImplement[] temp = new TableImplement[collection.length - 1]; - System.arraycopy(collection, 0, temp, 0, i); - if (i < collection.length) { - System.arraycopy(collection, i + 1, temp, i, - collection.length - i - 1); - } - collection = temp; - return; - } + if (collection.containsKey(name)) { + Path path = Paths.get( + collection.get(name).getPath().toString(), collection + .get(name).getName()); + File file = new File(path.toString()); + this.deleteDir(file); + collection.remove(name); + return; } - throw new IllegalStateException("Error in removeTable-meth"); } - + throw new IllegalStateException("Requested database don't exist"); } - } 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 index 8c901a407..3c56d61ae 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java @@ -1,8 +1,3 @@ -/* - * Создание тестов для класса FactoryImplements - * Данные тесты в полном объеме проверяют функциональность - * соответствующего класса, включая граничные случаи - */ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; import java.io.IOException; @@ -13,17 +8,12 @@ /** * - * @author Андрей + * @author Timokhin Andrew */ public class FactoryImplementsTest { private final Map agregaret = new HashMap(); /** - * Тест работает на проверку генерации исключения IllegalArgumentException - * при попытке создать провайдера базы данных с пустой корневой директорией. - * Также тестируеться создание провайдера базы данных с корректной - * директорией. - * * @throws java.io.IOException */ @@ -35,7 +25,7 @@ public void testCreate() throws IOException { } @Test(expected = IllegalArgumentException.class) - public void testCreateCorrect() { + 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 index 1f22c1c26..f7646a9d7 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java @@ -25,22 +25,22 @@ public class TableImplementTest { @Rule public TemporaryFolder tmp = new TemporaryFolder(); - public TableProvider tp; + public TableProvider tableProvider; public String path; - public Table tb; + public Table table; @Before public void setUp() { TableProviderFactory tpv = new FactoryImplements(); path = tmp.newFolder("time").getAbsolutePath(); - tp = tpv.create(path); - tb = tp.createTable("testing"); + tableProvider = tpv.create(path); + table = tableProvider.createTable("testing"); - FactoryImplements tb = new FactoryImplements(); - TableProviderImplements tp = (TableProviderImplements) tb + FactoryImplements factory = new FactoryImplements(); + TableProviderImplements tableProvider = (TableProviderImplements) factory .create("test"); - Table time = tp.createTable("new"); - time = tp.getTable("new"); + Table time = tableProvider.createTable("new"); + time = tableProvider.getTable("new"); } @@ -49,8 +49,7 @@ public void setUp() { */ @Test public void testGetName() { - String result = tb.getName(); - assertTrue("testing".equals(result)); + assertTrue("testing".equals(table.getName())); } /** @@ -58,21 +57,20 @@ public void testGetName() { */ @Test public void testSizeByDefault() { - int result = tb.size(); - assertEquals(0, result); + assertEquals(0, table.size()); } @Test public void testSizeAfterAddedAndDel() { - tb.put("1", "11"); - tb.put("2", "22"); - int result = tb.size(); + table.put("1", "11"); + table.put("2", "22"); + int result = table.size(); assertEquals(2, result); - tb.remove("2"); - result = tb.size(); + table.remove("2"); + result = table.size(); assertEquals(1, result); - tb.remove("1"); - result = tb.size(); + table.remove("1"); + result = table.size(); assertEquals(0, result); } @@ -82,25 +80,25 @@ public void testSizeAfterAddedAndDel() { @Test(expected = IllegalArgumentException.class) public void testPutIfKeyIsNull() { String value = "test_value"; - tb.put(null, value); + table.put(null, value); } @Test(expected = IllegalArgumentException.class) public void testPutIfValueIsNull() { String key = "test_key"; - tb.put(key, null); + table.put(key, null); } @Test(expected = IllegalArgumentException.class) public void testPutIfValueAndKeyIsNull() { - tb.put(null, null); + table.put(null, null); } @Test public void testPutIfKeyDnHaveInDataBase() { String key = "test_key"; String value = "test_value"; - assertNull(tb.put(key, value)); + assertNull(table.put(key, value)); } @Test @@ -109,8 +107,8 @@ public void testPutIfKeyHaveInDataBase() { String valueOld = "test_value_old"; String valueNew = "test_value_new"; - assertNull(tb.put(key, valueOld)); - assertEquals(valueOld, tb.put(key, valueNew)); + assertNull(table.put(key, valueOld)); + assertEquals(valueOld, table.put(key, valueNew)); } /** @@ -118,18 +116,18 @@ public void testPutIfKeyHaveInDataBase() { */ @Test(expected = IllegalArgumentException.class) public void testRemoveIfKeyNull() { - tb.remove(null); + table.remove(null); } @Test public void testRemoveIfKeyExist() { String key = "key_test"; String value = "value_test"; - tb.put(key, value); + table.put(key, value); - assertEquals(value, tb.remove(key)); + assertEquals(value, table.remove(key)); try { - assertNull(tb.get(key)); + assertNull(table.get(key)); } catch (IllegalArgumentException ex) { Logger.getLogger(TableImplementTest.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyNullAndNotFound ex) { @@ -141,7 +139,7 @@ public void testRemoveIfKeyExist() { public void testRemoveIfKeyDnExist() { String key = "key_test"; - assertNull(tb.remove(key)); + assertNull(table.remove(key)); } /** @@ -149,24 +147,33 @@ public void testRemoveIfKeyDnExist() { */ @Test public void testCommitIfEmpty() { - assertEquals(0, tb.commit()); + assertEquals(0, table.commit()); } @Test public void testCommitIfFullAnything() { - tb.put("id564", "989"); - tb.put("id988", "123"); - tb.put("id123", "766"); - assertEquals(3, tb.commit()); + table.put("id564", "989"); + table.put("id988", "123"); + table.put("id123", "766"); + assertEquals(3, table.commit()); } public void testCommitIfWasRollback() { - tb.put("id564", "989"); - tb.put("id988", "123"); - tb.put("id123", "766"); - tb.rollback(); + table.put("id564", "989"); + table.put("id988", "123"); + table.put("id123", "766"); + table.rollback(); - assertEquals(0, tb.commit()); + 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()); } /** @@ -174,70 +181,70 @@ public void testCommitIfWasRollback() { */ @Test public void testRollbackIfStateEmpty() { - assertEquals(0, tb.rollback()); + assertEquals(0, table.rollback()); } @Test(expected = NullPointerException.class) public void testRollbackNullPointer() { - tb.put("id564", "989"); - tb.put("id988", "123"); - tb.put("id123", "766"); - tb.commit(); - tb.rollback(); + table.put("id564", "989"); + table.put("id988", "123"); + table.put("id123", "766"); + table.commit(); + table.rollback(); } @Test public void testRollbackSomeChainChanges() { - tb.put("1", "1"); - tb.put("2", "2"); - tb.put("3", "3"); - tb.commit(); - tb.put("4", "4"); - tb.put("54", "54"); - tb.commit(); - assertEquals(2, tb.rollback()); + 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 { - tb.put("1", "11"); - tb.put("2", "22"); - tb.put("3", "33"); - tb.commit(); - assertEquals("11", tb.get("1")); - assertEquals("22", tb.get("2")); - assertEquals("33", tb.get("3")); - tb.put("4", "44"); - tb.put("5", "55"); - tb.commit(); - assertEquals("44", tb.get("4")); - assertEquals("55", tb.get("5")); - tb.rollback(); - assertEquals(null, tb.get("4")); - assertEquals(null, tb.get("5")); - assertEquals("33", tb.get("3")); - assertEquals(3, tb.size()); + 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 { - tb.put("1", "11"); - tb.put("2", "22"); - tb.put("3", "33"); - tb.commit(); - assertEquals("11", tb.get("1")); - assertEquals("22", tb.get("2")); - assertEquals("33", tb.get("3")); - tb.put("4", "44"); - tb.put("5", "55"); - assertEquals("11", tb.remove("1")); - assertEquals("22", tb.remove("2")); - assertEquals(null, tb.remove("66")); - tb.commit(); - tb.rollback(); - assertEquals("11", tb.get("1")); - assertEquals(3, tb.size()); + 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()); } 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 index fe32b21c2..0a60f5e8f 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java @@ -85,8 +85,8 @@ public void testRemoveTableDnExist() { @Test public void testRemoveTableIfExist() { - tp.createTable("test"); - tp.removeTable("test"); - assertNull(tp.getTable("test")); + tp.createTable("testdb"); + tp.removeTable("testdb"); + assertNull(tp.getTable("testdb")); } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/UnknownCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/UnknownCommand.java new file mode 100644 index 000000000..b99e7c859 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/UnknownCommand.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.JUnit; + +/** + * + * @author Андрей + */ +public class UnknownCommand extends Exception { + public UnknownCommand(String description) { + super(description); + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java index e886419d3..d22ab0313 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java @@ -6,6 +6,8 @@ import java.io.IOException; import java.util.Set; import static java.lang.Math.abs; +import java.nio.file.Path; +import java.nio.file.Paths; /** * Класс @class Writer отвечает за физическую запись информации с на жесткий @@ -16,6 +18,8 @@ */ public class Writer { + final int totalSubDir = 16; + final String dirct = ".dir"; boolean checkDir(String name) { File tmpFile = new File(name); @@ -26,23 +30,19 @@ boolean checkDir(String name) { void createDir(String path) { File tmpDir = new File(path); tmpDir.mkdir(); - // System.out.println(path); return; } void createFile(String path) throws IOException { File tmpFile = new File(path); - File prepareToMakeDir = new File(tmpFile.getParent().toString()); prepareToMakeDir.mkdirs(); - // System.out.println(prepareToMakeDir.getAbsolutePath()); tmpFile.createNewFile(); return; } public void deleteDirectory(File dir) { - if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { @@ -56,34 +56,40 @@ public void deleteDirectory(File dir) { } public void write(TableProviderImplements tp) throws IOException { - this.deleteDirectory(new File(tp.dir)); File baseDir = new File(tp.dir); baseDir.mkdir(); if (tp.collection != null) { - for (TableImplement ti : tp.collection) { - File dataBaseDir = new File(tp.dir + "\\" + ti.getName()); + Set dataBase = tp.collection.keySet(); + for (String name : dataBase) { + TableImplement ti = tp.collection.get(name); + Path pathToDb = Paths.get(tp.dir, ti.getName()); + File dataBaseDir = new File(pathToDb.toString()); dataBaseDir.mkdir(); if (ti.getMap() != null) { Set keyList; keyList = ti.getMap().keySet(); for (String keyFind : keyList) { - Integer dirToWrite = new Integer( - abs(keyFind.hashCode() % 16)); - String localPath = tp.dir + "\\" + ti.getName() + "\\" - + dirToWrite.toString() + ".dir"; - if (!this.checkDir(localPath)) { - this.createDir(localPath); + Integer dirToWrite = new Integer(abs(keyFind.hashCode() + % totalSubDir)); + Path localPath = Paths.get(tp.dir, ti.getName(), + dirToWrite.toString() + dirct); + if (!this.checkDir(localPath.toString())) { + this.createDir(localPath.toString()); } - dirToWrite = new Integer(abs(ti.getMap().get(keyFind) - .hashCode() % 16 % 16)); - String localFile = localPath + "\\" - + dirToWrite.toString(); - if (!this.checkDir(localFile)) { - this.createFile(localFile); + dirToWrite = new Integer((ti.getMap().get(keyFind) + .hashCode() + % totalSubDir % totalSubDir)); + 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()); } DataOutputStream outStream = new DataOutputStream( - new FileOutputStream(localFile)); + new FileOutputStream(localFile.toString(), true)); outStream.writeInt(keyFind.length()); outStream.writeChars(keyFind); outStream.writeInt(ti.getMap().get(keyFind).toString() @@ -98,5 +104,4 @@ public void write(TableProviderImplements tp) throws IOException { } return; } - } From e162d7d35082e7e855910fc561bfbfb73632b664 Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Sun, 1 Feb 2015 18:11:13 +0300 Subject: [PATCH 08/18] *proper* --- .../FileMap/JUnit/FactoryImplements.java | 4 +- .../FileMap/JUnit/InteractiveMode.java | 35 +++++++++----- .../AndrewTimokhin/FileMap/JUnit/Reader.java | 39 +++++++-------- .../FileMap/JUnit/TableImplement.java | 48 +++++++++---------- .../JUnit/TableProviderImplements.java | 40 ++++++++-------- .../JUnit/Test/FactoryImplementsTest.java | 7 +-- .../JUnit/Test/TableImplementTest.java | 18 +++++-- .../AndrewTimokhin/FileMap/JUnit/Writer.java | 8 ++-- 8 files changed, 109 insertions(+), 90 deletions(-) diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java index aaac7ac10..dbe780dcf 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java @@ -16,13 +16,13 @@ public class FactoryImplements implements TableProviderFactory { public TableProvider create(String dir) { if (dir == null) { throw new IllegalArgumentException( - "Info: String representing directory is null"); + "String representing directory is null"); } try { return new TableProviderImplements(dir); } catch (IOException xcpt) { throw new RuntimeException( - "Info: Target directory cannot be created or you don't have access to creating files! Try to run as administrator"); + "Target directory cannot be created or you don't have access to creating files! Try to run as administrator"); } } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java index 5bd60cdab..fe7c8b389 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java @@ -13,6 +13,19 @@ * */ public class InteractiveMode { + + static final String CREATE_COMMAND = "create"; + static final String PUT_COMMAND = "put"; + static final String GET_COMMAND = "get"; + static final String REMOVE_COMMAND = "remove"; + static final String DROP_COMMAND = "drop"; + static final String COMMIT_COMMAND = "commit"; + static final String ROLLBACK_COMMAND = "rollback"; + static final String USE_COMMAND = "use"; + static final String SIZE_COMMAND = "size"; + static final String LIST_COMMAND = "list"; + static final String EXIT_COMMAND = "exit"; + private TableImplement table; final TableProviderImplements provider; final FactoryImplements factory; @@ -36,7 +49,7 @@ boolean command(String textToParser) throws UnknownCommand, throw new UnknownCommand( "Current command was not recognized. Programm fail"); switch (commands[0]) { - case "create": + case CREATE_COMMAND: if (commands.length != 2) { this.invitationToRepeat(); break; @@ -46,7 +59,7 @@ boolean command(String textToParser) throws UnknownCommand, else System.out.println("created"); break; - case "put": + case PUT_COMMAND: if (commands.length != 3) { this.invitationToRepeat(); break; @@ -61,7 +74,7 @@ boolean command(String textToParser) throws UnknownCommand, System.out.println("*new*"); break; } - case "get": + case GET_COMMAND: if (commands.length != 2) { this.invitationToRepeat(); break; @@ -76,7 +89,7 @@ boolean command(String textToParser) throws UnknownCommand, System.out.println("*not exist*"); break; } - case "remove": + case REMOVE_COMMAND: if (commands.length != 2) { this.invitationToRepeat(); break; @@ -95,7 +108,7 @@ boolean command(String textToParser) throws UnknownCommand, System.out.println("*not removed, because not exist*"); break; } - case "drop": + case DROP_COMMAND: if (commands.length != 2) { this.invitationToRepeat(); break; @@ -109,7 +122,7 @@ boolean command(String textToParser) throws UnknownCommand, System.out.println(error); } break; - case "commit": + case COMMIT_COMMAND: if (commands.length != 1) { this.invitationToRepeat(); break; @@ -120,7 +133,7 @@ boolean command(String textToParser) throws UnknownCommand, System.out.println("No table"); break; - case "rollback": + case ROLLBACK_COMMAND: if (commands.length != 1) { this.invitationToRepeat(); break; @@ -130,7 +143,7 @@ boolean command(String textToParser) throws UnknownCommand, else System.out.println("No table"); break; - case "use": + case USE_COMMAND: if (commands.length != 2) { this.invitationToRepeat(); break; @@ -145,7 +158,7 @@ boolean command(String textToParser) throws UnknownCommand, System.out.println("Using"); } break; - case "size": + case SIZE_COMMAND: if (commands.length != 1) { this.invitationToRepeat(); break; @@ -159,7 +172,7 @@ boolean command(String textToParser) throws UnknownCommand, System.out.println(totalSize); } break; - case "list": + case LIST_COMMAND: if (commands.length != 1) { this.invitationToRepeat(); break; @@ -173,7 +186,7 @@ boolean command(String textToParser) throws UnknownCommand, } break; } - case "exit": { + case EXIT_COMMAND: { if (table != null) table.commit(); return false; diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java index 0d5ff53a2..8624b4373 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java @@ -8,8 +8,10 @@ import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Vector; @@ -21,15 +23,21 @@ */ public class Reader { - final int totalSubDir = 16; - final String direct = ".dir"; - + static final int TOTAL_SUB_STRING = 16; + static final String DIRECT = ".dir"; + private void readKeyValue(DataInputStream rd, StringBuilder string) throws IOException{ + int length = rd.readInt(); + for (int k = 0; k < length; k++) { + string + .append(rd.readChar()); + } + }; public void read(TableProviderImplements tp) throws IOException { StringBuilder keyBuilder = new StringBuilder(); StringBuilder valueBuilder = new StringBuilder(); int length; - String path = tp.dir; - Vector tables = new Vector(); + String path = tp.getDir(); + List tables = new ArrayList(); boolean dbExist = false; File testDir = new File(path); if (testDir.list() != null) { @@ -38,12 +46,12 @@ public void read(TableProviderImplements tp) throws IOException { File checkDir = new File(pathToFile.toString()); if (checkDir.isDirectory()) { dbExist = true; - TableImplement dataBase = new TableImplement(time, tp.dir); + TableImplement dataBase = new TableImplement(time, tp.getDir()); tables.add(dataBase); - for (int i = 0; i < totalSubDir; i++) { + for (int i = 0; i < TOTAL_SUB_STRING; i++) { Integer numberDir = new Integer(i); Path pathToDb = Paths.get(path, time, - numberDir.toString() + direct); + numberDir.toString() + DIRECT); File locDB = new File(pathToDb.toString()); if (locDB.exists()) { for (String file : locDB.list()) { @@ -54,16 +62,9 @@ public void read(TableProviderImplements tp) throws IOException { pathToLocalDb.toString()))) { while (true) { try { - length = rd.readInt(); - for (int k = 0; k < length; k++) { - keyBuilder - .append(rd.readChar()); - } - length = rd.readInt(); - for (int k = 0; k < length; k++) { - valueBuilder.append(rd - .readChar()); - } + readKeyValue(rd, keyBuilder); + readKeyValue(rd, valueBuilder); + dataBase.getMap().put( keyBuilder.toString(), valueBuilder.toString()); @@ -80,7 +81,7 @@ public void read(TableProviderImplements tp) throws IOException { } } catch (FileNotFoundException fnfe) { throw new RuntimeException( - "Info: Target directory cannot be read! Try to run as administrator"); + "Target directory cannot be read! Try to run as administrator"); } } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java index 1d02056d7..1a81df79a 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java @@ -67,17 +67,14 @@ public String getName() { @Override public int size() { int size = 0; - if (map != null) { size += map.size(); - } - return size; + return size; } @Override - public String get(String key) throws IllegalArgumentException, - KeyNullAndNotFound { + public String get(String key) throws KeyNullAndNotFound { if (key == null) { - throw new KeyNullAndNotFound("Info: Key is null"); + throw new KeyNullAndNotFound("Key is null"); } if (map != null) { if (map.containsKey(key)) { @@ -92,11 +89,11 @@ public String put(String key, String value) throws IllegalArgumentException { String time = null; if (key == null || value == null) { throw new IllegalArgumentException( - "Info: Key or (and) value is wrong."); + "Key or (and) value is wrong."); } if (map != null) { if (map.containsKey(key)) { - time = (String) map.get(key); + time = map.get(key); } } map.put(key, value); @@ -107,13 +104,11 @@ public String put(String key, String value) throws IllegalArgumentException { public String remove(String key) throws IllegalArgumentException { String time = null; if (key == null) { - throw new IllegalArgumentException("Info: Key is wrong."); + throw new IllegalArgumentException("Key is wrong."); } - if (map != null) { // if map is empty, then it is null if (map.containsKey(key)) { time = (String) map.get(key); map.remove(key); - } } return time; } @@ -141,10 +136,8 @@ public int totalChanges() { if (backup != null && map != null) { Set backupKey = backup.keySet(); for (String timeKey : backupKey) { - if (map.containsKey(timeKey) - && !(backup.get(timeKey).equals(map.get(timeKey)))) { - counter++; - } else if (!map.containsKey(timeKey)) { + if ((map.containsKey(timeKey) + && !(backup.get(timeKey).equals(map.get(timeKey)))) || !map.containsKey(timeKey)) { counter++; } } @@ -163,17 +156,17 @@ public int commit() { try { return this.writeToDisk(); } catch (IOException ioexcptn) { - throw new RuntimeException("Cannot write to the File System"); + throw new RuntimeException(new IOException("Cannot write to the File System")); } } public int writeToDisk() throws IOException { boolean flagIfBaseExist = false; - Reader rd = new Reader(); - FactoryImplements tb = new FactoryImplements(); - TableProviderImplements tableProvider = (TableProviderImplements) tb + Reader reader = new Reader(); + FactoryImplements factory = new FactoryImplements(); + TableProviderImplements tableProvider = (TableProviderImplements) factory .create(path); - rd.read(tableProvider); + reader.read(tableProvider); Writer writer = new Writer(); if (tableProvider.collection != null) { { @@ -182,11 +175,11 @@ public int writeToDisk() throws IOException { Map tmp = new HashMap<>(); Set copy = tableProvider.collection.get(name).map .keySet(); - for (String time : copy) { - tmp.put(new String(time), + for (String copyString : copy) { + tmp.put(new String(copyString), new String( (String) tableProvider.collection - .get(name).map.get(time))); + .get(name).map.get(copyString))); } this.backup = new HashMap(tmp); } @@ -207,10 +200,13 @@ public int writeToDisk() throws IOException { } @Override - public int rollback() { - Map time = new HashMap(this.map); + public int rollback() throws NullPointerException{ + Map copyMap = new HashMap(this.map); + if (this.backup!= null) this.map = new HashMap(this.backup); - this.backup = time; + else + this.map = new HashMap(); + this.backup = copyMap; return this.commit(); } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java index 86fa7e1ec..39d758f28 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java @@ -14,20 +14,9 @@ public class TableProviderImplements implements TableProvider { - public static void deleteDir(File dir) { - if (dir.isDirectory()) { - String[] children = dir.list(); - for (int i = 0; i < children.length; i++) { - File f = new File(dir, children[i]); - deleteDir(f); - } - dir.delete(); - } else - dir.delete(); - } - - protected Map collection; - public final String dir; + + public Map collection; + private final String dir; TableProviderImplements(String dir) throws IOException { this.dir = dir; @@ -36,6 +25,18 @@ public static void deleteDir(File dir) { rd.read(this); } + public static void deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + for (String childName : children) { + File f = new File(dir, childName); + deleteDir(f); + } + dir.delete(); + } else + dir.delete(); + } + public void write() throws IOException { Writer writeToFileSystem = new Writer(); writeToFileSystem.write(this); @@ -45,12 +46,10 @@ public void write() throws IOException { public Table getTable(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException( - "Info: Name of DataBase is null. Please, enter correct name"); + "Name of DataBase is null. Please, enter correct name"); } - if (collection != null) { // if database is created now if (collection.containsKey(name)) return collection.get(name); - } return null; } @@ -58,7 +57,7 @@ public Table getTable(String name) throws IllegalArgumentException { public Table createTable(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException( - "Info: Name of DataBase is null. Please, enter correct name"); + "Name of DataBase is null. Please, enter correct name"); } if (collection != null) { if (collection.containsKey(name)) @@ -81,7 +80,7 @@ public void removeTable(String name) throws IllegalArgumentException, IllegalStateException { if (name == null) { throw new IllegalArgumentException( - "Info: Name of DataBase is null. Please, enter correct name"); + "Name of DataBase is null. Please, enter correct name"); } if (collection != null) { if (collection.containsKey(name)) { @@ -96,4 +95,7 @@ public void removeTable(String name) throws IllegalArgumentException, } throw new IllegalStateException("Requested database don't exist"); } + public String getDir() { + return dir; + } } 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 index 3c56d61ae..9b87330fa 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java @@ -11,17 +11,12 @@ * @author Timokhin Andrew */ public class FactoryImplementsTest { - private final Map agregaret = new HashMap(); - - /** - * @throws java.io.IOException - */ @Test public void testCreate() throws IOException { TableProviderImplements resultOne = (TableProviderImplements) new FactoryImplements() .create("test"); - assertEquals("test", resultOne.dir); + assertEquals("test", resultOne.getDir()); } @Test(expected = IllegalArgumentException.class) 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 index f7646a9d7..563f223f0 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java @@ -31,9 +31,9 @@ public class TableImplementTest { @Before public void setUp() { - TableProviderFactory tpv = new FactoryImplements(); + TableProviderFactory tableProviderFactory = new FactoryImplements(); path = tmp.newFolder("time").getAbsolutePath(); - tableProvider = tpv.create(path); + tableProvider = tableProviderFactory.create(path); table = tableProvider.createTable("testing"); FactoryImplements factory = new FactoryImplements(); @@ -184,13 +184,14 @@ public void testRollbackIfStateEmpty() { assertEquals(0, table.rollback()); } - @Test(expected = NullPointerException.class) + @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 @@ -248,4 +249,15 @@ public void testCommitCheckChangesRollbackCheck() throws IllegalArgumentExceptio } + + + @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/Writer.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java index d22ab0313..6727f0d36 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java @@ -56,14 +56,14 @@ public void deleteDirectory(File dir) { } public void write(TableProviderImplements tp) throws IOException { - this.deleteDirectory(new File(tp.dir)); - File baseDir = new File(tp.dir); + this.deleteDirectory(new File(tp.getDir())); + File baseDir = new File(tp.getDir()); baseDir.mkdir(); if (tp.collection != null) { Set dataBase = tp.collection.keySet(); for (String name : dataBase) { TableImplement ti = tp.collection.get(name); - Path pathToDb = Paths.get(tp.dir, ti.getName()); + Path pathToDb = Paths.get(tp.getDir(), ti.getName()); File dataBaseDir = new File(pathToDb.toString()); dataBaseDir.mkdir(); if (ti.getMap() != null) { @@ -72,7 +72,7 @@ public void write(TableProviderImplements tp) throws IOException { for (String keyFind : keyList) { Integer dirToWrite = new Integer(abs(keyFind.hashCode() % totalSubDir)); - Path localPath = Paths.get(tp.dir, ti.getName(), + Path localPath = Paths.get(tp.getDir(), ti.getName(), dirToWrite.toString() + dirct); if (!this.checkDir(localPath.toString())) { this.createDir(localPath.toString()); From b615130640fdead244b654a260c59be771a8ed75 Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Mon, 2 Feb 2015 15:31:28 +0300 Subject: [PATCH 09/18] *newwithpack* --- .../FileMap/JUnit/Commands/Commands.java | 24 +++ .../FileMap/JUnit/Commands/CommitCommand.java | 27 +++ .../FileMap/JUnit/Commands/CreateCommand.java | 27 +++ .../FileMap/JUnit/Commands/DropCommand.java | 31 ++++ .../FileMap/JUnit/Commands/ExitCommand.java | 22 +++ .../FileMap/JUnit/Commands/GetCommand.java | 41 +++++ .../FileMap/JUnit/Commands/ListCommand.java | 39 +++++ .../FileMap/JUnit/Commands/PutCommand.java | 33 ++++ .../FileMap/JUnit/Commands/RemoveCommand.java | 35 ++++ .../JUnit/Commands/RollbackCommand.java | 27 +++ .../FileMap/JUnit/Commands/SizeCommand.java | 32 ++++ .../FileMap/JUnit/Commands/UseCommand.java | 33 ++++ .../FileMap/JUnit/FactoryImplements.java | 5 +- .../FileMap/JUnit/InteractiveMode.java | 160 +++--------------- .../AndrewTimokhin/FileMap/JUnit/Reader.java | 30 ++-- .../FileMap/JUnit/TableImplement.java | 24 ++- .../JUnit/TableProviderImplements.java | 18 +- 17 files changed, 437 insertions(+), 171 deletions(-) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CommitCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CreateCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/DropCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/GetCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ListCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/PutCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RemoveCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RollbackCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/UseCommand.java diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java new file mode 100644 index 000000000..e2382f78c --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java @@ -0,0 +1,24 @@ +/* + * 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.Commands; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class Commands { + static TableImplement currentTable; + static public boolean execute(String[] command, TableProviderImplements table) { + return false; //be-default + }; + static void invitationToRepeat() { + System.out + .println("Current command was not recognized or not complete. Please, try again"); + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CommitCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CommitCommand.java new file mode 100644 index 000000000..53036e610 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CommitCommand.java @@ -0,0 +1,27 @@ +/* + * 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.Commands; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class CommitCommand extends Commands{ + + static public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 1) { + Commands.invitationToRepeat(); + return true; + } + if (currentTable != null) + System.out.println("Total changes -> " + currentTable.commit()); + else + System.out.println("No table"); + return true; +} +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CreateCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CreateCommand.java new file mode 100644 index 000000000..b8b33391b --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CreateCommand.java @@ -0,0 +1,27 @@ +/* + * 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.Commands; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class CreateCommand extends Commands{ + + static public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 2) { + Commands.invitationToRepeat(); + return true; + } + if (tableProvider.createTable(commands[1]) == null) + System.out.println("Exist!"); + else + System.out.println("created"); + return true; + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/DropCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/DropCommand.java new file mode 100644 index 000000000..8cab7e9e3 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/DropCommand.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.Commands; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class DropCommand extends Commands{ + + static public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 2) { + Commands.invitationToRepeat(); + return true; + } + try { + tableProvider.removeTable(commands[1]); + System.out.println("dropped"); + } catch (IllegalStateException error) { + System.out.println("Not exists"); + } catch (IllegalArgumentException error) { + System.out.println(error); + } + return true; +} +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java new file mode 100644 index 000000000..d033d7f80 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java @@ -0,0 +1,22 @@ +/* + * 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.Commands; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class ExitCommand extends Commands{ + + static public boolean execute(String[] commands, TableProviderImplements tableProvider) { + + if (currentTable != null) + currentTable.commit(); + return false; +} +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/GetCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/GetCommand.java new file mode 100644 index 000000000..e1a132aee --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/GetCommand.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.Commands; + +import java.util.logging.Level; +import java.util.logging.Logger; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.KeyNullAndNotFound; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class GetCommand extends Commands{ + + static public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 2) { + Commands.invitationToRepeat(); + return true; + } else if (currentTable == null) { + System.out.println("No table"); + return true; + } 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 true; + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ListCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ListCommand.java new file mode 100644 index 000000000..ede098211 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ListCommand.java @@ -0,0 +1,39 @@ +/* + * 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.Commands; + +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.KeyNullAndNotFound; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class ListCommand extends Commands{ + + static public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 1) { + Commands.invitationToRepeat(); + return true; + } else if (currentTable == null) { + System.out.println("No table"); + return true; + } else { + Set set = currentTable.getMap().keySet(); + for (String key : set) { + try { + System.out.println(key + " " + currentTable.get(key)); + } catch (KeyNullAndNotFound ex) { + System.out.println("Null key is wrong!"); + } + } +} + return true; + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/PutCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/PutCommand.java new file mode 100644 index 000000000..6f3b5f2b8 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/PutCommand.java @@ -0,0 +1,33 @@ +/* + * 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.Commands; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class PutCommand extends Commands{ + +static public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 3) { + Commands.invitationToRepeat(); + return true; + } else if (currentTable == null) { + System.out.println("No table"); + return true; + } else { + String oldValue = currentTable.put(commands[1], commands[2]); + if (oldValue != null) + System.out.println("*old* -> " + oldValue); + else + System.out.println("*new*"); + } + return true; + } +} + diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RemoveCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RemoveCommand.java new file mode 100644 index 000000000..10f3323cc --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RemoveCommand.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.Commands; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class RemoveCommand extends Commands{ + + static public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 2) { + Commands.invitationToRepeat(); + return true; + } else if (currentTable == null) { + System.out.println("No table"); + return true; + } else { + if (commands[1] == null) { + System.out.println("*wrong key"); + return true; + } + String value = currentTable.remove(commands[1]); + if (value != null) + System.out.println("*value* -> " + value); + else + System.out.println("*not removed, because not exist*"); +} return true; + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RollbackCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RollbackCommand.java new file mode 100644 index 000000000..10204bcad --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RollbackCommand.java @@ -0,0 +1,27 @@ +/* + * 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.Commands; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class RollbackCommand extends Commands{ + + static public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 1) { + Commands.invitationToRepeat(); + return true; + } + if (currentTable != null) + System.out.println("Total changes -> " + currentTable .rollback()); + else + System.out.println("No table"); + return true; +} +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java new file mode 100644 index 000000000..47c394510 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java @@ -0,0 +1,32 @@ +/* + * 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.Commands; + +import java.util.Set; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class SizeCommand extends Commands{ + + static public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 1) { + Commands.invitationToRepeat(); + return true; + } + { + int totalSize = 0; + Set set = tableProvider.collection.keySet(); + for (String key : set) { + totalSize += tableProvider.collection.get(key).size(); + } + System.out.println(totalSize); + } + return true; +} +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/UseCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/UseCommand.java new file mode 100644 index 000000000..748056360 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/UseCommand.java @@ -0,0 +1,33 @@ +/* + * 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.Commands; + +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableImplement; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class UseCommand extends Commands{ + + public static boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 2) { + Commands.invitationToRepeat(); + return true; + } + currentTable = (TableImplement) tableProvider.getTable(commands[1]); + if (currentTable == null) + System.out.println("Not exists"); + else { + if (currentTable.totalChanges() > 0) + System.out.println("Need commit->"); + else + System.out.println("Using"); + } + return false; + } +} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java index dbe780dcf..734017632 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java @@ -20,9 +20,8 @@ public TableProvider create(String dir) { } try { return new TableProviderImplements(dir); - } catch (IOException xcpt) { - throw new RuntimeException( - "Target directory cannot be created or you don't have access to creating files! Try to run as administrator"); + } catch (IOException exception) { + throw new RuntimeException(exception); } } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java index fe7c8b389..f4cef0050 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java @@ -6,6 +6,17 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; import java.util.Set; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.CommitCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.CreateCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.DropCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.ExitCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.GetCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.ListCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.PutCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.RemoveCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.RollbackCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.SizeCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.UseCommand; /** * @@ -27,19 +38,13 @@ public class InteractiveMode { static final String EXIT_COMMAND = "exit"; private TableImplement table; - final TableProviderImplements provider; - final FactoryImplements factory; - String currentDir; + final private TableProviderImplements provider; + final private FactoryImplements factory; + private String currentDir; InteractiveMode(String path) { factory = new FactoryImplements(); provider = (TableProviderImplements) factory.create(path); - currentDir = null; - } - - private void invitationToRepeat() { - System.out - .println("Current command was not recognized or not complete. Please, try again"); } boolean command(String textToParser) throws UnknownCommand, @@ -50,149 +55,40 @@ boolean command(String textToParser) throws UnknownCommand, "Current command was not recognized. Programm fail"); switch (commands[0]) { case CREATE_COMMAND: - if (commands.length != 2) { - this.invitationToRepeat(); - break; - } - if (provider.createTable(commands[1]) == null) - System.out.println("Exist!"); - else - System.out.println("created"); + CreateCommand.execute(commands, provider) ; break; case PUT_COMMAND: - if (commands.length != 3) { - this.invitationToRepeat(); - break; - } else if (table == null) { - System.out.println("No table"); - break; - } else { - String oldValue = table.put(commands[1], commands[2]); - if (oldValue != null) - System.out.println("*old* -> " + oldValue); - else - System.out.println("*new*"); + PutCommand.execute(commands, provider); break; - } case GET_COMMAND: - if (commands.length != 2) { - this.invitationToRepeat(); + GetCommand.execute(commands, provider); break; - } else if (table == null) { - System.out.println("No table"); - break; - } else { - String value = table.get(commands[1]); - if (value != null) - System.out.println("*value* -> " + value); - else - System.out.println("*not exist*"); - break; - } case REMOVE_COMMAND: - if (commands.length != 2) { - this.invitationToRepeat(); - break; - } else if (table == null) { - System.out.println("No table"); - break; - } else { - if (commands[1] == null) { - System.out.println("*wrong key"); - break; - } - String value = table.remove(commands[1]); - if (value != null) - System.out.println("*value* -> " + value); - else - System.out.println("*not removed, because not exist*"); + RemoveCommand.execute(commands, provider); break; - } case DROP_COMMAND: - if (commands.length != 2) { - this.invitationToRepeat(); - break; - } - try { - provider.removeTable(commands[1]); - System.out.println("dropped"); - } catch (IllegalStateException error) { - System.out.println("Not exists"); - } catch (IllegalArgumentException error) { - System.out.println(error); - } + DropCommand.execute(commands, provider); break; case COMMIT_COMMAND: - if (commands.length != 1) { - this.invitationToRepeat(); - break; - } - if (table != null) - System.out.println("Total changes -> " + table.commit()); - else - System.out.println("No table"); + CommitCommand.execute(commands, provider); break; - - case ROLLBACK_COMMAND: - if (commands.length != 1) { - this.invitationToRepeat(); - break; - } - if (table != null) - System.out.println("Total changes -> " + table.rollback()); - else - System.out.println("No table"); + case ROLLBACK_COMMAND: + RollbackCommand.execute(commands, provider); break; case USE_COMMAND: - if (commands.length != 2) { - this.invitationToRepeat(); - break; - } - table = (TableImplement) provider.getTable(commands[1]); - if (table == null) - System.out.println("Not exists"); - else { - if (table.totalChanges() > 0) - System.out.println("Need commit->"); - else - System.out.println("Using"); - } + UseCommand.execute(commands, provider); break; case SIZE_COMMAND: - if (commands.length != 1) { - this.invitationToRepeat(); - break; - } - { - int totalSize = 0; - Set set = provider.collection.keySet(); - for (String key : set) { - totalSize += provider.collection.get(key).size(); - } - System.out.println(totalSize); - } + SizeCommand.execute(commands, provider); break; case LIST_COMMAND: - if (commands.length != 1) { - this.invitationToRepeat(); - break; - } else if (table == null) { - System.out.println("No table"); + ListCommand.execute(commands, provider); break; - } else { - Set set = table.getMap().keySet(); - for (String key : set) { - System.out.println(key + " " + table.get(key)); - } - break; - } case EXIT_COMMAND: { - if (table != null) - table.commit(); - return false; - } + return ExitCommand.execute(commands, provider); + } default: - this.invitationToRepeat(); + System.out.println("Wrong command!"); break; } return true; diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java index 8624b4373..500072664 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java @@ -10,10 +10,8 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Vector; /** * Класс @class Reader отвечает за физическое чтение данных из файловой системы. @@ -25,13 +23,19 @@ public class Reader { static final int TOTAL_SUB_STRING = 16; static final String DIRECT = ".dir"; - private void readKeyValue(DataInputStream rd, StringBuilder string) throws IOException{ - int length = rd.readInt(); - for (int k = 0; k < length; k++) { - string - .append(rd.readChar()); - } - }; + private String directory; + + public Reader(String directory) { + this.directory = directory; + } + + private void readKeyValue(DataInputStream rd, StringBuilder string) throws IOException { + int length = rd.readInt(); + for (int k = 0; k < length; k++) { + string + .append(rd.readChar()); + } +} public void read(TableProviderImplements tp) throws IOException { StringBuilder keyBuilder = new StringBuilder(); StringBuilder valueBuilder = new StringBuilder(); @@ -79,9 +83,9 @@ public void read(TableProviderImplements tp) throws IOException { break; } } - } catch (FileNotFoundException fnfe) { + } catch (FileNotFoundException exceptionFileNotFound) { throw new RuntimeException( - "Target directory cannot be read! Try to run as administrator"); + exceptionFileNotFound); } } } @@ -90,13 +94,13 @@ public void read(TableProviderImplements tp) throws IOException { } } if (!dbExist) { - return; + return ; } Map copy = new HashMap<>(); for (TableImplement table : tables) { copy.put(table.getName(), table); } tp.collection = copy; - return; + return ; } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java index 1a81df79a..e821d5ed7 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java @@ -66,9 +66,7 @@ public String getName() { @Override public int size() { - int size = 0; - size += map.size(); - return size; + return map.size(); } @Override @@ -86,29 +84,29 @@ public String get(String key) throws KeyNullAndNotFound { @Override public String put(String key, String value) throws IllegalArgumentException { - String time = null; + String previousValue = null; if (key == null || value == null) { throw new IllegalArgumentException( "Key or (and) value is wrong."); } if (map != null) { if (map.containsKey(key)) { - time = map.get(key); + previousValue = map.get(key); } } map.put(key, value); - return time; + return previousValue; } @Override public String remove(String key) throws IllegalArgumentException { String time = null; if (key == null) { - throw new IllegalArgumentException("Key is wrong."); + throw new IllegalArgumentException("Key shouldn't be null"); } - if (map.containsKey(key)) { - time = (String) map.get(key); - map.remove(key); + if (map.containsKey(key)) { + time = map.get(key); + map.remove(key); } return time; } @@ -119,7 +117,7 @@ public List list() { if (map != null) { return new ArrayList(map.keySet()); } - return new ArrayList(); // if map is empty + return new ArrayList(); } public int totalChanges() { @@ -156,13 +154,13 @@ public int commit() { try { return this.writeToDisk(); } catch (IOException ioexcptn) { - throw new RuntimeException(new IOException("Cannot write to the File System")); + throw new RuntimeException(ioexcptn); } } public int writeToDisk() throws IOException { boolean flagIfBaseExist = false; - Reader reader = new Reader(); + Reader reader = new Reader(this.path); FactoryImplements factory = new FactoryImplements(); TableProviderImplements tableProvider = (TableProviderImplements) factory .create(path); diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java index 39d758f28..b63108d5a 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java @@ -20,8 +20,8 @@ public class TableProviderImplements implements TableProvider { TableProviderImplements(String dir) throws IOException { this.dir = dir; - collection = new HashMap<>(); - Reader rd = new Reader(); + collection = new HashMap(); + Reader rd = new Reader(new String(this.dir)); rd.read(this); } @@ -29,8 +29,7 @@ public static void deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (String childName : children) { - File f = new File(dir, childName); - deleteDir(f); + deleteDir(new File(dir, childName)); } dir.delete(); } else @@ -46,10 +45,10 @@ public void write() throws IOException { public Table getTable(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException( - "Name of DataBase is null. Please, enter correct name"); + "Name of DataBase is null"); } - if (collection.containsKey(name)) - return collection.get(name); + if (collection.containsKey(name)) { + return collection.get(name); } return null; } @@ -62,10 +61,8 @@ public Table createTable(String name) throws IllegalArgumentException { if (collection != null) { if (collection.containsKey(name)) return null; - { - collection.put(name, new TableImplement(name, dir)); + collection.put(name, new TableImplement(name, dir)); return collection.get(name); - } } if (collection == null) { collection = new HashMap<>(); @@ -95,6 +92,7 @@ public void removeTable(String name) throws IllegalArgumentException, } throw new IllegalStateException("Requested database don't exist"); } + public String getDir() { return dir; } From f412af55ef95be964a01f56dd95fe2b9c7693e78 Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Mon, 2 Feb 2015 22:33:54 +0300 Subject: [PATCH 10/18] *newv* --- .../FileMap/JUnit/Commands/Commands.java | 12 +- .../FileMap/JUnit/Commands/CommitCommand.java | 25 +++-- .../FileMap/JUnit/Commands/CreateCommand.java | 21 ++-- .../FileMap/JUnit/Commands/DropCommand.java | 32 +++--- .../FileMap/JUnit/Commands/ExitCommand.java | 13 +-- .../FileMap/JUnit/Commands/GetCommand.java | 32 +++--- .../FileMap/JUnit/Commands/ListCommand.java | 43 ++++--- .../FileMap/JUnit/Commands/PutCommand.java | 36 +++--- .../FileMap/JUnit/Commands/RemoveCommand.java | 40 +++---- .../JUnit/Commands/RollbackCommand.java | 25 +++-- .../FileMap/JUnit/Commands/SizeCommand.java | 27 ++--- .../FileMap/JUnit/Commands/UseCommand.java | 33 +++--- .../FileMap/JUnit/FactoryImplements.java | 1 - .../FileMap/JUnit/InteractiveMode.java | 75 +++++++------ .../AndrewTimokhin/FileMap/JUnit/JUnit.java | 5 +- .../FileMap/JUnit/KeyNullAndNotFound.java | 1 + .../AndrewTimokhin/FileMap/JUnit/Reader.java | 81 ++++++------- .../AndrewTimokhin/FileMap/JUnit/Table.java | 26 ++--- .../FileMap/JUnit/TableImplement.java | 106 +++++++++++------- .../FileMap/JUnit/TableProvider.java | 29 +++-- .../FileMap/JUnit/TableProviderFactory.java | 8 +- .../JUnit/TableProviderImplements.java | 42 ++++--- .../JUnit/Test/TableImplementTest.java | 12 +- .../Test/TableProviderImplementsTest.java | 3 +- .../FileMap/JUnit/UnknownCommand.java | 1 + .../AndrewTimokhin/FileMap/JUnit/Writer.java | 34 +++--- 26 files changed, 395 insertions(+), 368 deletions(-) diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java index e2382f78c..38d603028 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java @@ -13,10 +13,14 @@ * @author Андрей */ public class Commands { - static TableImplement currentTable; - static public boolean execute(String[] command, TableProviderImplements table) { - return false; //be-default - }; + + static TableImplement currentTable; + + static public void execute(String[] command, TableProviderImplements table) { + return; //be-default + } + + ; static void invitationToRepeat() { System.out .println("Current command was not recognized or not complete. Please, try again"); diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CommitCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CommitCommand.java index 53036e610..8137c648d 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CommitCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CommitCommand.java @@ -11,17 +11,18 @@ * * @author Андрей */ -public class CommitCommand extends Commands{ +public class CommitCommand extends Commands { - static public boolean execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 1) { - Commands.invitationToRepeat(); - return true; - } - if (currentTable != null) - System.out.println("Total changes -> " + currentTable.commit()); - else - System.out.println("No table"); - return true; + static public void execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 1) { + Commands.invitationToRepeat(); + return; + } + if (currentTable != null) { + System.out.println("Total changes -> " + currentTable.commit()); + } else { + System.out.println("No table"); + } + return; + } } -} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CreateCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CreateCommand.java index b8b33391b..cfb511f2f 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CreateCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CreateCommand.java @@ -11,17 +11,18 @@ * * @author Андрей */ -public class CreateCommand extends Commands{ +public class CreateCommand extends Commands { - static public boolean execute(String[] commands, TableProviderImplements tableProvider) { + static public void execute(String[] commands, TableProviderImplements tableProvider) { if (commands.length != 2) { - Commands.invitationToRepeat(); - return true; - } - if (tableProvider.createTable(commands[1]) == null) - System.out.println("Exist!"); - else - System.out.println("created"); - return true; + Commands.invitationToRepeat(); + return; + } + if (tableProvider.createTable(commands[1]) == null) { + System.out.println("Exist!"); + } else { + System.out.println("created"); + } + return; } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/DropCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/DropCommand.java index 8cab7e9e3..c1615241d 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/DropCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/DropCommand.java @@ -11,21 +11,21 @@ * * @author Андрей */ -public class DropCommand extends Commands{ +public class DropCommand extends Commands { - static public boolean execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 2) { - Commands.invitationToRepeat(); - return true; - } - try { - tableProvider.removeTable(commands[1]); - System.out.println("dropped"); - } catch (IllegalStateException error) { - System.out.println("Not exists"); - } catch (IllegalArgumentException error) { - System.out.println(error); - } - return true; + static public void execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 2) { + Commands.invitationToRepeat(); + return; + } + try { + tableProvider.removeTable(commands[1]); + System.out.println("dropped"); + } catch (IllegalStateException error) { + System.out.println("Not exists"); + } catch (IllegalArgumentException error) { + System.out.println(error); + } + return; + } } -} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java index d033d7f80..2c4fabf48 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java @@ -11,12 +11,9 @@ * * @author Андрей */ -public class ExitCommand extends Commands{ - - static public boolean execute(String[] commands, TableProviderImplements tableProvider) { - - if (currentTable != null) - currentTable.commit(); - return false; +public class ExitCommand extends Commands { + + static public void execute(String[] commands, TableProviderImplements tableProvider) { + return; + } } -} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/GetCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/GetCommand.java index e1a132aee..eaae4f19d 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/GetCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/GetCommand.java @@ -5,7 +5,6 @@ */ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands; -import java.util.logging.Level; import java.util.logging.Logger; import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.KeyNullAndNotFound; import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; @@ -14,28 +13,29 @@ * * @author Андрей */ -public class GetCommand extends Commands{ - - static public boolean execute(String[] commands, TableProviderImplements tableProvider) { +public class GetCommand extends Commands { + + static public void execute(String[] commands, TableProviderImplements tableProvider) { if (commands.length != 2) { - Commands.invitationToRepeat(); - return true; - } else if (currentTable == null) { - System.out.println("No table"); - return true; - } else { - String value; + Commands.invitationToRepeat(); + return; + } else if (currentTable == null) { + System.out.println("No table"); + return; + } else { + String value; try { value = currentTable.get(commands[1]); - if (value != null) + if (value != null) { System.out.println("*value* -> " + value); - else + } else { System.out.println("*not exist*"); + } } catch (KeyNullAndNotFound ex) { System.out.println("Key is Null. Enter correct key"); } - + + } + return; } - return true; - } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ListCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ListCommand.java index ede098211..b593e7f63 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ListCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ListCommand.java @@ -5,9 +5,7 @@ */ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; +import java.util.ArrayList; import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.KeyNullAndNotFound; import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; @@ -15,25 +13,26 @@ * * @author Андрей */ -public class ListCommand extends Commands{ - - static public boolean execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 1) { - Commands.invitationToRepeat(); - return true; - } else if (currentTable == null) { - System.out.println("No table"); - return true; - } else { - Set set = currentTable.getMap().keySet(); - for (String key : set) { - try { - System.out.println(key + " " + currentTable.get(key)); - } catch (KeyNullAndNotFound ex) { - System.out.println("Null key is wrong!"); - } +public class ListCommand extends Commands { + + static public void execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 1) { + Commands.invitationToRepeat(); + return; + } else if (currentTable == null) { + System.out.println("No table"); + return; + } 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 true; + } + } + return; } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/PutCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/PutCommand.java index 6f3b5f2b8..89de343b9 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/PutCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/PutCommand.java @@ -11,23 +11,23 @@ * * @author Андрей */ -public class PutCommand extends Commands{ - -static public boolean execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 3) { - Commands.invitationToRepeat(); - return true; - } else if (currentTable == null) { - System.out.println("No table"); - return true; +public class PutCommand extends Commands { + + static public void execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 3) { + Commands.invitationToRepeat(); + return; + } else if (currentTable == null) { + System.out.println("No table"); + return; + } else { + String oldValue = currentTable.put(commands[1], commands[2]); + if (oldValue != null) { + System.out.println("*old* -> " + oldValue); } else { - String oldValue = currentTable.put(commands[1], commands[2]); - if (oldValue != null) - System.out.println("*old* -> " + oldValue); - else - System.out.println("*new*"); + System.out.println("*new*"); } - return true; - } -} - + } + return; + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RemoveCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RemoveCommand.java index 10f3323cc..7f764d08a 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RemoveCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RemoveCommand.java @@ -11,25 +11,27 @@ * * @author Андрей */ -public class RemoveCommand extends Commands{ +public class RemoveCommand extends Commands { - static public boolean execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 2) { - Commands.invitationToRepeat(); - return true; - } else if (currentTable == null) { - System.out.println("No table"); - return true; + static public void execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 2) { + Commands.invitationToRepeat(); + return; + } else if (currentTable == null) { + System.out.println("No table"); + return; + } else { + if (commands[1] == null) { + System.out.println("*wrong key"); + return; + } + String value = currentTable.remove(commands[1]); + if (value != null) { + System.out.println("*value* -> " + value); } else { - if (commands[1] == null) { - System.out.println("*wrong key"); - return true; - } - String value = currentTable.remove(commands[1]); - if (value != null) - System.out.println("*value* -> " + value); - else - System.out.println("*not removed, because not exist*"); -} return true; + System.out.println("*not removed, because not exist*"); + } + } + return; } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RollbackCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RollbackCommand.java index 10204bcad..24877b631 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RollbackCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RollbackCommand.java @@ -11,17 +11,18 @@ * * @author Андрей */ -public class RollbackCommand extends Commands{ +public class RollbackCommand extends Commands { - static public boolean execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 1) { - Commands.invitationToRepeat(); - return true; - } - if (currentTable != null) - System.out.println("Total changes -> " + currentTable .rollback()); - else - System.out.println("No table"); - return true; + static public void execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 1) { + Commands.invitationToRepeat(); + return; + } + if (currentTable != null) { + System.out.println("Total changes -> " + currentTable.rollback()); + } else { + System.out.println("No table"); + } + return; + } } -} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java index 47c394510..c507b5e42 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java @@ -12,21 +12,16 @@ * * @author Андрей */ -public class SizeCommand extends Commands{ +public class SizeCommand extends Commands { - static public boolean execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 1) { - Commands.invitationToRepeat(); - return true; - } - { - int totalSize = 0; - Set set = tableProvider.collection.keySet(); - for (String key : set) { - totalSize += tableProvider.collection.get(key).size(); - } - System.out.println(totalSize); - } - return true; -} + static public void execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 1) { + Commands.invitationToRepeat(); + return; + } + { + System.out.println(tableProvider.size()); + } + return; + } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/UseCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/UseCommand.java index 748056360..268bc12fa 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/UseCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/UseCommand.java @@ -12,22 +12,23 @@ * * @author Андрей */ -public class UseCommand extends Commands{ +public class UseCommand extends Commands { - public static boolean execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 2) { - Commands.invitationToRepeat(); - return true; + public static void execute(String[] commands, TableProviderImplements tableProvider) { + if (commands.length != 2) { + Commands.invitationToRepeat(); + return; + } + 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"); } - currentTable = (TableImplement) tableProvider.getTable(commands[1]); - if (currentTable == null) - System.out.println("Not exists"); - else { - if (currentTable.totalChanges() > 0) - System.out.println("Need commit->"); - else - System.out.println("Using"); + } + return; } - return false; - } -} \ No newline at end of file +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java index 734017632..9e569d792 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java @@ -9,7 +9,6 @@ * * @author Timokhin Andrew */ - public class FactoryImplements implements TableProviderFactory { @Override diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java index f4cef0050..58b77a4e6 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java @@ -5,7 +5,6 @@ */ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; -import java.util.Set; import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.CommitCommand; import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.CreateCommand; import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.DropCommand; @@ -21,10 +20,10 @@ /** * * @author Timokhin Andrew - * + * */ public class InteractiveMode { - + static final String CREATE_COMMAND = "create"; static final String PUT_COMMAND = "put"; static final String GET_COMMAND = "get"; @@ -36,7 +35,7 @@ public class InteractiveMode { static final String SIZE_COMMAND = "size"; static final String LIST_COMMAND = "list"; static final String EXIT_COMMAND = "exit"; - + private TableImplement table; final private TableProviderImplements provider; final private FactoryImplements factory; @@ -50,46 +49,48 @@ public class InteractiveMode { boolean command(String textToParser) throws UnknownCommand, IllegalArgumentException, KeyNullAndNotFound { String[] commands = textToParser.trim().split(" "); - if (commands.length < 1) + if (commands.length < 1) { throw new UnknownCommand( "Current command was not recognized. Programm fail"); + } switch (commands[0]) { - case CREATE_COMMAND: - CreateCommand.execute(commands, provider) ; - break; - case PUT_COMMAND: - PutCommand.execute(commands, provider); + case CREATE_COMMAND: + CreateCommand.execute(commands, provider); + break; + case PUT_COMMAND: + PutCommand.execute(commands, provider); + break; + case GET_COMMAND: + GetCommand.execute(commands, provider); + break; + case REMOVE_COMMAND: + RemoveCommand.execute(commands, provider); + break; + case DROP_COMMAND: + DropCommand.execute(commands, provider); + break; + case COMMIT_COMMAND: + CommitCommand.execute(commands, provider); + break; + case ROLLBACK_COMMAND: + RollbackCommand.execute(commands, provider); + break; + case USE_COMMAND: + UseCommand.execute(commands, provider); break; - case GET_COMMAND: - GetCommand.execute(commands, provider); + case SIZE_COMMAND: + SizeCommand.execute(commands, provider); break; - case REMOVE_COMMAND: - RemoveCommand.execute(commands, provider); + case LIST_COMMAND: + ListCommand.execute(commands, provider); break; - case DROP_COMMAND: - DropCommand.execute(commands, provider); - break; - case COMMIT_COMMAND: - CommitCommand.execute(commands, provider); - break; - case ROLLBACK_COMMAND: - RollbackCommand.execute(commands, provider); - break; - case USE_COMMAND: - UseCommand.execute(commands, provider); - break; - case SIZE_COMMAND: - SizeCommand.execute(commands, provider); - break; - case LIST_COMMAND: - ListCommand.execute(commands, provider); + case EXIT_COMMAND: { + ExitCommand.execute(commands, provider); + return false; + } + default: + System.out.println("Wrong command!"); break; - case EXIT_COMMAND: { - return ExitCommand.execute(commands, provider); - } - default: - System.out.println("Wrong command!"); - break; } return true; } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java index d11b9ebdb..ba7849071 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java @@ -2,13 +2,12 @@ import java.io.IOException; import java.util.Scanner; -import java.util.logging.Level; -import java.util.logging.Logger; public class JUnit { + public static void main(String[] args) throws IOException, IllegalArgumentException, KeyNullAndNotFound { - InteractiveMode user = new InteractiveMode("C:\\DataBase"); + InteractiveMode user = new InteractiveMode(System.getProperty("fizteh.db.dir")); Scanner sc = new Scanner(System.in); try { diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java index 14844565b..c50f130d9 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java @@ -2,6 +2,7 @@ @SuppressWarnings("serial") public class KeyNullAndNotFound extends Exception { + public KeyNullAndNotFound(String description) { super(description); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java index 500072664..19b280a8f 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java @@ -8,40 +8,36 @@ import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; /** * Класс @class Reader отвечает за физическое чтение данных из файловой системы. - * + * * * @author Timokhin Andrew */ - public class Reader { + static final int TOTAL_SUB_STRING = 16; static final String DIRECT = ".dir"; - private String directory; - + private final String directory; + public Reader(String directory) { this.directory = directory; } - + private void readKeyValue(DataInputStream rd, StringBuilder string) throws IOException { int length = rd.readInt(); for (int k = 0; k < length; k++) { - string - .append(rd.readChar()); + string + .append(rd.readChar()); + } } -} + public void read(TableProviderImplements tp) throws IOException { StringBuilder keyBuilder = new StringBuilder(); StringBuilder valueBuilder = new StringBuilder(); int length; String path = tp.getDir(); - List tables = new ArrayList(); boolean dbExist = false; File testDir = new File(path); if (testDir.list() != null) { @@ -50,8 +46,9 @@ public void read(TableProviderImplements tp) throws IOException { File checkDir = new File(pathToFile.toString()); if (checkDir.isDirectory()) { dbExist = true; - TableImplement dataBase = new TableImplement(time, tp.getDir()); - tables.add(dataBase); + tp.createTable(time); + TableImplement dataBase = (TableImplement) tp.getTable(time); + dataBase.setPath(tp.getDir()); for (int i = 0; i < TOTAL_SUB_STRING; i++) { Integer numberDir = new Integer(i); Path pathToDb = Paths.get(path, time, @@ -64,29 +61,29 @@ public void read(TableProviderImplements tp) throws IOException { try (DataInputStream rd = new DataInputStream( new FileInputStream( pathToLocalDb.toString()))) { - while (true) { - try { - readKeyValue(rd, keyBuilder); - readKeyValue(rd, valueBuilder); - - dataBase.getMap().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) { - break; + while (true) { + try { + readKeyValue(rd, keyBuilder); + readKeyValue(rd, valueBuilder); + + 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); } - } - } catch (FileNotFoundException exceptionFileNotFound) { - throw new RuntimeException( - exceptionFileNotFound); - } } } } @@ -94,13 +91,9 @@ public void read(TableProviderImplements tp) throws IOException { } } if (!dbExist) { - return ; - } - Map copy = new HashMap<>(); - for (TableImplement table : tables) { - copy.put(table.getName(), table); + return; } - tp.collection = copy; - return ; + + return; } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java index abcf1dbc1..723ce8a6b 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java @@ -12,40 +12,36 @@ public interface Table { /** * Получает значение по указанному ключу. * - * @param key - * Ключ. + * @param key Ключ. * @return Значение. Если не найдено, возвращает null. * @throws KeyNullAndNotFound * - * @throws IllegalArgumentException - * Если значение параметра key является null. + * @throws IllegalArgumentException Если значение параметра key является + * null. */ String get(String key) throws IllegalArgumentException, KeyNullAndNotFound; /** * Устанавливает значение по указанному ключу. * - * @param key - * Ключ. - * @param value - * Значение. + * @param key Ключ. + * @param value Значение. * @return Значение, которое было записано по этому ключу ранее. Если ранее - * значения не было записано, возвращает null. + * значения не было записано, возвращает null. * - * @throws IllegalArgumentException - * Если значение параметров key или value является null. + * @throws IllegalArgumentException Если значение параметров key или value + * является null. */ String put(String key, String value); /** * Удаляет значение по указанному ключу. * - * @param key - * Ключ. + * @param key Ключ. * @return Значение. Если не найдено, возвращает null. * - * @throws IllegalArgumentException - * Если значение параметра key является null. + * @throws IllegalArgumentException Если значение параметра key является + * null. */ String remove(String key); diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java index e821d5ed7..6133a73e4 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java @@ -1,12 +1,12 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; /** - * Класс TableImplement содержит логику работы таблицы базы данных. - * В нем переопределены все методы, которые заявлены в интерфейсе Table - * + * Класс TableImplement содержит логику работы таблицы базы данных. В нем + * переопределены все методы, которые заявлены в интерфейсе Table + * * @author Timokhin Andrew */ - +import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.time; import java.io.IOException; import java.util.List; import java.util.ArrayList; @@ -14,14 +14,16 @@ import java.util.HashMap; import java.util.Map; import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; -public class TableImplement implements Table { +public class TableImplement implements Table { private String name; private String path; private Map map; private Map backup; - public Map current; + private Map current; public TableImplement(String name, String path) { this.path = path; @@ -29,14 +31,16 @@ public TableImplement(String name, String path) { map = new HashMap(); backup = new HashMap(); current = new HashMap(); + } public String getPath() { return path; } - public Map getMap() { - return map; + public void setPath(String newPath) { + this.path = newPath; + return; } public Map getBackup() { @@ -47,18 +51,10 @@ public void setBackup(Map backup) { this.backup = backup; } - public void setMap(Map map) { - this.map = map; - } - public void setName(String name) { this.name = name; } - public void setPath(String path) { - this.path = path; - } - @Override public String getName() { return name; @@ -66,7 +62,7 @@ public String getName() { @Override public int size() { - return map.size(); + return map.size(); } @Override @@ -105,7 +101,7 @@ public String remove(String key) throws IllegalArgumentException { throw new IllegalArgumentException("Key shouldn't be null"); } if (map.containsKey(key)) { - time = map.get(key); + time = map.get(key); map.remove(key); } return time; @@ -117,7 +113,7 @@ public List list() { if (map != null) { return new ArrayList(map.keySet()); } - return new ArrayList(); + return new ArrayList(); } public int totalChanges() { @@ -147,6 +143,7 @@ public int totalChanges() { } } return counter; + } @Override @@ -158,53 +155,80 @@ public int commit() { } } - public int writeToDisk() throws IOException { + public int writeToDisk() throws IOException, IllegalArgumentException { boolean flagIfBaseExist = false; Reader reader = new Reader(this.path); FactoryImplements factory = new FactoryImplements(); TableProviderImplements tableProvider = (TableProviderImplements) factory .create(path); reader.read(tableProvider); + copyOfMap(this.map, this.backup); Writer writer = new Writer(); - if (tableProvider.collection != null) { + if (tableProvider.getAvailableTables() != null) { + { - if (tableProvider.collection.containsKey(this.getName())) { + if (tableProvider.getAvailableTables().contains(this.getName())) { { Map tmp = new HashMap<>(); - Set copy = tableProvider.collection.get(name).map - .keySet(); + List copy = tableProvider.getTable(this.getName()).list(); for (String copyString : copy) { - tmp.put(new String(copyString), - new String( - (String) tableProvider.collection - .get(name).map.get(copyString))); + try { + tmp.put(new String(copyString), + new String( + (String) tableProvider.getTable(this.getName()).get(copyString))); + } catch (KeyNullAndNotFound ex) { + + } } this.backup = new HashMap(tmp); } - tableProvider.collection.put(this.getName(), this); - flagIfBaseExist = true; + } 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) { + + } } + flagIfBaseExist = true; } } - if (!flagIfBaseExist) { - tableProvider.createTable(this.name); - this.backup = null; + + if (this.totalChanges() > 0) { + try { + writer.write(tableProvider); + } catch (KeyNullAndNotFound NullKey) { + + } } - if (tableProvider.collection.containsKey(this.getName())) - tableProvider.collection.put(this.getName(), this); - if (this.totalChanges() > 0) - writer.write(tableProvider); return this.totalChanges(); } @Override - public int rollback() throws NullPointerException{ + public int rollback() throws NullPointerException { Map copyMap = new HashMap(this.map); - if (this.backup!= null) - this.map = new HashMap(this.backup); - else + 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); + return; + } + } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java index 0170b90b9..2a755ef1f 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java @@ -5,36 +5,33 @@ public interface TableProvider { /** * Возвращает таблицу с указанным названием. * - * @param name - * Название таблицы. + * @param name Название таблицы. * @return Объект, представляющий таблицу. Если таблицы с указанным именем - * не существует, возвращает null. - * @throws IllegalArgumentException - * Если название таблицы null или имеет недопустимое значение. + * не существует, возвращает null. + * @throws IllegalArgumentException Если название таблицы null или имеет + * недопустимое значение. */ Table getTable(String name); /** * Создаёт таблицу с указанным названием. * - * @param name - * Название таблицы. + * @param name Название таблицы. * @return Объект, представляющий таблицу. Если таблица уже существует, - * возвращает null. - * @throws IllegalArgumentException - * Если название таблицы null или имеет недопустимое значение. + * возвращает null. + * @throws IllegalArgumentException Если название таблицы null или имеет + * недопустимое значение. */ Table createTable(String name); /** * Удаляет таблицу с указанным названием. * - * @param name - * Название таблицы. - * @throws IllegalArgumentException - * Если название таблицы null или имеет недопустимое значение. - * @throws IllegalStateException - * Если таблицы с указанным названием не существует. + * @param name Название таблицы. + * @throws IllegalArgumentException Если название таблицы null или имеет + * недопустимое значение. + * @throws IllegalStateException Если таблицы с указанным названием не + * существует. */ void removeTable(String name); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java index 8f5860f47..3197859eb 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java @@ -5,12 +5,10 @@ public interface TableProviderFactory { /** * Возвращает объект для работы с базой данных. * - * @param dir - * Директория с файлами базы данных. + * @param dir Директория с файлами базы данных. * @return Объект для работы с базой данных. - * @throws IllegalArgumentException - * Если значение директории null или имеет недопустимое - * значение. + * @throws IllegalArgumentException Если значение директории null или имеет + * недопустимое значение. */ TableProvider create(String dir); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java index b63108d5a..2a279ead5 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java @@ -7,15 +7,14 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; +import java.util.Set; /** * @author Timokhin Andrew */ - public class TableProviderImplements implements TableProvider { - - public Map collection; + private Map collection; private final String dir; TableProviderImplements(String dir) throws IOException { @@ -25,18 +24,23 @@ public class TableProviderImplements implements TableProvider { rd.read(this); } - public static void deleteDir(File dir) { + public Set getAvailableTables() { + return collection.keySet(); + } + + public static void deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (String childName : children) { deleteDir(new File(dir, childName)); } dir.delete(); - } else + } else { dir.delete(); + } } - - public void write() throws IOException { + + public void write() throws IOException, KeyNullAndNotFound { Writer writeToFileSystem = new Writer(); writeToFileSystem.write(this); } @@ -47,8 +51,9 @@ public Table getTable(String name) throws IllegalArgumentException { throw new IllegalArgumentException( "Name of DataBase is null"); } - if (collection.containsKey(name)) { - return collection.get(name); } + if (collection.containsKey(name)) { + return collection.get(name); + } return null; } @@ -59,10 +64,11 @@ public Table createTable(String name) throws IllegalArgumentException { "Name of DataBase is null. Please, enter correct name"); } if (collection != null) { - if (collection.containsKey(name)) + if (collection.containsKey(name)) { return null; - collection.put(name, new TableImplement(name, dir)); - return collection.get(name); + } + collection.put(name, new TableImplement(name, dir)); + return collection.get(name); } if (collection == null) { collection = new HashMap<>(); @@ -83,7 +89,7 @@ public void removeTable(String name) throws IllegalArgumentException, if (collection.containsKey(name)) { Path path = Paths.get( collection.get(name).getPath().toString(), collection - .get(name).getName()); + .get(name).getName()); File file = new File(path.toString()); this.deleteDir(file); collection.remove(name); @@ -92,7 +98,15 @@ public void removeTable(String name) throws IllegalArgumentException, } 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/JUnit/Test/TableImplementTest.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java index 563f223f0..12ca1ae64 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java @@ -166,7 +166,7 @@ public void testCommitIfWasRollback() { assertEquals(0, table.commit()); } - + public void testCommitAndCommit() { table.put("id1", "1"); table.put("id2", "2"); @@ -205,8 +205,8 @@ public void testRollbackSomeChainChanges() { table.commit(); assertEquals(2, table.rollback()); } - - @Test + + @Test public void testCommitCheckRollbackCheck() throws IllegalArgumentException, KeyNullAndNotFound { table.put("1", "11"); table.put("2", "22"); @@ -228,7 +228,7 @@ public void testCommitCheckRollbackCheck() throws IllegalArgumentException, KeyN } - @Test + @Test public void testCommitCheckChangesRollbackCheck() throws IllegalArgumentException, KeyNullAndNotFound { table.put("1", "11"); table.put("2", "22"); @@ -249,9 +249,7 @@ public void testCommitCheckChangesRollbackCheck() throws IllegalArgumentExceptio } - - - @Test + @Test public void extraCheck() throws IllegalArgumentException, KeyNullAndNotFound { table.put("a", "b"); table.commit(); 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 index 0a60f5e8f..b72c52b98 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java @@ -19,6 +19,7 @@ * @author Андрей */ public class TableProviderImplementsTest { + @Rule public TemporaryFolder tmp = new TemporaryFolder(); public TableProvider tp; @@ -32,7 +33,6 @@ public void setUp() { /** * Следующие тесты полностью тестируют реализацию интерфейса */ - /** * Тесты getTable метода */ @@ -56,7 +56,6 @@ public void testGetTableIfDnExist() { /** * Тесты createTable метода */ - @Test(expected = IllegalArgumentException.class) public void testCreateTable() { tp.createTable(null); diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/UnknownCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/UnknownCommand.java index b99e7c859..7e7cc5408 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/UnknownCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/UnknownCommand.java @@ -10,6 +10,7 @@ * @author Андрей */ public class UnknownCommand extends Exception { + public UnknownCommand(String description) { super(description); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java index 6727f0d36..8d55e5818 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java @@ -8,6 +8,7 @@ import static java.lang.Math.abs; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; /** * Класс @class Writer отвечает за физическую запись информации с на жесткий @@ -16,8 +17,8 @@ * * @author Timokhin Andrew */ - public class Writer { + final int totalSubDir = 16; final String dirct = ".dir"; @@ -55,20 +56,20 @@ public void deleteDirectory(File dir) { } } - public void write(TableProviderImplements tp) throws IOException { + public void write(TableProviderImplements tp) throws IOException, KeyNullAndNotFound { this.deleteDirectory(new File(tp.getDir())); File baseDir = new File(tp.getDir()); baseDir.mkdir(); - if (tp.collection != null) { - Set dataBase = tp.collection.keySet(); + if (tp.getAvailableTables() != null) { + Set dataBase = tp.getAvailableTables(); for (String name : dataBase) { - TableImplement ti = tp.collection.get(name); + TableImplement ti = (TableImplement) tp.getTable(name); Path pathToDb = Paths.get(tp.getDir(), ti.getName()); File dataBaseDir = new File(pathToDb.toString()); dataBaseDir.mkdir(); - if (ti.getMap() != null) { - Set keyList; - keyList = ti.getMap().keySet(); + { + ArrayList keyList; + keyList = (ArrayList) ti.list(); for (String keyFind : keyList) { Integer dirToWrite = new Integer(abs(keyFind.hashCode() % totalSubDir)); @@ -77,7 +78,7 @@ public void write(TableProviderImplements tp) throws IOException { if (!this.checkDir(localPath.toString())) { this.createDir(localPath.toString()); } - dirToWrite = new Integer((ti.getMap().get(keyFind) + dirToWrite = new Integer((ti.get(keyFind) .hashCode() % totalSubDir % totalSubDir)); Path localFile = Paths.get(localPath.toString(), @@ -92,11 +93,16 @@ public void write(TableProviderImplements tp) throws IOException { new FileOutputStream(localFile.toString(), true)); outStream.writeInt(keyFind.length()); outStream.writeChars(keyFind); - outStream.writeInt(ti.getMap().get(keyFind).toString() - .length()); - outStream.writeChars(ti.getMap().get(keyFind) - .toString()); - outStream.close(); + try { + outStream.writeInt(ti.get(keyFind).toString() + .length()); + outStream.writeChars(ti.get(keyFind) + .toString()); + } catch (NullPointerException nullPointer) { + throw nullPointer; + } finally { + outStream.close(); + } } } From 512eb42ea189c2cf019a7954794b1b4a9ddb5817 Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Tue, 3 Feb 2015 04:15:17 +0300 Subject: [PATCH 11/18] without test --- .../FactoryImplements.java | 2 +- .../KeyNullAndNotFound.java | 2 +- .../FileMap/{JUnit => DataBase}/Reader.java | 10 +- .../FileMap/{JUnit => DataBase}/Table.java | 2 +- .../{JUnit => DataBase}/TableImplement.java | 18 +- .../{JUnit => DataBase}/TableProvider.java | 2 +- .../TableProviderFactory.java | 2 +- .../TableProviderImplements.java | 3 +- .../FileMap/{JUnit => DataBase}/Writer.java | 2 +- .../FileMap/JUnit/Commands/Commands.java | 28 -- .../FileMap/JUnit/Commands/ExitCommand.java | 19 -- .../FileMap/JUnit/Commands/SizeCommand.java | 27 -- .../FileMap/JUnit/InteractiveMode.java | 97 ------- .../FileMap/JUnit/Interpretator/Commands.java | 80 ++++++ .../JUnit/Interpretator/InteractiveMode.java | 43 +++ .../{ => Interpretator}/UnknownCommand.java | 3 +- .../AndrewTimokhin/FileMap/JUnit/JUnit.java | 66 ----- .../{Commands => Main}/CommitCommand.java | 18 +- .../{Commands => Main}/CreateCommand.java | 19 +- .../JUnit/{Commands => Main}/DropCommand.java | 19 +- .../FileMap/JUnit/Main/ExitCommand.java | 26 ++ .../JUnit/{Commands => Main}/GetCommand.java | 25 +- .../JUnit/{Commands => Main}/ListCommand.java | 24 +- .../FileMap/JUnit/Main/Main.java | 25 ++ .../JUnit/{Commands => Main}/PutCommand.java | 22 +- .../{Commands => Main}/RemoveCommand.java | 24 +- .../{Commands => Main}/RollbackCommand.java | 20 +- .../FileMap/JUnit/Main/SizeCommand.java | 30 ++ .../JUnit/{Commands => Main}/UseCommand.java | 22 +- .../JUnit/Test/FactoryImplementsTest.java | 28 -- .../JUnit/Test/TableImplementTest.java | 261 ------------------ .../Test/TableProviderImplementsTest.java | 91 ------ 32 files changed, 338 insertions(+), 722 deletions(-) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/{JUnit => DataBase}/FactoryImplements.java (92%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/{JUnit => DataBase}/KeyNullAndNotFound.java (72%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/{JUnit => DataBase}/Reader.java (91%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/{JUnit => DataBase}/Table.java (97%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/{JUnit => DataBase}/TableImplement.java (93%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/{JUnit => DataBase}/TableProvider.java (96%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/{JUnit => DataBase}/TableProviderFactory.java (88%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/{JUnit => DataBase}/TableProviderImplements.java (97%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/{JUnit => DataBase}/Writer.java (98%) delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/Commands.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/InteractiveMode.java rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/{ => Interpretator}/UnknownCommand.java (82%) delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/{Commands => Main}/CommitCommand.java (52%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/{Commands => Main}/CreateCommand.java (52%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/{Commands => Main}/DropCommand.java (58%) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitCommand.java rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/{Commands => Main}/GetCommand.java (58%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/{Commands => Main}/ListCommand.java (57%) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/Main.java rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/{Commands => Main}/PutCommand.java (55%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/{Commands => Main}/RemoveCommand.java (58%) rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/{Commands => Main}/RollbackCommand.java (52%) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/SizeCommand.java rename src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/{Commands => Main}/UseCommand.java (57%) delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/FactoryImplements.java similarity index 92% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/FactoryImplements.java index 9e569d792..f96850c3e 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/FactoryImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/FactoryImplements.java @@ -1,4 +1,4 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; import java.io.IOException; diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java similarity index 72% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java index c50f130d9..2e7cad278 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/KeyNullAndNotFound.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java @@ -1,4 +1,4 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; @SuppressWarnings("serial") public class KeyNullAndNotFound extends Exception { diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Reader.java similarity index 91% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Reader.java index 19b280a8f..6edda445e 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Reader.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Reader.java @@ -1,4 +1,4 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; import java.io.DataInputStream; import java.io.EOFException; @@ -69,18 +69,20 @@ public void read(TableProviderImplements tp) throws IOException { dataBase.put( keyBuilder.toString(), valueBuilder.toString()); - dataBase.getBackup().put(keyBuilder.toString(), valueBuilder.toString()); + dataBase.getBackup().put( + keyBuilder.toString(), + valueBuilder.toString()); keyBuilder.replace(0, keyBuilder.length(), ""); valueBuilder.replace(0, - valueBuilder.length(), ""); + valueBuilder.length(), ""); } catch (EOFException e) { rd.close(); break; } } - } catch (FileNotFoundException exceptionFileNotFound) { + } catch (FileNotFoundException exceptionFileNotFound) { throw new RuntimeException( exceptionFileNotFound); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Table.java similarity index 97% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Table.java index 723ce8a6b..5b813fe1b 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Table.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Table.java @@ -1,4 +1,4 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; import java.util.List; diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableImplement.java similarity index 93% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableImplement.java index 6133a73e4..aa710366f 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableImplement.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableImplement.java @@ -1,4 +1,4 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; /** * Класс TableImplement содержит логику работы таблицы базы данных. В нем @@ -6,16 +6,12 @@ * * @author Timokhin Andrew */ -import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.time; import java.io.IOException; import java.util.List; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; public class TableImplement implements Table { @@ -176,8 +172,8 @@ public int writeToDisk() throws IOException, IllegalArgumentException { tmp.put(new String(copyString), new String( (String) tableProvider.getTable(this.getName()).get(copyString))); - } catch (KeyNullAndNotFound ex) { - + } catch (KeyNullAndNotFound exception) { + continue; } } this.backup = new HashMap(tmp); @@ -191,9 +187,9 @@ public int writeToDisk() throws IOException, IllegalArgumentException { tableProvider.createTable(this.getName()); for (String timeString : this.list()) { try { - tableProvider.getTable(this.getName()).put(new String(timeString), new String(this.get(timeString))); + tableProvider.getTable(this.getName()).put(new String(timeString), new String(this.get(timeString))); } catch (KeyNullAndNotFound ex) { - + continue; } } flagIfBaseExist = true; @@ -203,8 +199,8 @@ public int writeToDisk() throws IOException, IllegalArgumentException { if (this.totalChanges() > 0) { try { writer.write(tableProvider); - } catch (KeyNullAndNotFound NullKey) { - + } catch (KeyNullAndNotFound nullKey) { + System.out.println(nullKey.toString()); } } return this.totalChanges(); diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProvider.java similarity index 96% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProvider.java index 2a755ef1f..152e8c771 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProvider.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProvider.java @@ -1,4 +1,4 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; public interface TableProvider { diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderFactory.java similarity index 88% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderFactory.java index 3197859eb..85fbc2af8 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderFactory.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderFactory.java @@ -1,4 +1,4 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; public interface TableProviderFactory { diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderImplements.java similarity index 97% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderImplements.java index 2a279ead5..1e70c1fb4 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/TableProviderImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderImplements.java @@ -1,10 +1,9 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +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.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Writer.java similarity index 98% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Writer.java index 8d55e5818..3deff6655 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Writer.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Writer.java @@ -1,4 +1,4 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; import java.io.DataOutputStream; import java.io.File; diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java deleted file mode 100644 index 38d603028..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/Commands.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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.Commands; - -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableImplement; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; - -/** - * - * @author Андрей - */ -public class Commands { - - static TableImplement currentTable; - - static public void execute(String[] command, TableProviderImplements table) { - return; //be-default - } - - ; - static void invitationToRepeat() { - System.out - .println("Current command was not recognized or not complete. Please, try again"); - } -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java deleted file mode 100644 index 2c4fabf48..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ExitCommand.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * 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.Commands; - -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; - -/** - * - * @author Андрей - */ -public class ExitCommand extends Commands { - - static public void execute(String[] commands, TableProviderImplements tableProvider) { - return; - } -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java deleted file mode 100644 index c507b5e42..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/SizeCommand.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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.Commands; - -import java.util.Set; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; - -/** - * - * @author Андрей - */ -public class SizeCommand extends Commands { - - static public void execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 1) { - Commands.invitationToRepeat(); - return; - } - { - System.out.println(tableProvider.size()); - } - return; - } -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java deleted file mode 100644 index 58b77a4e6..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/InteractiveMode.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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.JUnit.Commands.CommitCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.CreateCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.DropCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.ExitCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.GetCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.ListCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.PutCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.RemoveCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.RollbackCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.SizeCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands.UseCommand; - -/** - * - * @author Timokhin Andrew - * - */ -public class InteractiveMode { - - static final String CREATE_COMMAND = "create"; - static final String PUT_COMMAND = "put"; - static final String GET_COMMAND = "get"; - static final String REMOVE_COMMAND = "remove"; - static final String DROP_COMMAND = "drop"; - static final String COMMIT_COMMAND = "commit"; - static final String ROLLBACK_COMMAND = "rollback"; - static final String USE_COMMAND = "use"; - static final String SIZE_COMMAND = "size"; - static final String LIST_COMMAND = "list"; - static final String EXIT_COMMAND = "exit"; - - private TableImplement table; - final private TableProviderImplements provider; - final private FactoryImplements factory; - private String currentDir; - - InteractiveMode(String path) { - factory = new FactoryImplements(); - provider = (TableProviderImplements) factory.create(path); - } - - boolean command(String textToParser) throws UnknownCommand, - IllegalArgumentException, KeyNullAndNotFound { - String[] commands = textToParser.trim().split(" "); - if (commands.length < 1) { - throw new UnknownCommand( - "Current command was not recognized. Programm fail"); - } - switch (commands[0]) { - case CREATE_COMMAND: - CreateCommand.execute(commands, provider); - break; - case PUT_COMMAND: - PutCommand.execute(commands, provider); - break; - case GET_COMMAND: - GetCommand.execute(commands, provider); - break; - case REMOVE_COMMAND: - RemoveCommand.execute(commands, provider); - break; - case DROP_COMMAND: - DropCommand.execute(commands, provider); - break; - case COMMIT_COMMAND: - CommitCommand.execute(commands, provider); - break; - case ROLLBACK_COMMAND: - RollbackCommand.execute(commands, provider); - break; - case USE_COMMAND: - UseCommand.execute(commands, provider); - break; - case SIZE_COMMAND: - SizeCommand.execute(commands, provider); - break; - case LIST_COMMAND: - ListCommand.execute(commands, provider); - break; - case EXIT_COMMAND: { - ExitCommand.execute(commands, provider); - return false; - } - default: - System.out.println("Wrong command!"); - break; - } - return true; - } -} 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..f13667922 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/Commands.java @@ -0,0 +1,80 @@ +/* + * 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.HashMap; +import java.util.Map; +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.Main.CommitCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.CreateCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.DropCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.ExitCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.GetCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.ListCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.PutCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.RemoveCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.RollbackCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.SizeCommand; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.UseCommand; + +/** + * + * @author Андрей + */ +public class Commands { + + int digital; + public static TableImplement currentTable; + private Map totalCommands; + + public Commands(int digital) { + this.digital = digital; + + } + + public Commands() { + } + + public Map getAllCommand() { + 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()); + return totalCommands; + } + + public boolean checkAndRun(String[] command, TableProviderImplements table) { + if (this.invitationToRepeat(command, digital)) { + return true; + } + return this.execute(command, table); + + } + + public boolean execute(String[] command, TableProviderImplements table) { + return true; + } + + public boolean invitationToRepeat(String[] args, int checkValue) { + + if (args.length != checkValue) { + 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..44298319b --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/InteractiveMode.java @@ -0,0 +1,43 @@ +/* + * 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.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; + +/** + * + * @author Timokhin Andrew + * + */ +public class InteractiveMode { + + private final TableProviderImplements provider; + private final FactoryImplements factory; + private TableImplement table; + private String currentDir; + private Map allCommand; + + public InteractiveMode(String path, Commands command) { + allCommand = command.getAllCommand(); + factory = new FactoryImplements(); + provider = (TableProviderImplements) factory.create(path); + } + + public boolean command(String textToParser) throws UnknownCommand, + IllegalArgumentException, KeyNullAndNotFound { + String[] commands = textToParser.trim().split(" "); + if (commands.length < 1 || !allCommand.containsKey(commands[0])) { + System.out.println("Wrong command!"); + return true; + } + return allCommand.get(commands[0]).checkAndRun(commands, provider); + + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/UnknownCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/UnknownCommand.java similarity index 82% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/UnknownCommand.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/UnknownCommand.java index 7e7cc5408..c52636622 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/UnknownCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/UnknownCommand.java @@ -3,7 +3,7 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator; /** * @@ -14,4 +14,5 @@ public class UnknownCommand extends Exception { public UnknownCommand(String description) { super(description); } + } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java deleted file mode 100644 index ba7849071..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/JUnit.java +++ /dev/null @@ -1,66 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; - -import java.io.IOException; -import java.util.Scanner; - -public class JUnit { - - public static void main(String[] args) throws IOException, - IllegalArgumentException, KeyNullAndNotFound { - InteractiveMode user = new InteractiveMode(System.getProperty("fizteh.db.dir")); - Scanner sc = new Scanner(System.in); - - try { - while (user.command(sc.nextLine())); - /* - * FactoryImplements tb = new FactoryImplements(); - * TableProviderImplements tp = (TableProviderImplements) tb - * .create("C:\\DataBase"); Table tableA1 = tp.createTable("A1"); - * tableA1 = tp.getTable("A1"); - * - * /* Uncomment to see, that we have, when we run this programm - * twice. A1 must be : (1,1); (2,2); (3,3); A2 must be : all changes - */ - /* - * System.out.println("<===twice===>\n"); for (String tm : - * tableA1.list()) { System.out.println("key -> " + tm + - * " value -> " + tableA1.get(tm) ); } - * System.out.println("\n<===twice===>\n"); - */ - - /* - * tableA1.put("1", "1"); tableA1.put("2", "2"); tableA1.put("3", - * "3"); tableA1.commit(); tableA1.put("4", "4"); tableA1.put("5", - * "5"); tableA1.put("6", "6"); tableA1.put("7", "7"); - * tableA1.commit(); tableA1.rollback(); - * - * for (String tm : tableA1.list()) { System.out.println("key -> " + - * tm + " value -> " + tableA1.get(tm)); } - * - * Table tableA2 = tp.createTable("A2"); tableA2 = - * tp.getTable("A2"); - * - * /* System.out.println("<===twice===> \n"); for (String time: - * tableA2.list()){ System.out.println("key -> " + time + - * " value -> " + tableA2.get(time) ); } - * System.out.println("\n<===twice===> \n"); - */ - - /* - * tableA2.put("1", "green"); tableA2.put("2", "blue"); - * - * System.out.println("<========NEXT========>\n"); - * tableA2.remove("1"); - * - * for (String time : tableA2.list()) { System.out.println("key -> " - * + time + " value -> " + tableA2.get(time)); } - * - * tableA2.commit(); tableA2.put("3", "green"); tableA2.put("4", - * "black"); tableA2.put("5", "red"); tableA2.commit(); try { - * tableA2.get(null); } catch (KeyNullAndNotFound e) { - * System.out.println(e); } System.out.println(tableA2.get("4")); - */ - } catch (UnknownCommand ex) { - } - } -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CommitCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CommitCommand.java similarity index 52% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CommitCommand.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CommitCommand.java index 8137c648d..6b07a72cb 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CommitCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CommitCommand.java @@ -3,9 +3,10 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; /** * @@ -13,16 +14,17 @@ */ public class CommitCommand extends Commands { - static public void execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 1) { - Commands.invitationToRepeat(); - return; - } + public CommitCommand() { + super(1); + } + + @Override + public boolean execute(String[] commands, TableProviderImplements tableProvider) { if (currentTable != null) { System.out.println("Total changes -> " + currentTable.commit()); } else { System.out.println("No table"); } - return; + return true; } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CreateCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CreateCommand.java similarity index 52% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CreateCommand.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CreateCommand.java index cfb511f2f..2487edabf 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/CreateCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CreateCommand.java @@ -3,9 +3,10 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; /** * @@ -13,16 +14,18 @@ */ public class CreateCommand extends Commands { - static public void execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 2) { - Commands.invitationToRepeat(); - return; - } + public CreateCommand() { + super(2); + } + + @Override + public boolean execute(String[] commands, TableProviderImplements tableProvider) { if (tableProvider.createTable(commands[1]) == null) { System.out.println("Exist!"); } else { System.out.println("created"); } - return; + return true; } + } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/DropCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/DropCommand.java similarity index 58% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/DropCommand.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/DropCommand.java index c1615241d..88c72bb70 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/DropCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/DropCommand.java @@ -3,9 +3,10 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; /** * @@ -13,11 +14,12 @@ */ public class DropCommand extends Commands { - static public void execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 2) { - Commands.invitationToRepeat(); - return; - } + public DropCommand() { + super(2); + } + + @Override + public boolean execute(String[] commands, TableProviderImplements tableProvider) { try { tableProvider.removeTable(commands[1]); System.out.println("dropped"); @@ -26,6 +28,7 @@ static public void execute(String[] commands, TableProviderImplements tableProvi } catch (IllegalArgumentException error) { System.out.println(error); } - return; + return true; } + } 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..de7011e28 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitCommand.java @@ -0,0 +1,26 @@ +/* + * 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.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class ExitCommand extends Commands { + + public ExitCommand() { + super(1); + } + + @Override + public boolean execute(String[] commands, TableProviderImplements tableProvider) { + return false; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/GetCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/GetCommand.java similarity index 58% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/GetCommand.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/GetCommand.java index eaae4f19d..a81e7941e 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/GetCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/GetCommand.java @@ -3,11 +3,11 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; -import java.util.logging.Logger; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.KeyNullAndNotFound; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; +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.TableProviderImplements; /** * @@ -15,13 +15,15 @@ */ public class GetCommand extends Commands { - static public void execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 2) { - Commands.invitationToRepeat(); - return; - } else if (currentTable == null) { + public GetCommand() { + super(2); + } + + @Override + public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (currentTable == null) { System.out.println("No table"); - return; + return true; } else { String value; try { @@ -36,6 +38,7 @@ static public void execute(String[] commands, TableProviderImplements tableProvi } } - return; + return true; } + } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ListCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ListCommand.java similarity index 57% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ListCommand.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ListCommand.java index b593e7f63..a2e904245 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/ListCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ListCommand.java @@ -3,11 +3,12 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands; +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.JUnit.KeyNullAndNotFound; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.KeyNullAndNotFound; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; /** * @@ -15,13 +16,15 @@ */ public class ListCommand extends Commands { - static public void execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 1) { - Commands.invitationToRepeat(); - return; - } else if (currentTable == null) { + public ListCommand() { + super(1); + } + + @Override + public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (currentTable == null) { System.out.println("No table"); - return; + return true; } else { ArrayList set; set = (ArrayList) currentTable.list(); @@ -33,6 +36,7 @@ static public void execute(String[] commands, TableProviderImplements tableProvi } } } - return; + return true; } + } 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..3df876339 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/Main.java @@ -0,0 +1,25 @@ +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.Scanner; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.KeyNullAndNotFound; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.UnknownCommand; + +public class Main { + + public static void main(String[] args) throws IOException, + IllegalArgumentException, KeyNullAndNotFound, UnknownCommand { + InteractiveMode user = new InteractiveMode("C:\\DataBase", new Commands()); + Scanner sc = new Scanner(System.in); + System.out.print("$ "); + try { + while (user.command(sc.nextLine())) { + System.out.print("$ "); + } + } catch (UnknownCommand ex) { + System.out.println("Unknow operation. Fail"); + } + } +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/PutCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/PutCommand.java similarity index 55% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/PutCommand.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/PutCommand.java index 89de343b9..8961b239c 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/PutCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/PutCommand.java @@ -3,9 +3,10 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; /** * @@ -13,13 +14,15 @@ */ public class PutCommand extends Commands { - static public void execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 3) { - Commands.invitationToRepeat(); - return; - } else if (currentTable == null) { + public PutCommand() { + super(3); + } + + @Override + public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (currentTable == null) { System.out.println("No table"); - return; + return true; } else { String oldValue = currentTable.put(commands[1], commands[2]); if (oldValue != null) { @@ -28,6 +31,7 @@ static public void execute(String[] commands, TableProviderImplements tableProvi System.out.println("*new*"); } } - return; + return true; } + } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RemoveCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RemoveCommand.java similarity index 58% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RemoveCommand.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RemoveCommand.java index 7f764d08a..0fd91bc67 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RemoveCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RemoveCommand.java @@ -3,9 +3,10 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; /** * @@ -13,17 +14,19 @@ */ public class RemoveCommand extends Commands { - static public void execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 2) { - Commands.invitationToRepeat(); - return; - } else if (currentTable == null) { + public RemoveCommand() { + super(2); + } + + @Override + public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (currentTable == null) { System.out.println("No table"); - return; + return true; } else { if (commands[1] == null) { System.out.println("*wrong key"); - return; + return true; } String value = currentTable.remove(commands[1]); if (value != null) { @@ -32,6 +35,7 @@ static public void execute(String[] commands, TableProviderImplements tableProvi System.out.println("*not removed, because not exist*"); } } - return; + return true; } + } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RollbackCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RollbackCommand.java similarity index 52% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RollbackCommand.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RollbackCommand.java index 24877b631..18dbfa2f7 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/RollbackCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RollbackCommand.java @@ -3,9 +3,10 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator.Commands; +import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase.TableProviderImplements; /** * @@ -13,16 +14,19 @@ */ public class RollbackCommand extends Commands { - static public void execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 1) { - Commands.invitationToRepeat(); - return; - } + public RollbackCommand() { + super(1); + } + + @Override + public boolean execute(String[] commands, TableProviderImplements tableProvider) { + if (currentTable != null) { System.out.println("Total changes -> " + currentTable.rollback()); } else { System.out.println("No table"); } - return; + return true; } + } 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..03ca5ca70 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/SizeCommand.java @@ -0,0 +1,30 @@ +/* + * 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.TableProviderImplements; + +/** + * + * @author Андрей + */ +public class SizeCommand extends Commands { + + public SizeCommand() { + super(1); + } + + @Override + public boolean execute(String[] commands, TableProviderImplements tableProvider) { + + { + System.out.println(tableProvider.size()); + } + return true; + } + +} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/UseCommand.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UseCommand.java similarity index 57% rename from src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/UseCommand.java rename to src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UseCommand.java index 268bc12fa..cecb94e9c 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Commands/UseCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UseCommand.java @@ -3,10 +3,11 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Commands; +package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableImplement; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.TableProviderImplements; +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; /** * @@ -14,11 +15,13 @@ */ public class UseCommand extends Commands { - public static void execute(String[] commands, TableProviderImplements tableProvider) { - if (commands.length != 2) { - Commands.invitationToRepeat(); - return; - } + public UseCommand() { + super(2); + } + + @Override + public boolean execute(String[] commands, TableProviderImplements tableProvider) { + currentTable = (TableImplement) tableProvider.getTable(commands[1]); if (currentTable == null) { System.out.println("Not exists"); @@ -29,6 +32,7 @@ public static void execute(String[] commands, TableProviderImplements tableProvi System.out.println("Using"); } } - return; + return true; } + } 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 deleted file mode 100644 index 9b87330fa..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/FactoryImplementsTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -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 deleted file mode 100644 index 12ca1ae64..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableImplementTest.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Модульные тесты базы данных. - * - */ -package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit; - -import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; -import java.lang.IllegalArgumentException; -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())); - } - - /** - * Тесты на 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 deleted file mode 100644 index b72c52b98..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Test/TableProviderImplementsTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * 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 org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -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")); - } -} From 228acff6b8f59ca5375acd4a2790366195c2eb3f Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Tue, 3 Feb 2015 04:20:28 +0300 Subject: [PATCH 12/18] *with tests* --- .../JUnit/test/FactoryImplementsTest.java | 29 ++ .../JUnit/test/TableImplementTest.java | 262 ++++++++++++++++++ .../test/TableProviderImplementsTest.java | 91 ++++++ 3 files changed, 382 insertions(+) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/FactoryImplementsTest.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableImplementTest.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableProviderImplementsTest.java 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..814190111 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableImplementTest.java @@ -0,0 +1,262 @@ +/* + * Модульные тесты базы данных. + * + */ +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())); + } + + /** + * Тесты на 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")); + } +} From ec5d7cda347202ba2de8a2e10b41fc48a35d0265 Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Tue, 3 Feb 2015 04:46:13 +0300 Subject: [PATCH 13/18] *delete old* --- .../AndrewTimokhin/DataBase/Functional.java | 56 ------- .../AndrewTimokhin/DataBase/MainClass.java | 23 --- .../AndrewTimokhin/DataBase/ModeWork.java | 68 -------- .../AndrewTimokhin/DataBase/Reader.java | 57 ------- .../AndrewTimokhin/DataBase/Write.java | 31 ---- .../MultiDataBase/Functional.java | 73 -------- .../MultiDataBase/MainClass.java | 32 ---- .../MultiDataBase/ModeWork.java | 82 --------- .../AndrewTimokhin/MultiDataBase/Reader.java | 79 --------- .../MultiDataBase/TableWork.java | 111 ------------- .../AndrewTimokhin/MultiDataBase/Write.java | 59 ------- .../MultiFileHashMap v2.0/Functional.java | 58 ------- .../MultiFileHashMap v2.0/JUnit.java | 23 --- .../MultiFileHashMap v2.0/ModeWork.java | 94 ----------- .../MultiFileHashMap v2.0/Reader.java | 95 ----------- .../MultiFileHashMap v2.0/TableDriver.java | 37 ----- .../MultiFileHashMap v2.0/TableWork.java | 157 ------------------ .../MultiFileHashMap v2.0/Write.java | 72 -------- 18 files changed, 1207 deletions(-) delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Functional.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/MainClass.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/ModeWork.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Reader.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/DataBase/Write.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Functional.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/MainClass.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/ModeWork.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Reader.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/TableWork.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Write.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Functional.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/JUnit.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/ModeWork.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Reader.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableDriver.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableWork.java delete mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Write.java 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/MultiDataBase/Functional.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Functional.java deleted file mode 100644 index 577df5d48..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Functional.java +++ /dev/null @@ -1,73 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; - -import java.util.*; - -class Functional { - public Map[] map; - - public Functional(Map[] map) { - this.map = map; - } - - void put(Map[] map, int i, String key, String value) { - if (i == -1) { - System.out.println("NotDefBD#"); - return; - } - - if (map[i].containsKey(key)) { - System.out.println("overwrite"); - System.out.println(map[i].get(key)); - } else { - System.out.println("new"); - } - map[i].put(key, value); - } - - void get(Map[] map, int i, String key) { - if (i == -1) { - System.out.println("NotDefBD#"); - return; - } - if (map[i] != null) { - if (map[i].containsKey(key)) { - System.out.println("found"); - System.out.println(map[i].get(key)); - } else { - System.out.println("not found"); - } - } - } - - void remove(Map[] map, int i, String key) { - if (i == -1) { - System.out.println("NotDefBD#"); - return; - } - if (map[i] != null) { - if (map[i].containsKey(key)) { - map[i].remove(key); - } else { - System.out.println("not found"); - } - } - } - - void showtables() { - for (int i = 0; i < 16; i++) { - if (map[i] != null) { - if (map[i].size() == 0) { - map[i] = null; - } - } - } - for (int i = 0; i < 16; i++) { - if (map[i] != null) { - - System.out.println("table " + i + " " + map[i].size()); - } - } - - } -} - diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/MainClass.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/MainClass.java deleted file mode 100644 index 3e0d27cbf..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/MainClass.java +++ /dev/null @@ -1,32 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; - -import java.io.*; -import java.util.*; - -public class MainClass { - - public static void main(String[] args) { - @SuppressWarnings("unchecked") - Map[] map = (Map[]) new Map[16]; - for (int i = 0; i < 16; i++) { - map[i] = new HashMap(); - } - - Reader rd = new Reader(System.getProperty("fizteh.db.dir").toString()); - map = rd.read(); - Write wr = new Write(System.getProperty("fizteh.db.dir").toString()); - Functional fn = new Functional(map); - ModeWork mw = new ModeWork(map, System.getProperty("fizteh.db.dir") - .toString()); - mw.usermode(fn); - - try { - wr.write(map); - - } catch (IOException e) { - System.out.println(e.toString()); - } - - } -} - diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/ModeWork.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/ModeWork.java deleted file mode 100644 index eb5261a61..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/ModeWork.java +++ /dev/null @@ -1,82 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; - -import java.util.*; - -class ModeWork { - String dir; - TableWork tw = new TableWork(); - - public ModeWork(Map[] time, String direct) { - dir = direct; - } - - int stepMode(String[] array, Functional f, int index) { - - switch (array[0 + index]) { - case "put": - f.put(f.map, tw.setDir, array[1 + index], array[2 + index]); - return 2; - case "get": - f.get(f.map, tw.setDir, array[1 + index]); - return 1; - case "remove": - f.remove(f.map, tw.setDir, array[1 + index]); - return 1; - case "create": - tw.create(f.map, dir, array[1 + index]); - tw.createforUser(f.map, Integer.parseInt(array[1 + index])); - return 1; - case "drop": - tw.drop(dir, array[1 + index]); - tw.dropForUser(f.map, Integer.parseInt(array[1 + index])); - return 1; - case "use": - if (tw.userUse(dir, array[1 + index]) == 0) { - System.out.println("not exist"); - } else { - System.out.println("using " + array[1 + index]); - } - tw.setDir = Integer.parseInt(array[1 + index] - .replaceAll(".dat", "")); - return 1; - - case "showtables": - f.showtables(); - return 1; - case "exit": - return -1; - default: - System.out.println("Unknow operation. Fail."); - return -1; - } - } - - void usermode(Functional func) { - - 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; - } - } - rd.close(); - - } - - /* - * void interactive( Map[] time , String[] mass) { int - * offset = 0; Functional func = new Functional(time); int i = 0; while - * (true) { if (i < mass.length) { offset = stepMode(time,mass, func, i); i - * += offset; if (offset == -1) { break; } i++; } else { break; } } - * - * } - */ - -} - diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Reader.java deleted file mode 100644 index ebdaaab85..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Reader.java +++ /dev/null @@ -1,79 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; - -import java.util.*; -import java.io.*; - -public class Reader { - private TableWork tw = new TableWork(); - private String filepath; - - private Map[] map; - - public Reader(String path) { - filepath = path; - - map = (Map[]) new Map[16]; - - } - - public Map[] read() { - for (Integer i = 0; i < 16; i++) { - if (tw.useForReader(filepath, i.toString()) == 1) { - map[i] = new HashMap(); - StringBuilder keyBuilder = new StringBuilder(); - StringBuilder valueBuilder = new StringBuilder(); - File localbase = new File(filepath + "/" + i.toString()); - String[] list = localbase.list(); - if (list != null) { - for (String currentDat : list) { - int length = 0; - try (DataInputStream rd = new DataInputStream( - new FileInputStream(filepath + "/" - + i.toString() + "/" + currentDat))) { - while (true) { - try { - length = rd.readInt(); - for (int k = 0; k < length; k++) { - keyBuilder.append(rd.readChar()); - - } - length = rd.readInt(); - for (int k = 0; k < length; k++) { - valueBuilder.append(rd.readChar()); - - } - map[i].put(keyBuilder.toString(), - valueBuilder.toString()); - keyBuilder.replace(0, keyBuilder.length(), - ""); - valueBuilder.replace(0, - valueBuilder.length(), ""); - if (i == 15) { - tw.setDir = -1; - } - } 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/MultiDataBase/TableWork.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/TableWork.java deleted file mode 100644 index 0abe22833..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/TableWork.java +++ /dev/null @@ -1,111 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; - -import java.io.*; -import java.util.*; - -public class TableWork { - public int setDir = -1; // by default - - public int getset() { - return setDir; - } - - public void createforUser(Map[] agr, int numdir) { - if (agr[numdir] != null) { - - return; - } - agr[numdir] = new HashMap(); - return; - } - - public int create(Map[] agr, String homeDir, - String tableToAdd) { - - File local = new File(homeDir); - String[] list; - list = local.list(); - if (list != null) { - for (int i = 0; i < list.length; i++) { - if (list[i].equals(tableToAdd)) { - System.out.println(tableToAdd + " exists"); - return 1; // if exist - } - - } - } - File newtable = new File(homeDir + "/" + tableToAdd); - newtable.mkdirs(); - if (agr[Integer.parseInt(tableToAdd)] == null) { - agr[Integer.parseInt(tableToAdd)] = new HashMap(); - } - System.out.println("created"); - return 0; // if added - } - - public void dropForUser(Map[] agr, int numdir) { - if (agr[numdir] == null) { - return; - } - agr[numdir] = null; - return; - - } - - public int drop(String homeDir, String tableToDel) { - int haveDir = 0; - File local = new File(homeDir); - String[] list; - list = local.list(); - if (list != null) { - for (int i = 0; i < list.length; i++) { - if (list[i].equals(tableToDel)) { - haveDir = 1; // if exist - } - } - } - if (haveDir == 0) { - System.out.println("not exists"); - return 0; - } - - File delTable = new File(homeDir + "/" + tableToDel); - for (File file : new File(homeDir + "/" + tableToDel).listFiles()) { - if (file.isFile()) { - file.delete(); - } - } - delTable.delete(); - System.out.println(tableToDel + " dropped"); - return 1; // if was deleted - } - - public int useForReader(String homeDir, String numDir) { - File local = new File(homeDir); - String[] list; - list = local.list(); - if (list != null) { - for (int i = 0; i < list.length; i++) { - if (list[i].equals(numDir)) { - return 1; // if exist - } - } - } - return 0; // if n - } - - public int userUse(String homeDir, String table) { - File local = new File(homeDir); - String[] list; - list = local.list(); - if (list != null) { - for (int i = 0; i < list.length; i++) { - if (list[i].equals(table)) { - return 1; // if exist - } - } - } - return 0; // if added - } -} - diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Write.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Write.java deleted file mode 100644 index 1260b4be4..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiDataBase/Write.java +++ /dev/null @@ -1,59 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiDataBase; - -import java.util.*; -import java.io.*; -import java.util.regex.*; - -public class Write { - private String filepath; - - public Write(String path) { - filepath = path; - } - - public void write(Map[] map) throws IOException { - for (Integer i = 0; i < 16; i++) { - if (map[i] != null) { - - for (Integer j = 0; j < 16; j++) { - String local = j.toString() + ".dat"; - File tmp = new File(filepath + "/" + i.toString() + "/" - + local); - tmp.createNewFile(); - try (DataOutputStream out = new DataOutputStream( - new FileOutputStream(filepath + "/" + i.toString() - + "/" + local))) { - Set st = map[i].keySet(); - for (String time : st) { - - String tm = local.replaceAll(".dat", ""); - if ((time.hashCode() / 16 % 16) == Integer - .parseInt(tm)) { - - out.writeInt(time.length()); - out.writeChars(time); - out.writeInt(((String) map[i].get(time)) - .length()); - out.writeChars((String) map[i].get(time)); - } - - } - - } catch (FileNotFoundException e) { - System.err.print("Not Found " + e.toString()); - } catch (IOException e) { - System.err.print("IOException " + e.toString()); - } - if (tmp.length() == 0) { - tmp.delete(); - } - } - } - if (map[i] == null) { - File delTable = new File(filepath + "/" + i.toString()); - - delTable.delete(); - } - } - } -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Functional.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Functional.java deleted file mode 100644 index 252b9f1db..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Functional.java +++ /dev/null @@ -1,58 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; - -import java.io.IOException; -import java.util.*; - -public class Functional { - - void put(Map[] map, int i, String key, String value) { - if (i == -1) { - System.out.println("NotDefBD#"); - return; - } - - if (map[i].containsKey(key)) { - System.out.println("overwrite"); - System.out.println(map[i].get(key)); - } else { - System.out.println("new"); - } - map[i].put(key, value); - } - - void get(Map[] map, int i, String key) { - if (i == -1) { - System.out.println("NotDefBD#"); - return; - } - if (map[i] != null) { - if (map[i].containsKey(key)) { - System.out.println("found"); - System.out.println(map[i].get(key)); - } else { - System.out.println("not found"); - } - } - } - - void remove(Map[] map, int i, String key) { - if (i == -1) { - System.out.println("NotDefBD#"); - return; - } - if (map[i] != null) { - if (map[i].containsKey(key)) { - map[i].remove(key); - } else { - System.out.println("not found"); - } - } - } - - void showtables(TableDriver[] td) throws NullPointerException, IOException { - for (TableDriver time : td) { - - System.out.println("table " + time.getName() + " " + time.size()); - } - } -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/JUnit.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/JUnit.java deleted file mode 100644 index 29641658e..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/JUnit.java +++ /dev/null @@ -1,23 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; - -import java.io.*; -import java.util.*; - -public class JUnit { - public static void main(String[] args) throws IOException { - String path = System.getProperty("fizteh.db.dir").toString(); - TableWork tb = new TableWork(0, path); - Functional fn = new Functional(); - - ModeWork mw = new ModeWork(); - - mw.usermode(fn, tb); - Write wr = new Write(); - for (int i = 0; i < tb.t.length; i++) { - - wr.write(tb.t[i], tb); - } - - }; - -} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/ModeWork.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/ModeWork.java deleted file mode 100644 index edc6c5fbd..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/ModeWork.java +++ /dev/null @@ -1,94 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; - -import java.io.IOException; -import java.util.*; - -class ModeWork { - Functional fn; - - ModeWork() { - fn = new Functional(); - } - - int stepMode(String[] array, TableWork f, int index) - throws NullPointerException, IOException { - - switch (array[0 + index]) { - case "put": - if (f.indicator == -1) - System.out.println("UNDEF"); - else - fn.put(f.t[f.indicator].map, array[1 + index].hashCode() % 16, - array[1 + index], array[2 + index]); - return 2; - case "get": - if (f.indicator == -1) - System.out.println("UNDEF"); - else - fn.get(f.t[f.indicator].map, array[1 + index].hashCode() % 16, - array[1 + index]); - return 1; - case "remove": - if (f.indicator == -1) - System.out.println("UNDEF"); - else - fn.remove(f.t[f.indicator].map, - array[1 + index].hashCode() % 16, array[1 + index]); - return 1; - case "create": - f.create(array[1 + index]); - - return 1; - case "drop": - f.drop(array[1 + index]); - - return 1; - case "use": - if (f.userUse(array[1 + index]) == 0) { - - } else { - - } - - return 1; - - case "showtables": - fn.showtables(f.t); - return 1; - case "exit": - return -1; - default: - System.out.println("Unknow operation. Fail."); - return -1; - } - } - - void usermode(Functional func, TableWork t) throws NullPointerException, - IOException { - - 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, t, 0) == -1) { - break; - } - } - rd.close(); - - } - - /* - * void interactive( Map[] time , String[] mass) { int - * offset = 0; Functional func = new Functional(time); int i = 0; while - * (true) { if (i < mass.length) { offset = stepMode(time,mass, func, i); i - * += offset; if (offset == -1) { break; } i++; } else { break; } } - * - * } - */ - -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Reader.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Reader.java deleted file mode 100644 index 5c991effd..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Reader.java +++ /dev/null @@ -1,95 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; - -import java.util.*; -import java.io.*; - -public class Reader { - - private Map[] map; - - public Reader() { - - } - - public Map[] read(String filepath) { - - map = (Map[]) new Map[16]; - for (int ind = 0; ind < 16; ind++) { - map[ind] = new HashMap(); - } - - int flag = 0; - File alldir = new File(filepath); - String file[] = alldir.list(); - - for (Integer i = 0; i < 16; i++) { - for (int j = 0; j < file.length; j++) { - if (i.toString().equals(file[j].toString())) { - flag = 1; - break; - } - } - if (flag == 1) - - { - - StringBuilder keyBuilder = new StringBuilder(); - StringBuilder valueBuilder = new StringBuilder(); - File localbase = new File(filepath + "\\" + i.toString()); - - String[] list = localbase.list(); - - if (list != null) { - for (String currentDat : list) { - - int length = 0; - try (DataInputStream rd = new DataInputStream( - new FileInputStream(filepath + "\\" - + i.toString() + "\\" + currentDat))) { - while (true) { - try { - length = rd.readInt(); - for (int k = 0; k < length; k++) { - keyBuilder.append(rd.readChar()); - - } - length = rd.readInt(); - for (int k = 0; k < length; k++) { - valueBuilder.append(rd.readChar()); - - } - map[i].put(keyBuilder.toString(), - valueBuilder.toString()); - keyBuilder.replace(0, keyBuilder.length(), - ""); - valueBuilder.replace(0, - valueBuilder.length(), ""); - if (i == 15) { - - } - } 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()); - } - } - } - } - flag = 0; - } - - return map; - } - -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableDriver.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableDriver.java deleted file mode 100644 index 115cba42e..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableDriver.java +++ /dev/null @@ -1,37 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; - -import java.util.HashMap; -import java.util.Map; - -public class TableDriver { - private String name; - public Map[] map; - - TableDriver() { - - } - - TableDriver(String name) { - this.name = name; - map = (Map[]) new Map[16]; - for (int i = 0; i < 16; i++) { - map[i] = new HashMap(); - } - - } - - public int size() { - int summ = 0; - if (map != null) { - for (int i = 0; i < 16; i++) { - if (map[i] != null) - summ += map[i].size(); - } - } - return summ; - } - - public String getName() { - return name; - } -} \ No newline at end of file diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableWork.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableWork.java deleted file mode 100644 index 59b62cbea..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/TableWork.java +++ /dev/null @@ -1,157 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; - -import java.io.*; -import java.util.*; - -public class TableWork { - public TableDriver t[]; - String homeDir; - int indicator; - int size; - - TableWork(int size, String homeDir) { - Reader rd = new Reader(); - this.size = 0; - File input = new File(homeDir); - String[] st; - st = input.list(); - if (st != null) { - for (String path : st) { - - File tm2 = new File(homeDir + "\\" + path); - - if (tm2.list() != null) { - - if (size == 0) { - t = new TableDriver[1]; - t[0] = new TableDriver(path); - t[0].map = rd.read(homeDir + "\\" + path); - - } else { - TableDriver temp[] = new TableDriver[t.length + 1]; - for (int k = 0; k < t.length; k++) - temp[k] = t[k]; - - temp[t.length] = new TableDriver(path); - temp[t.length].map = rd.read(homeDir + "\\" + path); - - t = temp; - } - size++; - } - - } - } - - this.homeDir = homeDir; - - indicator = -1; - } - - public int setDir = -1; // by default - - public int getset() { - return setDir; - } - - public int create(String tableToAdd) throws NullPointerException { - - if (t != null) { - for (int i = 0; i < t.length; i++) { - if (tableToAdd.equals(t[i].getName())) { - System.out.println("exist!"); - return 1; - } - } - ; - { - - TableDriver temp[] = new TableDriver[t.length + 1]; - for (int k = 0; k < t.length; k++) - temp[k] = t[k]; - - temp[t.length] = new TableDriver(tableToAdd); - t = temp; - System.out.println("created"); - } - } - - if (t == null || size == 0) { - t = new TableDriver[1]; - t[0] = new TableDriver(tableToAdd); - } - System.out.println("created"); - size++; - return 0; // if added - } - - public void remove(File anyfile) { - if (!anyfile.exists()) - return; - if (anyfile.isDirectory()) { - for (File f : anyfile.listFiles()) - remove(f); - anyfile.delete(); - } else { - anyfile.delete(); - } - } - - public void drop(String tableToDel) throws NullPointerException, - IOException { - int haveDir = 0; - for (int i = 0; i < t.length; i++) { - if (t[i] != null && tableToDel.equals(t[i].getName()) == true) { - - if (t.length != 1) { - TableDriver tm = new TableDriver(); - t[i] = t[t.length - 1]; - t[t.length - 1] = null; - - } else - t[i] = null; - size--; - System.out.println(tableToDel + " dropped"); - File in = new File(homeDir); - String st[] = in.list(); - - if (st != null) { - for (String time : st) { - if (time.equals(tableToDel)) { - - in = new File(homeDir + "\\" + tableToDel); - - remove(in); - - } - - } - } - - // if was deleted - break; - } - - } - if (haveDir == 0) { - System.out.println("not exists"); - - } - - } - - public int userUse(String tablename) throws NullPointerException { - if (t != null && t[0] != null) - for (int i = 0; i < t.length; i++) { - if (t[i].getName().equals(tablename)) { - indicator = i; - System.out.println("use"); - return 0; - } - } - System.out.println("not exist"); - return 1; - - } - -} diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Write.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Write.java deleted file mode 100644 index ef81ade64..000000000 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/MultiFileHashMap v2.0/Write.java +++ /dev/null @@ -1,72 +0,0 @@ -package ru.fizteh.fivt.students.AndrewTimokhin.MultiFileHashMap; - -import java.util.*; -import java.io.*; -import java.util.regex.*; - -public class Write { - private String filepath; - - public Write() { - - } - - public void write(TableDriver tm, TableWork tb) throws IOException { - if (tm != null) { - filepath = tb.homeDir + "\\" + tm.getName(); - File time2 = new File(filepath); - time2.mkdir(); - - for (Integer i = 0; i < 16; i++) { - if (tm.map[i] != null) { - - for (Integer j = 0; j < 16; j++) { - String local = j.toString() + ".dat"; - - File tmp0 = new File(filepath + "\\" + i.toString()); - tmp0.mkdir(); - - File tmp = new File(filepath + "\\" + i.toString() - + "\\" + local); - tmp.createNewFile(); - try (DataOutputStream out = new DataOutputStream( - new FileOutputStream(filepath + "\\" - + i.toString() + "\\" + local))) { - Set st = tm.map[i].keySet(); - for (String time : st) { - - String tr = local.replaceAll(".dat", ""); - if ((time.hashCode() / 16 % 16) == Integer - .parseInt(tr)) { - - out.writeInt(time.length()); - out.writeChars(time); - out.writeInt(((String) tm.map[i].get(time)) - .length()); - out.writeChars((String) tm.map[i].get(time)); - } - - } - - } catch (FileNotFoundException e) { - System.err.print("Not Found " + e.toString()); - } catch (IOException e) { - System.err.print("IOException " + e.toString()); - } - if (tmp.length() == 0) { - tmp.delete(); - } - } - File tmp0 = new File(filepath + "\\" + i.toString()); - if (tmp0.list().length == 0) - tmp0.delete(); - } - if (tm.map[i] == null) { - File delTable = new File(filepath + "\\" + i.toString()); - - delTable.delete(); - } - } - } - } -} From 93aca57f8680c203b60330a744c70b32e491233d Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Tue, 3 Feb 2015 05:10:24 +0300 Subject: [PATCH 14/18] Update Main.java --- .../fivt/students/AndrewTimokhin/FileMap/JUnit/Main/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index 3df876339..6d7ed9ba0 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/Main.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/Main.java @@ -11,7 +11,7 @@ public class Main { public static void main(String[] args) throws IOException, IllegalArgumentException, KeyNullAndNotFound, UnknownCommand { - InteractiveMode user = new InteractiveMode("C:\\DataBase", new Commands()); + InteractiveMode user = new InteractiveMode(System.getProperty("db.file").toString(), new Commands()); Scanner sc = new Scanner(System.in); System.out.print("$ "); try { From 44da6c6251b5aea6f398d1e122a28d7d606bb29d Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Tue, 3 Feb 2015 05:11:17 +0300 Subject: [PATCH 15/18] Update KeyNullAndNotFound.java --- .../AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java index 2e7cad278..e21aa3a50 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java @@ -1,6 +1,5 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; -@SuppressWarnings("serial") public class KeyNullAndNotFound extends Exception { public KeyNullAndNotFound(String description) { From b5fae6b74c4dd0ed2ec48232eeb114cfd2c7c689 Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Wed, 4 Feb 2015 05:08:59 +0300 Subject: [PATCH 16/18] *FINAL* --- .../FileMap/DataBase/ConstantValue.java | 16 ++++ .../FileMap/DataBase/DeleteAlgorithm.java | 28 +++++++ .../FileMap/DataBase/KeyNullAndNotFound.java | 1 - .../FileMap/DataBase/Reader.java | 40 +++------- .../FileMap/DataBase/Table.java | 2 + .../FileMap/DataBase/TableImplement.java | 79 ++++++------------- .../DataBase/TableProviderImplements.java | 52 +++--------- .../FileMap/DataBase/Writer.java | 46 +++-------- .../FileMap/JUnit/Interpretator/Commands.java | 58 ++------------ .../JUnit/Interpretator/InteractiveMode.java | 28 +++---- .../UnknownCommandException.java | 18 +++++ .../FileMap/JUnit/Main/CommitCommand.java | 9 ++- .../FileMap/JUnit/Main/CreateCommand.java | 8 +- .../FileMap/JUnit/Main/DropCommand.java | 14 ++-- .../FileMap/JUnit/Main/ExitCommand.java | 18 ++++- .../FileMap/JUnit/Main/ExitException.java | 17 ++++ .../FileMap/JUnit/Main/GetCommand.java | 10 ++- .../FileMap/JUnit/Main/ListCommand.java | 10 ++- .../FileMap/JUnit/Main/Main.java | 67 ++++++++++++++-- .../FileMap/JUnit/Main/PutCommand.java | 10 ++- .../FileMap/JUnit/Main/RemoveCommand.java | 12 ++- .../FileMap/JUnit/Main/RollbackCommand.java | 8 +- .../FileMap/JUnit/Main/SizeCommand.java | 11 +-- .../FileMap/JUnit/Main/UnknowCommand.java | 29 +++++++ .../FileMap/JUnit/Main/UseCommand.java | 8 +- 25 files changed, 334 insertions(+), 265 deletions(-) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/ConstantValue.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/DeleteAlgorithm.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/UnknownCommandException.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitException.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UnknowCommand.java 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/KeyNullAndNotFound.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java index 2e7cad278..e21aa3a50 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java @@ -1,6 +1,5 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.DataBase; -@SuppressWarnings("serial") public class KeyNullAndNotFound extends Exception { public KeyNullAndNotFound(String 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 index 6edda445e..28816afeb 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Reader.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Reader.java @@ -15,44 +15,33 @@ * * @author Timokhin Andrew */ -public class Reader { +public class Reader implements ConstantValue { - static final int TOTAL_SUB_STRING = 16; - static final String DIRECT = ".dir"; - private final String directory; - - public Reader(String directory) { - this.directory = directory; - } - - private void readKeyValue(DataInputStream rd, StringBuilder string) throws IOException { + 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()); + string.append(rd.readChar()); } + return string; } public void read(TableProviderImplements tp) throws IOException { - StringBuilder keyBuilder = new StringBuilder(); - StringBuilder valueBuilder = new StringBuilder(); - int length; + StringBuilder keyBuilder; + StringBuilder valueBuilder; String path = tp.getDir(); - boolean dbExist = false; 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()) { - dbExist = true; tp.createTable(time); TableImplement dataBase = (TableImplement) tp.getTable(time); dataBase.setPath(tp.getDir()); for (int i = 0; i < TOTAL_SUB_STRING; i++) { - Integer numberDir = new Integer(i); Path pathToDb = Paths.get(path, time, - numberDir.toString() + DIRECT); + i + DIRECTORY_SUFFIX); File locDB = new File(pathToDb.toString()); if (locDB.exists()) { for (String file : locDB.list()) { @@ -63,8 +52,8 @@ public void read(TableProviderImplements tp) throws IOException { pathToLocalDb.toString()))) { while (true) { try { - readKeyValue(rd, keyBuilder); - readKeyValue(rd, valueBuilder); + keyBuilder = readKeyValue(rd); + valueBuilder = readKeyValue(rd); dataBase.put( keyBuilder.toString(), @@ -75,14 +64,14 @@ public void read(TableProviderImplements tp) throws IOException { keyBuilder.replace(0, keyBuilder.length(), ""); valueBuilder.replace(0, - valueBuilder.length(), ""); + valueBuilder.length(), ""); } catch (EOFException e) { rd.close(); break; } } - } catch (FileNotFoundException exceptionFileNotFound) { + } catch (FileNotFoundException exceptionFileNotFound) { throw new RuntimeException( exceptionFileNotFound); } @@ -92,10 +81,5 @@ public void read(TableProviderImplements tp) throws IOException { } } } - if (!dbExist) { - return; - } - - return; } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Table.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Table.java index 5b813fe1b..1e48afe75 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Table.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Table.java @@ -6,6 +6,8 @@ public interface Table { /** * Возвращает название базы данных. + * + * @return name representing database */ String getName(); diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableImplement.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableImplement.java index aa710366f..910fbe776 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableImplement.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableImplement.java @@ -19,16 +19,13 @@ public class TableImplement implements Table { private String path; private Map map; private Map backup; - private Map current; public TableImplement(String name, String path) { this.path = path; this.name = name; - map = new HashMap(); - backup = new HashMap(); - current = new HashMap(); - - } + map = new HashMap<>(); + backup = new HashMap<>(); + } public String getPath() { return path; @@ -36,17 +33,12 @@ public String getPath() { public void setPath(String newPath) { this.path = newPath; - return; } public Map getBackup() { return backup; } - public void setBackup(Map backup) { - this.backup = backup; - } - public void setName(String name) { this.name = name; } @@ -66,10 +58,8 @@ public String get(String key) throws KeyNullAndNotFound { if (key == null) { throw new KeyNullAndNotFound("Key is null"); } - if (map != null) { - if (map.containsKey(key)) { - return map.get(key); - } + if (map.containsKey(key)) { + return map.get(key); } return null; } @@ -81,7 +71,7 @@ public String put(String key, String value) throws IllegalArgumentException { throw new IllegalArgumentException( "Key or (and) value is wrong."); } - if (map != null) { + { if (map.containsKey(key)) { previousValue = map.get(key); } @@ -105,21 +95,11 @@ public String remove(String key) throws IllegalArgumentException { @Override public List list() { - Set time; - if (map != null) { - return new ArrayList(map.keySet()); - } - return new ArrayList(); + return new ArrayList<>(map.keySet()); } public int totalChanges() { int counter = 0; - if (backup == null && map == null) { - return 0; - } - if (backup != null && map == null) { - return backup.size(); - } if (backup == null && map != null) { return map.size(); } @@ -146,61 +126,55 @@ public int totalChanges() { public int commit() { try { return this.writeToDisk(); - } catch (IOException ioexcptn) { - throw new RuntimeException(ioexcptn); + } catch (IOException exception) { + throw new RuntimeException(exception); } } public int writeToDisk() throws IOException, IllegalArgumentException { - boolean flagIfBaseExist = false; - Reader reader = new Reader(this.path); + 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() != null) { { 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( - (String) tableProvider.getTable(this.getName()).get(copyString))); - } catch (KeyNullAndNotFound exception) { - continue; - } + 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); } + this.backup = new HashMap<>(tmp); } else { tableProvider.createTable(this.name); - this.backup = new HashMap(); + 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))); + tableProvider.getTable(this.getName()).put(new String(timeString), new String(this.get(timeString))); } catch (KeyNullAndNotFound ex) { continue; } } - flagIfBaseExist = true; } - } if (this.totalChanges() > 0) { try { writer.write(tableProvider); } catch (KeyNullAndNotFound nullKey) { - System.out.println(nullKey.toString()); + System.out.println(nullKey.toString()); } } return this.totalChanges(); @@ -208,11 +182,11 @@ public int writeToDisk() throws IOException, IllegalArgumentException { @Override public int rollback() throws NullPointerException { - Map copyMap = new HashMap(this.map); + Map copyMap = new HashMap<>(this.map); if (this.backup != null) { - this.map = new HashMap(this.backup); + this.map = new HashMap<>(this.backup); } else { - this.map = new HashMap(); + this.map = new HashMap<>(); } this.backup = copyMap; return this.commit(); @@ -224,7 +198,6 @@ private void copyOfMap(Map from, Map to) { timeMap.put(new String(timeKey), new String(from.get(timeKey))); } to = new HashMap(timeMap); - return; } } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderImplements.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderImplements.java index 1e70c1fb4..455b49972 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderImplements.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderImplements.java @@ -11,15 +11,15 @@ /** * @author Timokhin Andrew */ -public class TableProviderImplements implements TableProvider { +public class TableProviderImplements implements TableProvider, DeleteAlgorithm { - private Map collection; + private final Map collection; private final String dir; - TableProviderImplements(String dir) throws IOException { + public TableProviderImplements(String dir) throws IOException { this.dir = dir; - collection = new HashMap(); - Reader rd = new Reader(new String(this.dir)); + collection = new HashMap<>(); + Reader rd = new Reader(); rd.read(this); } @@ -27,23 +27,6 @@ public Set getAvailableTables() { return collection.keySet(); } - public static void deleteDir(File dir) { - if (dir.isDirectory()) { - String[] children = dir.list(); - for (String childName : children) { - deleteDir(new File(dir, childName)); - } - dir.delete(); - } else { - dir.delete(); - } - } - - public void write() throws IOException, KeyNullAndNotFound { - Writer writeToFileSystem = new Writer(); - writeToFileSystem.write(this); - } - @Override public Table getTable(String name) throws IllegalArgumentException { if (name == null) { @@ -62,19 +45,13 @@ public Table createTable(String name) throws IllegalArgumentException { throw new IllegalArgumentException( "Name of DataBase is null. Please, enter correct name"); } - if (collection != null) { - if (collection.containsKey(name)) { - return null; - } - collection.put(name, new TableImplement(name, dir)); - return collection.get(name); - } - if (collection == null) { - collection = new HashMap<>(); - collection.put(name, new TableImplement(name, dir)); - return collection.get(name); + + if (collection.containsKey(name)) { + return null; } - return null; + collection.put(name, new TableImplement(name, dir)); + return collection.get(name); + } @Override @@ -84,16 +61,13 @@ public void removeTable(String name) throws IllegalArgumentException, throw new IllegalArgumentException( "Name of DataBase is null. Please, enter correct name"); } - if (collection != null) { if (collection.containsKey(name)) { - Path path = Paths.get( - collection.get(name).getPath().toString(), collection + Path path = Paths.get(collection.get(name).getPath(), collection .get(name).getName()); File file = new File(path.toString()); - this.deleteDir(file); + this.deleteDirectory(file); collection.remove(name); return; - } } throw new IllegalStateException("Requested database don't exist"); } diff --git a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Writer.java b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Writer.java index 3deff6655..f8d91d242 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Writer.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Writer.java @@ -17,10 +17,7 @@ * * @author Timokhin Andrew */ -public class Writer { - - final int totalSubDir = 16; - final String dirct = ".dir"; +public class Writer implements ConstantValue, DeleteAlgorithm { boolean checkDir(String name) { File tmpFile = new File(name); @@ -31,36 +28,20 @@ boolean checkDir(String name) { void createDir(String path) { File tmpDir = new File(path); tmpDir.mkdir(); - return; } void createFile(String path) throws IOException { File tmpFile = new File(path); - File prepareToMakeDir = new File(tmpFile.getParent().toString()); + File prepareToMakeDir = new File(tmpFile.getParent()); prepareToMakeDir.mkdirs(); tmpFile.createNewFile(); - return; - } - - public void deleteDirectory(File dir) { - if (dir.isDirectory()) { - String[] children = dir.list(); - for (int i = 0; i < children.length; i++) { - File tmpFile = new File(dir, children[i]); - deleteDirectory(tmpFile); - } - dir.delete(); - } else { - dir.delete(); - } } public void write(TableProviderImplements tp) throws IOException, KeyNullAndNotFound { this.deleteDirectory(new File(tp.getDir())); File baseDir = new File(tp.getDir()); baseDir.mkdir(); - if (tp.getAvailableTables() != null) { Set dataBase = tp.getAvailableTables(); for (String name : dataBase) { TableImplement ti = (TableImplement) tp.getTable(name); @@ -72,15 +53,15 @@ public void write(TableProviderImplements tp) throws IOException, KeyNullAndNotF keyList = (ArrayList) ti.list(); for (String keyFind : keyList) { Integer dirToWrite = new Integer(abs(keyFind.hashCode() - % totalSubDir)); + % TOTAL_SUB_STRING)); Path localPath = Paths.get(tp.getDir(), ti.getName(), - dirToWrite.toString() + dirct); + dirToWrite.toString() + DIRECTORY_SUFFIX); if (!this.checkDir(localPath.toString())) { this.createDir(localPath.toString()); } dirToWrite = new Integer((ti.get(keyFind) .hashCode() - % totalSubDir % totalSubDir)); + % TOTAL_SUB_STRING % TOTAL_SUB_STRING)); Path localFile = Paths.get(localPath.toString(), dirToWrite.toString()); File checkIfExist = new File(localFile.toString()); @@ -89,25 +70,20 @@ public void write(TableProviderImplements tp) throws IOException, KeyNullAndNotF this.createFile(localFile.toString()); } - DataOutputStream outStream = new DataOutputStream( - new FileOutputStream(localFile.toString(), true)); - outStream.writeInt(keyFind.length()); - outStream.writeChars(keyFind); - try { + 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()); - } catch (NullPointerException nullPointer) { - throw nullPointer; - } finally { - outStream.close(); } } } } - } - return; } } 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 index f13667922..39dd55a02 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/Commands.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/Commands.java @@ -5,71 +5,27 @@ */ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator; -import java.util.HashMap; -import java.util.Map; 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.Main.CommitCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.CreateCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.DropCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.ExitCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.GetCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.ListCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.PutCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.RemoveCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.RollbackCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.SizeCommand; -import ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Main.UseCommand; /** * * @author Андрей */ -public class Commands { +public abstract class Commands { - int digital; - public static TableImplement currentTable; - private Map totalCommands; + int numberOfArguments; - public Commands(int digital) { - this.digital = digital; + public Commands(int numberOfArgumentsSet) { + numberOfArguments = numberOfArgumentsSet; } - public Commands() { - } - - public Map getAllCommand() { - 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()); - return totalCommands; - } - - public boolean checkAndRun(String[] command, TableProviderImplements table) { - if (this.invitationToRepeat(command, digital)) { - return true; - } - return this.execute(command, table); - - } - - public boolean execute(String[] command, TableProviderImplements table) { - return true; - } + 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, int checkValue) { + public boolean invitationToRepeat(String[] args) { - if (args.length != checkValue) { + if (args.length != numberOfArguments) { System.out .println("Current command was not recognized or not complete. Please, try again"); return true; 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 index 44298319b..547a70937 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/InteractiveMode.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/InteractiveMode.java @@ -6,10 +6,8 @@ package ru.fizteh.fivt.students.AndrewTimokhin.FileMap.JUnit.Interpretator; import java.util.Map; -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.JUnit.Main.UnknowCommand; /** * @@ -17,27 +15,23 @@ * */ public class InteractiveMode { - - private final TableProviderImplements provider; - private final FactoryImplements factory; - private TableImplement table; - private String currentDir; - private Map allCommand; - public InteractiveMode(String path, Commands command) { - allCommand = command.getAllCommand(); - factory = new FactoryImplements(); - provider = (TableProviderImplements) factory.create(path); + private final Map allCommand; + private final Commands fail; + + public InteractiveMode(Map allCommand) { + this.allCommand = allCommand; + fail = new UnknowCommand(); } - public boolean command(String textToParser) throws UnknownCommand, + 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("Wrong command!"); - return true; + System.out.println("Details: Wrong command!"); + return fail; } - return allCommand.get(commands[0]).checkAndRun(commands, provider); + 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 index 6b07a72cb..209a23d2c 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CommitCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CommitCommand.java @@ -5,6 +5,7 @@ */ 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; @@ -19,12 +20,16 @@ public CommitCommand() { } @Override - public boolean execute(String[] commands, TableProviderImplements tableProvider) { + 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 true; + 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 index 2487edabf..2452cc8fb 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CreateCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CreateCommand.java @@ -5,6 +5,7 @@ */ 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; @@ -19,13 +20,16 @@ public CreateCommand() { } @Override - public boolean execute(String[] commands, TableProviderImplements tableProvider) { + 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 true; + 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 index 88c72bb70..6477940ce 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/DropCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/DropCommand.java @@ -5,6 +5,7 @@ */ 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; @@ -19,16 +20,17 @@ public DropCommand() { } @Override - public boolean execute(String[] commands, TableProviderImplements tableProvider) { + 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 error) { - System.out.println("Not exists"); - } catch (IllegalArgumentException error) { - System.out.println(error); + } catch (IllegalStateException | IllegalArgumentException error) { + throw error; } - return true; + 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 index de7011e28..f8fb8d792 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitCommand.java @@ -5,6 +5,7 @@ */ 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; @@ -18,9 +19,22 @@ 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 boolean execute(String[] commands, TableProviderImplements tableProvider) { - return false; + 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 index a81e7941e..f4aa6d36f 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/GetCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/GetCommand.java @@ -7,6 +7,7 @@ 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; /** @@ -20,10 +21,13 @@ public GetCommand() { } @Override - public boolean execute(String[] commands, TableProviderImplements tableProvider) { + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } if (currentTable == null) { System.out.println("No table"); - return true; + return null; } else { String value; try { @@ -38,7 +42,7 @@ public boolean execute(String[] commands, TableProviderImplements tableProvider) } } - return true; + 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 index a2e904245..5e2760aa0 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ListCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ListCommand.java @@ -8,6 +8,7 @@ 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; /** @@ -21,10 +22,13 @@ public ListCommand() { } @Override - public boolean execute(String[] commands, TableProviderImplements tableProvider) { + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } if (currentTable == null) { System.out.println("No table"); - return true; + return null; } else { ArrayList set; set = (ArrayList) currentTable.list(); @@ -36,7 +40,7 @@ public boolean execute(String[] commands, TableProviderImplements tableProvider) } } } - return true; + 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 index 3df876339..830dbc19f 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/Main.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/Main.java @@ -2,24 +2,77 @@ 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.UnknownCommand; +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, UnknownCommand { - InteractiveMode user = new InteractiveMode("C:\\DataBase", new Commands()); + 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 (user.command(sc.nextLine())) { + while (true) { + String commands = sc.nextLine(); + + Main.table = user.runCommand(commands).execute(commands.trim().split(" "), Main.provider, Main.table); System.out.print("$ "); - } - } catch (UnknownCommand ex) { - System.out.println("Unknow operation. Fail"); + } + + } 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 index 8961b239c..17704b198 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/PutCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/PutCommand.java @@ -5,6 +5,7 @@ */ 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; @@ -19,10 +20,13 @@ public PutCommand() { } @Override - public boolean execute(String[] commands, TableProviderImplements tableProvider) { + public TableImplement execute(String[] commands, TableProviderImplements provider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } if (currentTable == null) { System.out.println("No table"); - return true; + return null; } else { String oldValue = currentTable.put(commands[1], commands[2]); if (oldValue != null) { @@ -31,7 +35,7 @@ public boolean execute(String[] commands, TableProviderImplements tableProvider) System.out.println("*new*"); } } - return true; + 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 index 0fd91bc67..972b38685 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RemoveCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RemoveCommand.java @@ -5,6 +5,7 @@ */ 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; @@ -19,14 +20,17 @@ public RemoveCommand() { } @Override - public boolean execute(String[] commands, TableProviderImplements tableProvider) { + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; + } if (currentTable == null) { System.out.println("No table"); - return true; + return null; } else { if (commands[1] == null) { System.out.println("*wrong key"); - return true; + return currentTable; } String value = currentTable.remove(commands[1]); if (value != null) { @@ -35,7 +39,7 @@ public boolean execute(String[] commands, TableProviderImplements tableProvider) System.out.println("*not removed, because not exist*"); } } - return true; + 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 index 18dbfa2f7..d5591b7fc 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RollbackCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RollbackCommand.java @@ -5,6 +5,7 @@ */ 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; @@ -19,14 +20,17 @@ public RollbackCommand() { } @Override - public boolean execute(String[] commands, TableProviderImplements tableProvider) { + 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 true; + 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 index 03ca5ca70..640bbf4ed 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/SizeCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/SizeCommand.java @@ -5,6 +5,7 @@ */ 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; @@ -19,12 +20,12 @@ public SizeCommand() { } @Override - public boolean execute(String[] commands, TableProviderImplements tableProvider) { - - { - System.out.println(tableProvider.size()); + public TableImplement execute(String[] commands, TableProviderImplements tableProvider, TableImplement currentTable) { + if (invitationToRepeat(commands)) { + return currentTable; } - return true; + 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 index cecb94e9c..3578d2f72 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UseCommand.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UseCommand.java @@ -20,9 +20,13 @@ public UseCommand() { } @Override - public boolean execute(String[] commands, TableProviderImplements tableProvider) { + 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 { @@ -32,7 +36,7 @@ public boolean execute(String[] commands, TableProviderImplements tableProvider) System.out.println("Using"); } } - return true; + return currentTable; } } From 7ad5cb3455ca505f2ec16615d2ec223b10ecf942 Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Wed, 4 Feb 2015 05:11:11 +0300 Subject: [PATCH 17/18] *FINAL_VERSION* --- .../FileMap/DataBase/ConstantValue.java | 16 ++ .../FileMap/DataBase/DeleteAlgorithm.java | 28 ++ .../FileMap/DataBase/FactoryImplements.java | 26 ++ .../FileMap/DataBase/KeyNullAndNotFound.java | 8 + .../FileMap/DataBase/Reader.java | 85 ++++++ .../FileMap/DataBase/Table.java | 77 +++++ .../FileMap/DataBase/TableImplement.java | 203 ++++++++++++++ .../FileMap/DataBase/TableProvider.java | 37 +++ .../DataBase/TableProviderFactory.java | 14 + .../DataBase/TableProviderImplements.java | 86 ++++++ .../FileMap/DataBase/Writer.java | 89 ++++++ .../FileMap/JUnit/Interpretator/Commands.java | 36 +++ .../JUnit/Interpretator/InteractiveMode.java | 37 +++ .../UnknownCommandException.java | 18 ++ .../FileMap/JUnit/Main/CommitCommand.java | 35 +++ .../FileMap/JUnit/Main/CreateCommand.java | 35 +++ .../FileMap/JUnit/Main/DropCommand.java | 36 +++ .../FileMap/JUnit/Main/ExitCommand.java | 40 +++ .../FileMap/JUnit/Main/ExitException.java | 17 ++ .../FileMap/JUnit/Main/GetCommand.java | 48 ++++ .../FileMap/JUnit/Main/ListCommand.java | 46 +++ .../FileMap/JUnit/Main/Main.java | 78 ++++++ .../FileMap/JUnit/Main/PutCommand.java | 41 +++ .../FileMap/JUnit/Main/RemoveCommand.java | 45 +++ .../FileMap/JUnit/Main/RollbackCommand.java | 36 +++ .../FileMap/JUnit/Main/SizeCommand.java | 31 +++ .../FileMap/JUnit/Main/UnknowCommand.java | 29 ++ .../FileMap/JUnit/Main/UseCommand.java | 42 +++ .../JUnit/test/FactoryImplementsTest.java | 29 ++ .../JUnit/test/TableImplementTest.java | 262 ++++++++++++++++++ .../test/TableProviderImplementsTest.java | 91 ++++++ 31 files changed, 1701 insertions(+) create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/ConstantValue.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/DeleteAlgorithm.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/FactoryImplements.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/KeyNullAndNotFound.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Reader.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Table.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableImplement.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProvider.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderFactory.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/TableProviderImplements.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/DataBase/Writer.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/Commands.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/InteractiveMode.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Interpretator/UnknownCommandException.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CommitCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/CreateCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/DropCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ExitException.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/GetCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/ListCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/Main.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/PutCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RemoveCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/RollbackCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/SizeCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UnknowCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/Main/UseCommand.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/FactoryImplementsTest.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableImplementTest.java create mode 100644 src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableProviderImplementsTest.java 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..814190111 --- /dev/null +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableImplementTest.java @@ -0,0 +1,262 @@ +/* + * Модульные тесты базы данных. + * + */ +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())); + } + + /** + * Тесты на 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")); + } +} From 45290a2595817f3f2f1a588208ec5c531d5fb294 Mon Sep 17 00:00:00 2001 From: AndrewTimokhin Date: Wed, 4 Feb 2015 06:57:40 +0300 Subject: [PATCH 18/18] *some changes* --- .../FileMap/JUnit/test/TableImplementTest.java | 5 +++++ 1 file changed, 5 insertions(+) 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 index 814190111..7ef43ddb6 100644 --- a/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableImplementTest.java +++ b/src/ru/fizteh/fivt/students/AndrewTimokhin/FileMap/JUnit/test/TableImplementTest.java @@ -53,6 +53,11 @@ public void testGetName() { assertTrue("testing".equals(table.getName())); } + @Test(expected = KeyNullAndNotFound.class) + public void testGetNullKey() throws KeyNullAndNotFound { + table.get(null); + } + /** * Тесты на size method */