@PUT
 @Consumes(MediaType.APPLICATION_XML)
 public Response putTaskData(String value) {
   Response res = null;
   // add your code here
   // first check if the Entity exists in the datastore
   DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
   MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
   syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
   Key entKey = KeyFactory.createKey("TaskData", keyname);
   Date date = new Date();
   try {
     // if it is, signal that we updated the entity
     Entity ts = datastore.get(entKey);
     ts.setProperty("value", value);
     ts.setProperty("date", date);
     datastore.put(ts);
     res = Response.noContent().build();
   } catch (EntityNotFoundException e) {
     // if it is not, create it and
     // signal that we created the entity in the datastore
     Entity taskdata = new Entity("TaskData", keyname);
     taskdata.setProperty("value", value);
     taskdata.setProperty("date", date);
     datastore.put(taskdata);
     res = Response.created(uriInfo.getAbsolutePath()).build();
   }
   TaskData td = new TaskData(keyname, value, date);
   syncCache.put(keyname, td);
   return res;
 }
  @GET
  @Path("{route_id}")
  @Produces(MediaType.APPLICATION_JSON)
  public String getPlace(@PathParam("route_id") String routeID) {
    JSONObject reply = new JSONObject();
    try {

      syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));

      Entity result = (Entity) syncCache.get(routeID);
      if (result != null)
        return reply
            .append("status", "OK")
            .append("message", "Found in memcache.")
            .append("Route Object", result)
            .toString();

      return reply.append("status", "fail").append("message", "Not found in memcache.").toString();
    } catch (Exception e) {
      return new JSONObject()
          .append("status", "fail")
          .append("message", "Route object with ID " + routeID + " not found.")
          .toString();
    }
  }
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public String addRoute(Route route, @Context HttpServletResponse servletResponse)
      throws IOException {
    try {
      Entity routeEntity = new Entity("Route");
      routeEntity.setProperty("originPlaceID", route.getOrigin().getGooglePlaceId());
      routeEntity.setProperty("destinationPlaceID", route.getDestination().getGooglePlaceId());
      routeEntity.setProperty("duration", route.getDuration());
      routeEntity.setProperty("distance", route.getDistance());
      routeEntity.setProperty("origin", route.getOrigin().getAddress());
      routeEntity.setProperty("destination", route.getDestination().getAddress());

      Text mapJsonAsText = route.getMapJsonAsText();
      routeEntity.setProperty("routeJSON", mapJsonAsText);

      syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
      String cacheKey = "route-" + key.nextLong();
      syncCache.put(cacheKey, routeEntity);
      return new JSONObject().append("status", "OK").append("key", cacheKey).toString();
    } catch (Exception e) {
      return new JSONObject()
          .append("status", "fail")
          .append("message", "Could not cache object.")
          .toString();
    }
  }
 @DELETE
 @Path("{route_id}")
 @Produces(MediaType.APPLICATION_JSON)
 public String deletePlace(@PathParam("route_id") String routeID) {
   syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
   JSONObject reply = new JSONObject();
   try {
     syncCache.delete(routeID);
     return reply
         .append("status", "OK")
         .append("message", "successfully deleted route " + routeID + " from " + "memcache")
         .toString();
   } catch (Exception e) {
     return new JSONObject().append("status", "fail").append("message", e.getMessage()).toString();
   }
 }
Example #5
0
public class ErrorDialog extends JDialog {

  private static final long serialVersionUID = 1L;

  public static final int DEFAULT_FIRST_COMUMN_WIDTH = 300;

  public static void displayErrorDialog(List<Object> errors, @CheckForNull Window frame) {
    ErrorDialog errorDialog = new ErrorDialog(frame);
    errorDialog.setErrors(errors);
    errorDialog.setVisible(true);
  }

  List<?> errors = Collections.emptyList();

  final JTable table;

  final ErrorTableModel model = new ErrorTableModel();

  {
    table = new JTable();
    model.setErrors(errors);
    table.setModel(model);
    TableColumn detailsColumn = table.getColumnModel().getColumn(1);
    detailsColumn.setCellEditor(new DetailRenderer());
    detailsColumn.setCellRenderer(new DetailRenderer());
    detailsColumn.setPreferredWidth(15);
    table.getColumnModel().getColumn(0).setPreferredWidth(DEFAULT_FIRST_COMUMN_WIDTH);
  }

  final JButton closeButton;

  {
    closeButton = new JButton("Zamknij");
    closeButton.addActionListener(new HideWindowActionListener(this));
  }

  private final ClassHandler<Formatter> detailsHandlers = ErrorHandlers.createLongHandlers();

  public ErrorDialog() {
    super();
    initialize();
  }

  public ErrorDialog(@CheckForNull Frame owner, boolean modal) {
    super(owner, modal);
    initialize();
  }

  public ErrorDialog(@CheckForNull Window owner) {
    super(owner);
    initialize();
  }

  private void initialize() {
    setLayout(new MigLayout("fillx", "[fill]"));
    add(new JScrollPane(table));
    add(closeButton, "tag finished, dock south");
    pack();
    initLocation(this);
  }

  private class DetailRenderer extends AbstractCellEditor
      implements TableCellRenderer, TableCellEditor {

    private static final long serialVersionUID = 1L;

    Object value;

    final JButton rendererEditor;

    final ErrorDetailsDialog dialog = new ErrorDetailsDialog(ErrorDialog.this);

    {
      rendererEditor = new JButton(MainIconManager.getIcon("error_go"));
      rendererEditor.setBorderPainted(false);
      rendererEditor.setContentAreaFilled(false);
      rendererEditor.addActionListener(
          new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
              dialog.setText(detailsHandlers.getHandler(value).getMessage(value));
              dialog.setVisible(true);
            }
          });
    }

    @Override
    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      return rendererEditor;
    }

    @Override
    public Object getCellEditorValue() {
      return value;
    }

    @Override
    public Component getTableCellEditorComponent(
        JTable table, Object value, boolean isSelected, int row, int column) {
      this.value = value;
      return rendererEditor;
    }
  }

  public void setErrors(List<?> errors) {
    this.errors = errors;
    model.setErrors(errors);
  }

  @Override
  public void setVisible(boolean b) {
    pack();
    super.setVisible(b);
  }
}
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    resp.getWriter().println("<html><body>");

    String keyname = req.getParameter("keyname");
    String value = req.getParameter("value");

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    // Using the synchronous cache.
    MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
    syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));

    // display every element of kind TaskData for /datastore
    if (req.getParameterMap().isEmpty()) {
      // querying from datastore
      resp.getWriter().println("<h3>Datastore results:</h3>");
      List<String> listOfKeys = new ArrayList<String>();
      Query q = new Query("TaskData");
      PreparedQuery pq = datastore.prepare(q);
      for (Entity result : pq.asIterable()) {
        String datastore_key = result.getKey().getName();
        String taskData_value = (String) result.getProperty("value");
        Date taskData_date = (Date) result.getProperty("date");
        resp.getWriter()
            .println(
                "<p>keyname = "
                    + datastore_key
                    + "  value = "
                    + taskData_value
                    + " date = "
                    + taskData_date.toString()
                    + "</p>");
        listOfKeys.add(datastore_key);
      }
      // check which of the keys exist in memcache
      String memcache_value;
      resp.getWriter().println("<h3>Memcache results:</h3>");
      for (String datastore_key : listOfKeys) {
        memcache_value = (String) syncCache.get(datastore_key);
        if (memcache_value != null) {
          // String decoded = new String(memcache_value, "UTF-8");
          resp.getWriter()
              .println("<p>keyname = " + datastore_key + " value = " + memcache_value + "</p>");
        }
      }
    }

    // display element of kind TaskData with key=keyname
    else if (keyname != null && value == null) {

      // first check in the cache
      String memcache_value = (String) syncCache.get(keyname); // Read from cache.
      // Get value from datastore
      Key task_key = KeyFactory.createKey("TaskData", keyname);
      try {
        Entity tne = datastore.get(task_key);
        if (memcache_value == null) {
          resp.getWriter().println("<h2>Datastore</h2>");
        } else {
          resp.getWriter().println("<h2>Both</h2>");
        }

      } catch (EntityNotFoundException e) {
        resp.getWriter().println("<h2>Neither</h2>");
      }
    }

    // store element of kind TaskData with key=keyname and value=value
    else if (keyname != null && value != null) {
      Entity tne = new Entity("TaskData", keyname);
      tne.setProperty("value", value);
      tne.setProperty("date", new Date());
      datastore.put(tne);
      syncCache.put(keyname, value); // Populate cache.
      resp.getWriter()
          .println("<h2>Stored " + keyname + " and " + value + " in Datastore and Memcache</h2>");
    } else {

      resp.getWriter().println("<h2>You entered wrong query parameters</h2>");
    }

    /*
       Entity tne = new Entity("TaskData", "Person");
    alice.setProperty("gender", "female");
    alice.setProperty("age", 20);
    */

    resp.getWriter().println("</body></html>");
  }