Skip to content
This repository was archived by the owner on Sep 27, 2022. It is now read-only.
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package ru.fizteh.fivt.students.dmitry_morozov.junit;

public class BadDBFileException extends Exception {

public BadDBFileException(String msg) {
super(msg);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package ru.fizteh.fivt.students.dmitry_morozov.junit;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Всё в этом файле - полный ад. Перепроектировать.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Даже если будете оставлять, то прочитайте про возможности enum-ов в Джаве и сделайте честные enum-ы-объекты


enum CommandName {
PUT, REMOVE
};

public class ChangingCommand {
public CommandName cName;
public String[] args;

public ChangingCommand(CommandName c, String arg1, String arg2) {
cName = c;
if (cName == CommandName.PUT) {
args = new String[2];
args[0] = arg1;
args[1] = arg2;
}
if (cName == CommandName.REMOVE) {
args = new String[1];
args[0] = arg1;
}
}

}
96 changes: 96 additions & 0 deletions src/ru/fizteh/fivt/students/dmitry_morozov/junit/DBCollection.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package ru.fizteh.fivt.students.dmitry_morozov.junit;

import java.util.List;
import java.io.File;
import java.io.IOException;

import ru.fizteh.fivt.storage.strings.Table;
import ru.fizteh.fivt.storage.strings.TableProvider;

public class DBCollection implements TableProvider {
private String dirPath;
private FileMap maps;

public DBCollection(String dirPath) throws IllegalArgumentException {
this.dirPath = dirPath;
maps = null;
if (dirPath == null) {
throw new IllegalArgumentException("path is null");
}
if (dirPath.endsWith("/") && !dirPath.equals("/")) {
String tmp = "";
for (int i = 0; i < dirPath.length() - 1; i++) {
tmp += dirPath.charAt(i);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Найдите в стандартной библиотеке функцию вырезания подстроки.

}
dirPath = tmp;
}
try {
maps = new FileMap(dirPath + "/tables_info.dat");
} catch (BadDBFileException | IOException e) {
throw new IllegalArgumentException(e.getMessage());
}
}

public List<String> showTables() { // Actually doesn't
// throw anything.
return maps.list();
}

@Override
public Table getTable(String name) throws IllegalArgumentException {
String fullPath = maps.get(name);
if (fullPath == null) {
return null;
}
Table res;
try {
res = new ReversableMFHM(name);
} catch (BadDBFileException e) {
throw new IllegalArgumentException(e.getMessage());
}
return res;
}

@Override
public Table createTable(String name) {
// TODO Auto-generated method stub
if (maps.get(name) != null) {
return null;
}
maps.put(name, dirPath + "/" + name);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

http://stackoverflow.com/questions/711993/does-java-have-a-path-joining-method
Исправить. Ваше решение не кросс-платформенно.

File dir = new File(dirPath + "/" + name);
if (!dir.mkdirs()) {
throw new IllegalArgumentException();
}
ReversableMFHM res;
try {
res = new ReversableMFHM(dirPath + "/" + name);
} catch (BadDBFileException e) {
maps.remove(name);
throw new IllegalStateException();
}
return res;
}

@Override
public void removeTable(String name) {
String tname = maps.get(name);
if (tname != null) { // Database found.
if (!Utils.removeDirectory(tname)) {
System.err.println("deleting table from disk failed");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Библиотечный класс не должен ничего печатать на потоки вывода. Бросайте исключения.

} else {
maps.remove(name);
}
} else { // Database not found.
throw new IllegalStateException();
}
}

public void emeregencyExit() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

emergency - там нет "e" после "r" )

try {
maps.exit();
} catch (IOException e) {
e.printStackTrace();
}
}
}
198 changes: 198 additions & 0 deletions src/ru/fizteh/fivt/students/dmitry_morozov/junit/FileMap.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
package ru.fizteh.fivt.students.dmitry_morozov.junit;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import ru.fizteh.fivt.storage.strings.Table;

public class FileMap implements Table {
private Map<String, String> table;
private File dbFile;

public FileMap(String path) throws BadDBFileException, IOException {
table = new HashMap<>();
dbFile = new File(path);
if (!dbFile.exists()) {
if (!dbFile.createNewFile()) {
throw new BadDBFileException("Couldldn't create db file");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Couldldn't - опечатка)

}
} else {
if (!dbFile.isFile()) {
throw new BadDBFileException("Is not a file");
}
}
if (!(dbFile.setReadable(true)) && dbFile.setWritable(true)) {
throw new BadDBFileException("Couldn't set rw options");
}
DataInputStream in = new DataInputStream(new FileInputStream(dbFile));

while (true) {
String key = readString(in);
if (key == null) {
break;
}
String value = readString(in);
if (value == null) {
in.close();
throw new BadDBFileException("Couldn't set rw options");
}
table.put(key, value);
}
in.close();

}

/**
* @return String read from file. If meets end of file, returns null.
* @throws BadDBFileException
* @throws IOException
* */

private String readString(DataInputStream in) throws IOException,
BadDBFileException {
final int sizeOfInt = 4;
int len;
String res = "";
if (in.available() >= sizeOfInt) {
len = in.readInt();
if (0 != len % 2 || in.available() < len) {
in.close();
throw new BadDBFileException("File was damaged");
}
len /= 2;
while (len > 0) {
char curChar = in.readChar();
res += curChar;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Используйте StringBuilder. Ваше решение порождает слишком много лишних промежуточных строк.

len--;
}
} else {
return null;
}
return res;
}

public String put(String key, String value) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException();
}
String res = table.get(key);
table.put(key, value);
return res;
}

public String get(String key) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException();
}
String val = table.get(key);
return val;
}

public String clearGet(String key) {
return table.get(key);
}

public List<String> list() {
List<String> res = new ArrayList<>();
Set<Entry<String, String>> tableSet = table.entrySet();
for (Entry<String, String> i : tableSet) {
res.add(i.getKey());
}
return res;
}

public void printList(PrintWriter pw) {
Set<Entry<String, String>> tableSet = table.entrySet();
Iterator<Entry<String, String>> checkLast = tableSet.iterator();
if (checkLast.hasNext()) {
checkLast.next();
}
for (Entry<String, String> i : tableSet) {
if (checkLast.hasNext()) {
pw.print(i.getKey() + ", ");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Замените на String.join()
  2. Вынесите этот код по месту использования. Метод с таким API вообще не нужен в библиотеке.

checkLast.next();
} else {
pw.print(i.getKey());
}
}
pw.flush();
}

public void fullList(PrintWriter pw) {
Set<Entry<String, String>> tableSet = table.entrySet();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Аналогично.

Iterator<Entry<String, String>> checkLast = tableSet.iterator();
if (checkLast.hasNext()) {
checkLast.next();
}
for (Entry<String, String> i : tableSet) {
if (checkLast.hasNext()) {
pw.println(i.getKey() + " " + i.getValue());
checkLast.next();
} else {
pw.print(i.getKey() + " " + i.getValue());
}
}
pw.flush();
}

public String remove(String key) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException();
}
return table.remove(key);
}

public void exit() throws IOException {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exit -> close

DataOutputStream out = new DataOutputStream(
new FileOutputStream(dbFile));
Set<Entry<String, String>> tableSet = table.entrySet();
for (Entry<String, String> it : tableSet) {
writeData(out, it.getKey());
writeData(out, it.getValue());
}
out.flush();
out.close();
}

private void writeData(DataOutputStream out, String toWrite)
throws IOException {
int len = toWrite.length();
out.writeInt(len * 2);
out.writeChars(toWrite);
}

public boolean isEmpty() {
return table.isEmpty();
}

public int size() {
return table.size();
}

@Override
public String getName() {
return dbFile.getName();
}

@Override
public int commit() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хотелось бы видеть здесь реализацию

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это реализация класса FileMap из второго задания, там вообще не должно быть механизма транзакций. Добавил commit() и rollback(), потому что унаследовал класс от Table.

return 0;
}

@Override
public int rollback() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

и здесь

return 0;
}
}
Loading