Exemplo n.º 1
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // topdish1.appspot.com/api/dishDetail?id[]=1&id[]=2&id[]=5...

    String[] ids = req.getParameterValues(APIConstants.ID_ARRAY);
    Set<Key> dishKeys = new HashSet<Key>();

    for (int i = 0; i < ids.length; i++) {
      try {
        Long id = Long.parseLong(ids[i]);
        dishKeys.add(KeyFactory.createKey(Dish.class.getSimpleName(), id));
      } catch (NumberFormatException e) {
        // malformed input
      } catch (JDOObjectNotFoundException e) {
        // object not found, skipping
      }
    }

    final Set<Dish> dishes = Datastore.get(dishKeys);
    final Set<DishLite> dishLites = ConvertToLite.convertDishes(dishes);

    if (!dishLites.isEmpty()) {
      final JSONArray array = new JSONArray();

      // Traverse dishes
      for (final DishLite dish : dishLites) {
        try {
          // Put a new JSONObject of the Dish in the Array
          array.put(new JSONObject(new Gson().toJson(dish)));

        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      // Return array (empty or not)
      resp.getWriter().write(APIUtils.generateJSONSuccessMessage(DishConstants.DISHES, array));
    } else resp.getWriter().write(APIUtils.generateJSONFailureMessage("No dishes found"));
  }