Esempio n. 1
0
  // проверка валидности
  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");
    }
  }
Esempio n. 2
0
  // добавить продукт в базу 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");
    }
  }
Esempio n. 3
0
 // получение в виде таблицы
 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;
 }