private void loadHistory() { StringBuilder jsonArrayString = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(DEFAULT_PERSISTENCE_FILE))) { while (reader.ready()) { jsonArrayString.append(reader.readLine()); } } catch (IOException e) { logger.error("Could not parse message.", e); } JSONArray jsonArray = new JSONArray(); if (jsonArrayString.length() == 0) { return; } try { jsonArray = (JSONArray) MessageHelper.getJsonParser().parse(jsonArrayString.toString()); } catch (ParseException e) { logger.error("Could not parse message.", e); } for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); Message message = MessageHelper.jsonObjectToMessage(jsonObject); messages.add(message); } }
private Response doGet(HttpExchange httpExchange) { String query = httpExchange.getRequestURI().getQuery(); if (query == null) { return Response.badRequest("Absent query in request"); } Map<String, String> map = queryToMap(query); String token = map.get(Constants.REQUEST_PARAM_TOKEN); if (StringUtils.isEmpty(token)) { return Response.badRequest("Token query parameter is required"); } try { int index = MessageHelper.parseToken(token); if (index > messageStorage.size()) { return Response.badRequest( String.format( "Incorrect token in request: %s. Server does not have so many messages", token)); } Portion portion = new Portion(index); List<Message> messages = messageStorage.getPortion(portion); String responseBody = MessageHelper.buildServerResponseBody(messages, messageStorage.size()); return Response.ok(responseBody); } catch (InvalidTokenException e) { return Response.badRequest(e.getMessage()); } }
public List<String> getMessages() { CLIENT_LOGGER.info("start receiving messages"); checkConnected(); List<String> list = new ArrayList<>(); HttpURLConnection incomeConnection = null; try { CLIENT_LOGGER.info("send request for receive messages"); String query = String.format( "%s?%s=%s", Constants.CONTEXT_PATH, Constants.REQUEST_PARAM_TOKEN, MessageHelper.buildToken(localHistory.size())); URL url = new URL(Constants.PROTOCOL, host, port, query); incomeConnection = prepareInputConnection(url); CLIENT_LOGGER.info("response is received"); String response = MessageHelper.inputStreamToString(incomeConnection.getInputStream()); JSONObject jsonObject = MessageHelper.stringToJsonObject(response); JSONArray jsonArray = (JSONArray) jsonObject.get("messages"); CLIENT_LOGGER.info("received " + jsonArray.size() + " messages"); for (Object o : jsonArray) { logger.info(String.format("Message from server: %s", o)); CLIENT_LOGGER.info("message from server: " + o); list.add(o.toString()); } /** Here is an example how for cycle can be replaced with Java 8 Stream API */ // jsonArray.forEach(System.out::println); // list = (List<String>) // jsonArray.stream().map(Object::toString).collect(Collectors.toList()); } catch (ParseException e) { logger.error("Could not parse message", e); CLIENT_LOGGER.error("could not parse message", e); } catch (ConnectException e) { logger.error("Connection error. Disconnecting...", e); CLIENT_LOGGER.error("connection error", e); disconnect(); } catch (IOException e) { logger.error("IOException occured while reading input message", e); CLIENT_LOGGER.error("IOException occured while reading input message", e); } finally { if (incomeConnection != null) { incomeConnection.disconnect(); } } CLIENT_LOGGER.info("stop receiving messages"); return list; }
public void sendMessage(String message) { checkConnected(); HttpURLConnection outcomeConnection = null; try { CLIENT_LOGGER.info("start sending message \"" + message + "\""); outcomeConnection = prepareOutputConnection(); byte[] buffer = MessageHelper.buildSendMessageRequestBody(message).getBytes(); OutputStream outputStream = outcomeConnection.getOutputStream(); outputStream.write(buffer, 0, buffer.length); outputStream.close(); outcomeConnection.getInputStream(); // to send data to server CLIENT_LOGGER.info("message sent"); } catch (ConnectException e) { logger.error("Connection error. Disconnecting...", e); CLIENT_LOGGER.error("connection error", e); disconnect(); } catch (IOException e) { CLIENT_LOGGER.error("IOException", e); logger.error("IOException occurred while sending message", e); } finally { if (outcomeConnection != null) { outcomeConnection.disconnect(); } CLIENT_LOGGER.info("stop sending message \"" + message + "\""); } }
private boolean rewriteHistory() { try (Writer writer = new OutputStreamWriter(new FileOutputStream(DEFAULT_PERSISTENCE_FILE), "UTF-8")) { JSONArray array = MessageHelper.getJsonArrayOfMessages(messages); writer.write(array.toString()); return true; } catch (IOException e) { logger.error("Could not parse message.", e); return false; } }
// +++++++ private Response doPost(HttpExchange httpExchange) { try { Message message = MessageHelper.getClientMessage(httpExchange.getRequestBody()); logger.info(String.format("Received new message from user: %s", message)); messageStorage.addMessage(message); return Response.ok(); } catch (ParseException e) { logger.error("Could not parse message.", e); return new Response(Constants.RESPONSE_CODE_BAD_REQUEST, "Incorrect request body"); } catch (MessageExistException e) { logger.error("Message with same id exist.", e); return new Response(Constants.RESPONSE_CODE_BAD_REQUEST, "Message with same id exist"); } }