diff --git a/task-01-disk-analyzer/src/main/java/ru/hse/cs/java2020/task01/Main.java b/task-01-disk-analyzer/src/main/java/ru/hse/cs/java2020/task01/Main.java index d96d7e0..a14eea3 100644 --- a/task-01-disk-analyzer/src/main/java/ru/hse/cs/java2020/task01/Main.java +++ b/task-01-disk-analyzer/src/main/java/ru/hse/cs/java2020/task01/Main.java @@ -1,7 +1,198 @@ package ru.hse.cs.java2020.task01; +import java.io.File; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Queue; +import java.util.PriorityQueue; +import java.util.Collections; public class Main { + private static File rootLib; + private static int countMax = 5; + + static class Returning { + private File nameFile; + private long Filescnt, Folderscnt, totalSize; + private List TopSize; + + Returning() { + nameFile = null; + Filescnt = 0; + Folderscnt = 0; + totalSize = 0; + TopSize = new ArrayList<>(); + } + + Returning(File f) { + nameFile = f; + Filescnt = 0; + Folderscnt = 0; + totalSize = 0; + TopSize = new ArrayList<>(); + } + + Returning(long s, File f) { + nameFile = f; + Filescnt = -1; + Folderscnt = -1; + totalSize = s; + TopSize = null; + } + } + + static class FileSizeComparator implements Comparator { + public int compare(File f1, File f2) { + if (f1.length() != f2.length()) { + return Long.compare(f1.length(), f2.length()) * -1; + } + return 0; + } + } + static class FinalSizeComparator implements Comparator { + public int compare(Returning r1, Returning r2) { + if (r1.totalSize != r2.totalSize) { + return Long.compare(r1.totalSize, r2.totalSize) * -1; + } + return 0; + } + } + + private static int setPathAndNumMax(String[] args) { + if (args.length == 0) { + System.err.println("Too little amount of args"); + return 1; + } + rootLib = new File(args[0]); + if (args.length > 1) { + try { + countMax = Integer.parseInt(args[1]); + if (Integer.parseInt(args[1]) < 0) { + throw new NumberFormatException(); + } + } catch (NumberFormatException e) { + System.err.println("Number Format Exception caught"); + return 1; + } + } + + if (rootLib.isDirectory() && rootLib.exists()) { + return 0; + } + System.err.println("The path is incorrect"); + return 1; + } + + private static Returning getContaining(File f) { + Queue allFiles = new PriorityQueue<>(); + Returning r = new Returning(f); + + Collections.addAll(allFiles, f.listFiles()); + + while (!allFiles.isEmpty()) { + File fCur = allFiles.remove(); + + if (!fCur.isDirectory()) { + if (countMax > 0) { + if (r.TopSize.size() < countMax) { + r.TopSize.add(fCur); + } else if (r.TopSize.get(countMax - 1).length() < fCur.length()) { + r.TopSize.set(countMax - 1, fCur); + r.TopSize.sort(new FileSizeComparator()); + } + } + r.totalSize += fCur.length(); + r.Filescnt++; + } else { + if (fCur.listFiles() != null) { + r.Folderscnt++; + Collections.addAll(allFiles, fCur.listFiles()); + } + } + } + return r; + } + + + public static void main(String[] args) { - System.out.println("Hello World"); + final long startTime = System.currentTimeMillis(); + Queue allFiles = new PriorityQueue<>(); + List biggestFiles = new ArrayList<>(); + List resFiles = new ArrayList<>(); + + if (setPathAndNumMax(args) != 0) { + return; + } + + Collections.addAll(allFiles, rootLib.listFiles()); + + long totalSize = getContaining(rootLib).totalSize; + + while (!allFiles.isEmpty()) { + File currentFile = allFiles.remove(); + + if (currentFile.isDirectory()) { + File[] tmp = currentFile.listFiles(); + if (tmp != null) { + resFiles.add(getContaining(currentFile)); + } + } else { + if (countMax > 0) { + if (biggestFiles.size() < countMax) { + biggestFiles.add(currentFile); + } else if (biggestFiles.get(countMax - 1).length() < currentFile.length()) { + biggestFiles.set(countMax - 1, currentFile); + biggestFiles.sort(new FileSizeComparator()); + } + } + resFiles.add(new Returning(currentFile.length(), currentFile)); + } + + } + + resFiles.sort(new FinalSizeComparator()); + final int thousand24 = 1024; + final int hundred = 100; + final int thousand = 1000; + + + System.out.printf("%7s | %-50s | %14s | %15s | %12s | %14s | %12s %n", + "Number", "Path", "Size (kbytes)", "Size (percents)", "Files count", "Folders count", "All count"); + for (int i = 0; i < resFiles.size(); i++) { + Returning r = resFiles.get(i); + + if (r.nameFile.isDirectory()) { + System.out.printf("%7d | %-50s | %7d kbytes | %13f %% | %12d | %14d | %12d %n", i + 1, + r.nameFile.getPath().substring(args[0].length(), r.nameFile.getPath().length()), + r.totalSize / thousand24, (double) r.totalSize / totalSize * hundred, + r.Filescnt, r.Folderscnt, r.Filescnt + r.Folderscnt); + if (r.TopSize != null) { + biggestFiles.addAll(r.TopSize); + } + } else { + System.out.printf("%7d | %-50s | %7d kbytes | %13f %% | %12s | %14s | %12s %n", i + 1, + r.nameFile.getPath().substring(args[0].length(), r.nameFile.getPath().length()), + r.totalSize / thousand24, (double) r.totalSize / totalSize * hundred, "-", "-", "-"); + } + } + biggestFiles.sort(new FileSizeComparator()); + + if (resFiles.size() < countMax) { + countMax = resFiles.size(); + } + if (countMax > 0) { + System.out.println("\n"); + System.out.printf("%7s | %14s | %-120s %n", "Number", "Size", "Path"); + for (int i = 0; i < countMax; i++) { + System.out.printf("%7d | %7d kbytes | %-120s %n", + i + 1, biggestFiles.get(i).length() / thousand24, biggestFiles.get(i).getPath()); + } + } + + System.out.println("\n"); + System.out.println("Total folder size: " + totalSize / thousand24 + " kbytes"); + System.out.println("Total time: " + ((System.currentTimeMillis() - startTime) / thousand) + "c " + + ((System.currentTimeMillis() - startTime) % thousand) + "ms"); } -} +} \ No newline at end of file diff --git a/task-03-telegram-random-coffee/build.gradle b/task-03-telegram-random-coffee/build.gradle index a86e65d..6f4baa6 100644 --- a/task-03-telegram-random-coffee/build.gradle +++ b/task-03-telegram-random-coffee/build.gradle @@ -3,4 +3,6 @@ version '1.0' mainClassName = 'ru.hse.cs.java2020.task03.Main' dependencies { + compile group: 'org.telegram', name: 'telegrambots', version: '4.8.1' + implementation 'org.postgresql:postgresql:42.2.10' } diff --git a/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/BDInfo.java b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/BDInfo.java new file mode 100644 index 0000000..3d53e68 --- /dev/null +++ b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/BDInfo.java @@ -0,0 +1,25 @@ +package ru.hse.cs.java2020.task03; + +public class BDInfo { + public BDInfo(String tkn, String orgId, String name) { + this.token = tkn; + this.org = orgId; + this.username = name; + } + + public String getToken() { + return token; + } + + public String getOrg() { + return org; + } + + public String getUsername() { + return username; + } + + private final String token; + private final String org; + private final String username; +} diff --git a/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Bot.java b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Bot.java new file mode 100644 index 0000000..8b04ffb --- /dev/null +++ b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Bot.java @@ -0,0 +1,83 @@ +package ru.hse.cs.java2020.task03; +import org.telegram.telegrambots.ApiContextInitializer; +import org.telegram.telegrambots.bots.TelegramLongPollingBot; +import org.telegram.telegrambots.meta.TelegramBotsApi; +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.objects.Update; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; + +import java.util.ArrayList; +import java.util.List; + +public class Bot extends TelegramLongPollingBot { + + private static final List> updates = new ArrayList>(); + private static String TOKEN = null; + private static String USERNAME = null; + +// public Bot(String token, String usrname) { +// TOKEN = token; +// USERNAME = usrname; +// +// ApiContextInitializer.init(); +// TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); +// } + + public static Bot Builder(String token, String usrname) { + TOKEN = token; + USERNAME = usrname; + + ApiContextInitializer.init(); + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); + Bot bot = new Bot(); + + try { + telegramBotsApi.registerBot(bot); + } catch (TelegramApiRequestException e) { + System.out.println("err"); + } + return bot; + } + + public List> getUpdates() { + List> buffer = new ArrayList>(updates); + updates.clear(); + return buffer; + } + + private synchronized void sendMsg(String chatId, String s) { + SendMessage sendMessage = new SendMessage(); + sendMessage.enableMarkdown(true); + sendMessage.setChatId(chatId); + sendMessage.setText(s); + + try { + execute(sendMessage); + } catch (TelegramApiException e) { + e.printStackTrace(); + } + } + + @Override + public void onUpdateReceived(Update update) { + if (update.hasMessage()) { + ArrayList message = new ArrayList<>(); + message.add(update.getMessage().getChatId().toString()); + message.add(update.getMessage().getText()); + updates.add(message); + sendMsg(update.getMessage().getChatId().toString(), + update.getMessage().getChatId().toString() + " your request is being proceeded"); + } + } + + @Override + public String getBotUsername() { + return USERNAME; + } + + @Override + public String getBotToken() { + return TOKEN; + } +} diff --git a/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Client.java b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Client.java new file mode 100644 index 0000000..34bbac0 --- /dev/null +++ b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Client.java @@ -0,0 +1,170 @@ +package ru.hse.cs.java2020.task03; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Optional; + +public final class Client { + + private static final int TIMEOUT = 30; + private final HttpClient client; + private final String queryBasis = "https://api.tracker.yandex.net/v2/"; + + ArrayList getAllQueues(String oauthToken, String orgID) + throws java.io.IOException, java.lang.InterruptedException { + + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(queryBasis + "queues?")) + .timeout(Duration.ofSeconds(TIMEOUT)) + .headers("Authorization", "OAuth " + oauthToken, + "X-Org-Id", orgID) + .GET() + .build(); + + var response = client.send(request, HttpResponse.BodyHandlers.ofString()); + var body = response.body(); + + ArrayList result = new ArrayList<>(); + var queues = new JSONArray(body); + + for (var i = 0; i < queues.length(); i++) { + var pair = queues.getJSONObject(i); + result.add(new QueueHashMap(pair.getString("key"), pair.getInt("id"))); + } + return result; + } + + Optional createTask(String oauthToken, String orgID, String name, String description, + Optional user, String queueID) { + // forms JSON request + JSONObject JSON = new JSONObject(); + JSON.put("summary", name); + JSON.put("description", description); + JSON.put("queue", new JSONObject().put("id", queueID)); + if (user.isPresent()) { + JSON.put("assignee", user.get()); + } + + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(queryBasis + "issues?")) + .timeout(Duration.ofSeconds(TIMEOUT)) + .headers("Authorization", "OAuth " + oauthToken, + "X-Org-Id", orgID) + .POST(HttpRequest.BodyPublishers.ofString(JSON.toString())) + .build(); + + try { + var response = client.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() == 201) { + JSONObject obj = new JSONObject(response.body()); + return Optional.of(obj.getString("key")); + } else { + return Optional.empty(); + } + } catch (IOException | InterruptedException exc) { + return Optional.empty(); + } + } + + ArrayList getTasksByUser(String oauthToken, String orgID, String user) + throws TrackerException { + JSONObject request = new JSONObject(); + request.put("filter", new JSONObject().put("assignee", user)); + HttpRequest httpRequest = HttpRequest.newBuilder() + .uri(URI.create(queryBasis + "issues/_search?order=+updatedAt")) + .timeout(Duration.ofSeconds(TIMEOUT)) + .headers("Authorization", "OAuth " + oauthToken, + "X-Org-Id", orgID) + .POST(HttpRequest.BodyPublishers.ofString(request.toString())) + .build(); + try { + var response = client.send(httpRequest, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() != 200) { + System.err.println(response.body()); + throw new TrackerException(response.body()); + } + JSONArray responseJSON = new JSONArray(response.body()); + var result = new ArrayList(); + for (int i = 0; i < responseJSON.length(); i++) { + result.add(responseJSON.getJSONObject(i).getString("key")); + } + return result; + } catch (IOException | InterruptedException exc) { + System.err.println(exc.getMessage()); + throw new TrackerException(exc.getMessage()); + } + } + + Task getTask(String oauthToken, String orgID, String task) + throws java.io.IOException, java.lang.InterruptedException, TrackerException { + + HttpRequest mainRequest = HttpRequest.newBuilder() + .uri(URI.create(queryBasis + "issues/" + task)) + .timeout(Duration.ofSeconds(TIMEOUT)) + .headers("Authorization", "OAuth " + oauthToken, + "X-Org-Id", orgID) + .GET() + .build(); + + var response = client.send(mainRequest, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() == 401 || response.statusCode() == 403 || response.statusCode() == 404 || response.statusCode() == 400) { + throw new TrackerException(response.body()); + } + + var body = response.body(); + var res = new Task(); + + JSONObject obj = new JSONObject(body); + res.setName(obj.getString("key")); + res.setDescription(obj.getString("summary")); + if (obj.has("assignee")) { + res.setAssignedTo(obj.getJSONObject("assignee").getString("display")); + } else { + res.setAssignedTo(null); + } + res.setAuthor(obj.getJSONObject("createdBy").getString("display")); + if (obj.has("followers")) { + var followers = obj.getJSONArray("followers"); + for (int i = 0; i < followers.length(); i++) { + res.addFollower(followers.getJSONObject(i).getString("display")); + } + } + + HttpRequest commentRequest = HttpRequest.newBuilder() + .uri(URI.create(queryBasis + "issues/" + task + "/comments")) + .timeout(Duration.ofSeconds(TIMEOUT)) + .headers("Authorization", "OAuth " + oauthToken, + "X-Org-Id", orgID) + .GET() + .build(); + + response = client.send(commentRequest, HttpResponse.BodyHandlers.ofString()); + body = response.body(); + + var comments = new JSONArray(body); + for (int i = 0; i < comments.length(); i++) { + var comment = comments.getJSONObject(i); + res.addComment(new Comment(comment.getJSONObject("createdBy").getString("display"), + comment.getString("text"))); + } + return res; + } + + private Client() { + client = HttpClient.newHttpClient(); + } + + public static Client Builder() { + + Client client = new Client(); + return client; + } +} diff --git a/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Comment.java b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Comment.java new file mode 100644 index 0000000..de94559 --- /dev/null +++ b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Comment.java @@ -0,0 +1,19 @@ +package ru.hse.cs.java2020.task03; + +public class Comment { + public Comment(String givenAuthor, String givenText) { + this.author = givenAuthor; + this.text = givenText; + } + + private final String author; + private final String text; + + public String getAuthor() { + return author; + } + + public String getText() { + return text; + } +} diff --git a/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Main.java b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Main.java index 0268a8a..4abf7b3 100644 --- a/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Main.java +++ b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Main.java @@ -1,7 +1,31 @@ package ru.hse.cs.java2020.task03; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + public class Main { - public static void main(String[] args) { - System.out.println("Hello World"); + + public static void main(String[] args) throws IOException, InterruptedException, SQLException, TelegramApiException { + final String BOT_TOKEN = "1246051746:AAHy8Vb559shtCvbKO1R8VrxhM_GsAy77XQ"; + //String TREKKER_TOKEN = "AgAAAAA0cFXJAAZjNdE1vkSYoUD9pX8LH_wk898"; + //String TREKKER_ID = "4144791"; + final String BOT_USERNAME = "BetaTrackerbot"; + + Client trackerClient = Client.Builder(); + Bot bot = Bot.Builder(BOT_TOKEN, BOT_USERNAME); + PostgrBD base = new PostgrBD(); + MainProcess taskManager = new MainProcess(bot, base, trackerClient); + + while (true) { + Thread.sleep(10000); + List> updates = bot.getUpdates(); + for (var update : updates) { + taskManager.updater(update.get(0), update.get(1).split("\n")); + } + } } } diff --git a/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/MainProcess.java b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/MainProcess.java new file mode 100644 index 0000000..c279717 --- /dev/null +++ b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/MainProcess.java @@ -0,0 +1,213 @@ +package ru.hse.cs.java2020.task03; + +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.Optional; + +public class MainProcess { + + private final Bot tgbot; + private final PostgrBD postgrdb; + private final Client trClient; + private int counterPage = 0; + + public MainProcess(Bot telegrambot, PostgrBD DB, Client client) { + tgbot = telegrambot; + postgrdb = DB; + trClient = client; + } + + public void updater(String chatId, String[] request) throws SQLException, TelegramApiException { + switch (request[0]) { + case "/authorize": + authorize(chatId, request); + break; + case "/gettask": + getTask(chatId, request); + break; + case "/createtask": + createTask(chatId, request); + break; + case "/showqueues": + showQueues(chatId); + break; + case "/showmytasks": + counterPage = 0; + showMyTasks(chatId, request); + break; + case "/continue": + showMyTasks(chatId, request); + break; + default: + showInfo(chatId); + break; + } + } + + public void showInfo(String chatId) throws TelegramApiException { + sendMessage(chatId, + "Command list:\n" + + "Here you can recieve your personal token" + + "https://oauth.yandex.ru/authorize?response_type=token&client_id=b93d753ee4bf4a2caf8b4798025816ca \n" + + "/authorize TrackerToken X-Org-Id Username - to start using TrackerBot\n" + + "/createtask TaskName TaskDescription Queue [assignee] - to create a task with following parameters\n" + + "/gettask TaskId - to find task by Id and show main info\n" + + "/getQueues - to show all queues in Dashboard. Use it to create new tasks\n" + + "/getMyTasks [number] - to get tasks where you are an assignee \n Use new line as a separator \n"); + } + + public void authorize(String chatId, String[] request) throws SQLException, TelegramApiException { + if (request.length < 4) { + showInfo(chatId); + } else { + postgrdb.insertData(chatId, new BDInfo(request[1], request[2], request[3])); + sendMessage(chatId, "Authorization has been finished"); + } + } + + private void sendMessage(String chatId, String text) throws TelegramApiException { + tgbot.execute(new SendMessage(chatId, text)); + } + + public void getTask(String chatId, String[] request) throws TelegramApiException { + var userInfo = postgrdb.getData(chatId); + if (!userInfo.isPresent()) { + sendMessage(chatId, "No Authorization has been provided"); + return; + } + if (request.length < 2) { + showInfo(chatId); + } else { + try { + var task = trClient.getTask(userInfo.get().getToken(), userInfo.get().getOrg(), request[1]); + + sendMessage(chatId, "task name: " + task.getName()); + sendMessage(chatId, "description: " + task.getDescription()); + sendMessage(chatId, "author: " + task.getAuthor()); + + var assignedTo = task.getAssignedTo(); + assignedTo.ifPresent(s -> { + try { + sendMessage(chatId, "assignee: " + s); + } catch (TelegramApiException e) { + e.printStackTrace(); + } + }); + + var comments = task.getComments(); + if (comments.size() > 0) { + sendMessage(chatId, "comments:"); + for (var comment : comments) { + sendMessage(chatId, comment.getAuthor() + " comment " + comment.getText()); + } + } + + var followers = task.getFollowers(); + if (followers.size() > 0) { + sendMessage(chatId, "followers:"); + for (var follower : followers) { + sendMessage(chatId, follower); + } + } + + } catch (IOException | InterruptedException exc) { + sendMessage(chatId, "Undefined error occured"); + } catch (TrackerException exc) { + sendMessage(chatId, "Authorization problem occurred"); + sendMessage(chatId, exc.getMessage()); + } + } + } + + public void createTask(String chatId, String[] request) throws TelegramApiException { + + var userInfo = postgrdb.getData(chatId); + Optional newTask; + + if (!userInfo.isPresent()) { + sendMessage(chatId, "No Authorization has been provided"); + return; + } + + if (request.length < 4) { + showInfo(chatId); + } else { + // no assignee + if (request.length == 4) { + newTask = trClient.createTask(userInfo.get().getToken(), userInfo.get().getOrg(), request[1], + request[2], Optional.empty(), request[3]); + } // for user assign + else { + newTask = trClient.createTask(userInfo.get().getToken(), userInfo.get().getOrg(), request[1], + request[2], Optional.of(request[4]), request[3]); + } + if (newTask.isPresent()) { + sendMessage(chatId, "Task has been created" + newTask.get()); + } else { + sendMessage(chatId, "Undefined error occured"); + } + } + } + + public void showMyTasks(String chatId, String[] request) throws TelegramApiException { + var userInfo = postgrdb.getData(chatId); + + if (!userInfo.isPresent()) { + sendMessage(chatId, "No Authorization has been provided"); + return; + } + + try { + var tasks = trClient.getTasksByUser(userInfo.get().getToken(), userInfo.get().getOrg(), + userInfo.get().getUsername()); + int maxTasks = 1; + if (request.length > 1) { + maxTasks = Integer.parseInt(request[1]); + } + if (maxTasks >= tasks.size()) { + for (int i = 0; i < tasks.size(); i++) { + sendMessage(chatId, tasks.get(i)); + } + } else { + int temper = counterPage; + if (1 + temper > tasks.size()) { + sendMessage(chatId, "No more tasks!"); + return; + } + for (int i = temper; i < (maxTasks + temper) && i < tasks.size(); i++) { + sendMessage(chatId, tasks.get(i)); + counterPage++; + } + sendMessage(chatId, "Max tasks on page. Type /continue to proceed"); + return; + } + sendMessage(chatId, "No more tasks!"); + } catch (TrackerException exc) { + sendMessage(chatId, "Undefined error occured"); + System.err.println(exc.getMessage()); + sendMessage(chatId, exc.getMessage()); + } + } + + public void showQueues(String chatId) throws TelegramApiException { + + try { + var userInfo = postgrdb.getData(chatId); + if (!userInfo.isPresent()) { + sendMessage(chatId, "No Authorization has been provided"); + return; + } + var queues = trClient.getAllQueues(userInfo.get().getToken(), userInfo.get().getOrg()); + + sendMessage(chatId, "Current queues:"); + for (var queue : queues) { + sendMessage(chatId, "Name: " + queue.getKey() + " ID: " + queue.getId()); + } + } catch (IOException | InterruptedException exc) { + sendMessage(chatId, "Undefined error occured"); + } + } +} diff --git a/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/PostgrBD.java b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/PostgrBD.java new file mode 100644 index 0000000..16435c3 --- /dev/null +++ b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/PostgrBD.java @@ -0,0 +1,58 @@ +package ru.hse.cs.java2020.task03; + + +import java.sql.*; +import java.util.Optional; + +public class PostgrBD { + + private static Connection connection; + private static Statement statement; + + public PostgrBD() { + setConnection(); + } + + public void setConnection() { + try { + connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/JavaDB", "postgres", "1001"); + } catch (SQLException throwables) { + throwables.printStackTrace(); + } + } + + public Optional getData(String chatId) { + + String token = ""; + String orgid = ""; + String username = ""; + + try { + statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT \"token\", \"orgid\", \"username\" FROM public.\"BotTable\" WHERE \"chatid\" = '" + + chatId + "'"); + + if (!resultSet.isBeforeFirst()) { + return Optional.empty(); + } + while (resultSet.next()) { + token = resultSet.getString("token"); + orgid = resultSet.getString("orgid"); + username = resultSet.getString("username"); + } + + } catch (SQLException throwables) { + throwables.printStackTrace(); + } + + return Optional.of(new BDInfo(token, orgid, username)); + } + + public void insertData(String chatid, BDInfo userInfo) throws SQLException { + statement = connection.createStatement(); + String req = "INSERT INTO public.\"BotTable\"(username, chatid, orgid, token) VALUES (" + + "'" + userInfo.getUsername() + "'" + ", '" + chatid + "'," + + "'" + userInfo.getOrg() + "'" + "," + "'" + userInfo.getToken() + "')"; + statement.executeUpdate(req); + } +} diff --git a/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/QueueHashMap.java b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/QueueHashMap.java new file mode 100644 index 0000000..f3c7a19 --- /dev/null +++ b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/QueueHashMap.java @@ -0,0 +1,21 @@ +package ru.hse.cs.java2020.task03; + +public class QueueHashMap { + + public QueueHashMap(String newKey, long newId) { + this.key = newKey; + this.id = newId; + } + + public String getKey() { + return key; + } + + public long getId() { + return id; + } + + private String key; + + private long id; +} diff --git a/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Task.java b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Task.java new file mode 100644 index 0000000..f96f1b7 --- /dev/null +++ b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/Task.java @@ -0,0 +1,66 @@ +package ru.hse.cs.java2020.task03; + +import java.util.ArrayList; +import java.util.Optional; + +public class Task { + Task() { + followers = new ArrayList<>(); + comments = new ArrayList<>(); + } + + public void setName(String newName) { + this.name = newName; + } + + public void setDescription(String newDescription) { + this.description = newDescription; + } + + public void setAuthor(String newAuthor) { + this.author = newAuthor; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public String getAuthor() { + return author; + } + + void addComment(Comment info) { + comments.add(info); + } + + void addFollower(String follower) { + followers.add(follower); + } + + public ArrayList getFollowers() { + return followers; + } + + public ArrayList getComments() { + return comments; + } + + public Optional getAssignedTo() { + return assignedTo; + } + + public void setAssignedTo(String newAssignedTo) { + this.assignedTo = Optional.ofNullable(newAssignedTo); + } + + private Optional assignedTo; + private String name; + private String description; + private String author; + private ArrayList followers; + private ArrayList comments; +} diff --git a/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/TrackerException.java b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/TrackerException.java new file mode 100644 index 0000000..26a20dc --- /dev/null +++ b/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/TrackerException.java @@ -0,0 +1,7 @@ +package ru.hse.cs.java2020.task03; + +public class TrackerException extends Throwable { + public TrackerException(String message) { + super(message); + } +}