// добавить продукт в базу json server public static void add(ProductREST product) throws NotValidProductException, IOException { try { check(product); // рповеряем продукт // connection к серверу HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection())); con.setRequestMethod("POST"); // метод post для добавления // генерируем запрос StringBuilder urlParameters = new StringBuilder(); urlParameters .append("name=") .append(URLEncoder.encode(product.getName(), "UTF8")) .append("&"); urlParameters.append("price=").append(product.getPrice()).append("&"); urlParameters.append("weight=").append(product.getWeight()).append("&"); urlParameters .append("manufacturer=") .append(product.getManufacturer().getCountry()) .append("&"); urlParameters.append("category=").append(URLEncoder.encode(product.getCategory(), "UTF8")); con.setDoOutput(true); // разрешаем отправку данных // отправляем try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) { out.writeBytes(urlParameters.toString()); } // код ответа int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + PRODUCT_URL); System.out.println("Response Code : " + responseCode); } catch (NotValidProductException e) { e.printStackTrace(); throw e; } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new UnsupportedEncodingException("cannot recognize encoding"); } catch (ProtocolException e) { e.printStackTrace(); throw new ProtocolException("No such protocol, protocol must be POST,DELETE,PATCH,GET etc."); } catch (MalformedURLException e) { e.printStackTrace(); throw new MalformedURLException("Url is not valid"); } catch (IOException e) { e.printStackTrace(); throw new IOException("cannot write information to server"); } }
// получит все продукты в виде спсика public static List<ProductREST> getAll() throws IOException, JsonValidationException { List<ProductREST> products = new LinkedList<>(); String data = readAll(); for (JsonElement e : getElements(data)) { JsonObject obj = e.getAsJsonObject(); Iterator<Map.Entry<String, JsonElement>> elements = obj.entrySet().iterator(); int i = 0; ProductREST current = new ProductREST(); while (elements.hasNext()) { switch (i++) { case 0: current.setName(elements.next().getValue().getAsString()); break; case 1: current.setPrice(elements.next().getValue().getAsDouble()); break; case 2: current.setWeight(elements.next().getValue().getAsDouble()); break; case 3: current.setManufacturer( ProductREST.getManufacturer(elements.next().getValue().getAsString())); break; case 4: current.setCategory(elements.next().getValue().getAsString()); break; case 5: current.setId(elements.next().getValue().getAsInt()); break; default: throw new JsonValidationException("cannot validate json database, check it!"); } } products.add(current); } return products; }
// проверка валидности private static void check(ProductREST product) throws NotValidProductException { double EPS = 1E-9; // можно и с 0 сравнивать просто так нпаписал, интересно же =) if (product == null) { throw new NullPointerException("Product must not be null!"); } if (product.getName() == null || "".equals(product.getName())) { throw new NotValidProductException("Product name must not be empty"); } if (product.getCategory() == null || "".equals(product.getName())) { throw new NotValidProductException("category is not valid"); } if (product.getPrice() <= EPS || product.getWeight() <= EPS) { throw new NotValidProductException("Product weight and price must be more than zero"); } }
// получение в виде таблицы public static String[][] getTable() { List<ProductREST> products = new ArrayList<>(); try { products = getAll(); } catch (IOException | JsonValidationException e) { e.printStackTrace(); } String[][] result = new String[products.size()][5]; int i = 0; for (ProductREST p : products) { result[i][0] = p.getName(); result[i][1] = String.valueOf(p.getPrice()); result[i][2] = String.valueOf(p.getWeight()); result[i][3] = p.getManufacturer().getCountry(); result[i][4] = p.getCategory(); // найти в категорияях по id name i++; } return result; }