示例#1
0
 public void contextInitialized(ServletContextEvent event) {
   // This will be invoked as part of a warm up request, or the first user
   // request if no warm up request was invoked.
   ObjectifyService.register(GcmMessage.class);
   // ObjectifyService.register(CFUser.class);
   ObjectifyService.register(MyResource.class);
 }
 static {
   ObjectifyService.register(Channel.class);
   ObjectifyService.register(Target.class);
   ObjectifyService.register(Reason.class);
   ObjectifyService.register(User.class);
   ObjectifyService.register(PersistentConfiguration.class);
 }
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    ObjectifyService.register(Subscriber.class);
    Subscriber newSubscriber = new Subscriber(user.getEmail());
    ofy().save().entity(newSubscriber).now();

    // MailUpdate.subscribers.add(user);

    System.out.println(user.getEmail() + " has subscribed");
    List<Subscriber> subscribers = ObjectifyService.ofy().load().type(Subscriber.class).list();
    // for (Subscriber subscriber : subscribers){
    // ofy().delete().entity(subscriber);
    // }
    Collections.sort(subscribers);
    System.out.println("size" + subscribers.size());
    for (Subscriber subscriber : subscribers) {
      System.out.println(subscriber.getEmail());
    }
    // try{
    // RequestDispatcher view = req.getRequestDispatcher("");
    // view.forward(req, resp);

    // } catch (Exception e){}
    resp.sendRedirect("/");
  }
示例#4
0
 public static OrganizationService getInstance() {
   if (_self == null) {
     _self = new OrganizationService();
     ObjectifyService.register(HelpDeskOrganization.class);
     ObjectifyService.register(OrganizationResetTask.class);
   }
   return _self;
 }
  public void init() {
    reportStore = new ReportStore();
    reportStore.init();

    ObjectifyService.register(User.class);
    ObjectifyService.register(StoredReport.class);
    ObjectifyService.register(StoredImage.class);
  }
  @Post("xml")
  public Representation acceptItem(Representation entity) {

    DomRepresentation result = null;
    Document d = null;
    try {

      DomRepresentation input = new DomRepresentation(entity);
      Document doc = input.getDocument();
      // handle input document
      Element rootEl = doc.getDocumentElement();
      String usernameDoctor = XMLUtils.getTextValue(rootEl, "username");
      // output
      result = new DomRepresentation(MediaType.TEXT_XML);
      d = result.getDocument();

      try {
        ObjectifyService.register(Patient.class);
        ObjectifyService.register(Relative.class);
      } catch (Exception e) {
      }

      Key<Relative> doctor = new Key<Relative>(Relative.class, usernameDoctor);

      Objectify ofy = ObjectifyService.begin();

      List<Patient> listRU = ofy.query(Patient.class).filter("doctor", doctor).list();

      Element root = d.createElement("getUsers");
      d.appendChild(root);

      Element eltName4 = d.createElement("getUsersList");

      for (Patient us : listRU) {

        Element user = d.createElement("user");

        user.setAttribute("firstname", "" + us.getFirstName());
        user.setAttribute("lastname", "" + us.getLastName());
        user.setAttribute("username", "" + us.getUsername());
        user.setAttribute("password", "" + us.getPassword());
        user.appendChild(d.createTextNode(us.getUsername()));
        eltName4.appendChild(user);
      }
      root.appendChild(eltName4);

      d.normalizeDocument();

    } catch (Exception e) {
      result = XMLUtils.createXMLError("get doctors list error", "" + e.getMessage());
    }

    return result;
  }
  // Process the http POST of the form
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String kvartalName = req.getParameter("kvartal");
    if (kvartalName == null) {
      kvartalName = (String) req.getSession(true).getAttribute("kvartal");
    }

    String objectName = req.getParameter("objectName");
    if (objectName == null || objectName.length() == 0) {
      req.getSession(true).setAttribute("kvartal", kvartalName);
      resp.sendRedirect("/kvartal.jsp");
      return;
    }

    String category = req.getParameter("category");
    if (category == null) {
      category = "";
    }

    String opinion = req.getParameter("opinion");
    byte evaluation = 0;

    if (req.getParameter("evaluation") != null && req.getParameter("evaluation").length() > 0) {
      evaluation = Byte.parseByte(req.getParameter("evaluation"));
    }

    Key<Kvartal> getKvartalKey = Key.create(Kvartal.class, kvartalName);
    Key<OpinionObject> getOpinionObjectKey = Key.create(OpinionObject.class, objectName);

    OpinionObject nextObject = null;

    nextObject =
        ObjectifyService.ofy()
            .load()
            .type(OpinionObject.class)
            .filterKey(getOpinionObjectKey)
            .first()
            .now();

    if (nextObject == null) {
      nextObject = new OpinionObject(getKvartalKey, objectName);
    }

    // no address as of now
    nextObject.AddOpinionObject(objectName, category, "", opinion, evaluation);
    ObjectifyService.ofy().save().entity(nextObject).now(); // Update DB

    req.getSession(true).setAttribute("kvartal", kvartalName);

    resp.sendRedirect("/kvartal.jsp");
  }
 @Override
 @ApiMethod(name = "routes.get.query", httpMethod = "post")
 public List<RouteInfo> getRoutesByQuery(@Named("query") String query)
     throws IllegalArgumentException {
   ObjectifyService.begin();
   return routeServiceManager.getRoutes(query);
 }
 @Override
 public List<RouteInfo> saveRoute(
     AgentInfo userInfo, RouteInfo placeInfo, @Named("mode") RouteInfo.SaveMode mode)
     throws IllegalArgumentException {
   ObjectifyService.begin();
   return routeServiceManager.saveRoute(userInfo, placeInfo, mode);
 }
 @Override
 // @ApiMethod(name = "route.delete", httpMethod = "post")
 public List<RouteInfo> deleteRoute(AgentInfo userInfo, RouteInfo placeInfo)
     throws IllegalArgumentException {
   ObjectifyService.begin();
   return routeServiceManager.deleteRoute(userInfo, placeInfo);
 }
 @Override
 // @ApiMethod(name = "contractor.delete", httpMethod = "post")
 public List<ContractorInfo> deleteContractor(AgentInfo agentInfo, ContractorInfo contractorInfo)
     throws IllegalArgumentException {
   ObjectifyService.begin();
   return contractorManager.deleteContractor(agentInfo, contractorInfo);
 }
 @Override
 // @ApiMethod(name = "stat.send", httpMethod = "post")
 public void sendStat(StatInfo statInfo) {
   ObjectifyService.begin();
   logger.info(statInfo.getDetail());
   statManager.updateSessionStat(statInfo);
 }
  @Override
  public BookingInfo payWithStripe(@Named("token") String token, BookingInfo bookingInfo) {
    ObjectifyService.begin();
    logger.info("payWithStripe" + bookingInfo.getPaidPrice());
    Profil profil = bookingServiceManager.getProfil();
    logger.info("payWithStripe" + bookingInfo.getPaidPrice());
    Route route = ofy().load().type(Route.class).id(bookingInfo.getRouteId()).now();
    ContractorInfo contractorInfo = bookingServiceManager.getContractor(bookingInfo);
    Agent agent = ofy().load().type(Agent.class).id(contractorInfo.getAgentId()).now();
    Long orderCount = agent.getOrderCount();
    String orderRef = orderCount + "_" + bookingInfo.getName();

    String refusal = stripePayment.charge(token, bookingInfo, profil.getStripeSecret(), orderRef);
    if (refusal == null) {
      bookingInfo = bookingServiceManager.setPayed(profil, bookingInfo, OrderStatus.PAID, orderRef);
      if (bookingInfo != null) {
        AgentInfo agentInfo = bookingServiceManager.getAgent(contractorInfo);
        Mailer.sendConfirmation(bookingInfo, profil, agentInfo, contractorInfo);
        financeManager.addPayment(bookingInfo, new Date());
        ofy().save().entity(agent).now();
      }
    } else {
      bookingInfo.setStripeRefusalReason(refusal);
    }
    return bookingInfo;
  }
示例#14
0
  @Override
  public void start(UpdatableInjectionContext injectionContext) {
    InterceptorRegistry interceptorRegistry = injectionContext.get(InterceptorRegistry.class);
    interceptorRegistry.registerInterceptor(JobProcessor.class, new JobProcessorInterceptor());

    ObjectifyService.register(JobStatus.class);
  }
 @Override
 @ApiMethod(name = "bookings.agent", path = "bookingsagent", httpMethod = "post")
 public List<BookingInfo> getBookingsForAgent(AgentInfo agentInfo)
     throws IllegalArgumentException {
   ObjectifyService.begin();
   return bookingServiceManager.getBookingsAsInfo(agentInfo.getId());
 }
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Override
  public Object invoke(final Object proxy, final Method method, final Object[] args)
      throws Throwable {
    try {
      final Method implementationMethod =
          implementation.getClass().getMethod(method.getName(), method.getParameterTypes());
      final Transactional transactional = implementationMethod.getAnnotation(Transactional.class);

      if (transactional != null) {

        final IdempotencyHandler idempotencyHandler =
            IdempotencyHandlerFactory.createHandlerAnnotationBased(transactional);

        return ObjectifyService.ofy()
            .execute(
                transactional.type(),
                new Work() {
                  @Override
                  public Object run() {
                    if (idempotencyHandler.shouldTransactionProceed(proxy, method, args)) {
                      Object result = invokeMethod(args, implementationMethod);
                      idempotencyHandler.setReturn(result);
                    }
                    return idempotencyHandler.getReturn();
                  }
                });

      } else {
        return invokeMethod(args, implementationMethod);
      }
    } catch (RuntimeException err) {
      throw getRootCause(err, 5);
    }
  }
示例#17
0
 @SuppressWarnings("unchecked")
 public static synchronized List<Key<Line>> getTrainKeys() {
   String functionName = "getTrainKeys()";
   if (trainKeys == null || trainKeys.size() == 0) {
     Objectify ofy = ObjectifyService.begin();
     Query<Line> q = ofy.query(Line.class).filter("type", 21);
     List<Key<Line>> keys;
     try {
       Cache cache =
           CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
       keys = (List<Key<Line>>) cache.get(q.toString());
       if (keys == null) {
         keys = q.listKeys();
         cache.put(q.toString(), keys);
       }
     } catch (CacheException e) {
       keys = q.listKeys();
       Logger.getLogger(location).log(Level.SEVERE, functionName + ": Cache error: " + e);
       e.printStackTrace();
     }
     trainKeys = keys;
     Logger.getLogger(location)
         .log(Level.INFO, functionName + ": served new trainKeys. #" + trainKeys.size());
   }
   return trainKeys;
 }
示例#18
0
  public void addScoutsToClazz(Key<Clazz> clazzKey, List<Key<Scout>> scoutList) {
    Objectify ofy = ObjectifyService.begin();
    Clazz c = get(clazzKey);

    if (c == null) {
      throw new RuntimeException("Clazz " + clazzKey.getId() + " not found!");
    }

    Event e = ofy.get(c.getEvent());
    for (Key<Scout> scoutId : scoutList) {
      if (!c.getScoutIds().contains(scoutId)) {
        c.getScoutIds().add(scoutId);
      }
    }
    for (Key<Scout> s : scoutList) {
      TrackProgress tp = new TrackProgress();
      tp.setScoutKey(s);
      tp.setClazzKey(clazzKey);
      Date curDate = (Date) e.getStartDate().clone();
      List<DateAttendance> attendanceList = new ArrayList<DateAttendance>();
      while (!curDate.after(e.getEndDate())) {
        DateAttendance da = new DateAttendance();
        da.setDate((Date) curDate.clone());
        da.setPresent(false);
        curDate.setDate(curDate.getDate() + 1);
        attendanceList.add(da);
      }
      tp.setAttendanceList(attendanceList);
      MeritBadge mb = ofy.get(c.getMbId());
      tp.setRequirementList(buildRequirementList(mb.getRequirements(), "", 0));
      ofy.put(tp);
    }

    ofy.put(c);
  }
示例#19
0
  @Before
  public void setupSignGuestBookServlet() {
    helper.setUp();
    OfyHelper.register(); // Needed for Objectify
    closeable = ObjectifyService.begin(); // Objectify

    signGuestbookServlet = new SignGuestbookServlet();
  }
示例#20
0
  /**
   * Saves given bean.
   *
   * @param bean The bean to store.
   */
  public void save(T bean) {

    if (bean == null) {
      throw new IllegalArgumentException("null bean object");
    }
    LOGGER.info("Saving bean " + bean.getId());
    ObjectifyService.ofy().save().entity(bean).now();
  }
示例#21
0
  /**
   * Deletes given bean
   *
   * @param bean The bean to delete.
   */
  public void delete(T bean) {

    if (bean == null) {
      throw new IllegalArgumentException("null bean object");
    }
    LOGGER.info("Deleting bean " + bean.getId());
    ObjectifyService.ofy().delete().entity(bean);
  }
 @Override
 @ApiMethod(name = "bookings.route", path = "bookingsroute", httpMethod = "post")
 public List<BookingInfo> getBookingsForRoute(RouteInfo routeInfo)
     throws IllegalArgumentException {
   ObjectifyService.begin();
   logger.info("route inquiry:" + routeInfo.getStart() + " -> " + routeInfo.getEnd());
   return bookingServiceManager.getBookingsForRoute(routeInfo);
 }
 @Override
 // @ApiMethod(name = "profil.get", httpMethod = "post")
 public ProfilInfo getPaypalProfil() throws IllegalArgumentException {
   ObjectifyService.begin();
   ProfilInfo profilInfo = bookingServiceManager.getProfil().getInfo();
   logger.info(profilInfo.toString());
   return profilInfo;
 }
  @Post("xml")
  public Representation acceptItem(Representation entity) {

    DomRepresentation representation = null;
    try {
      DomRepresentation input = new DomRepresentation(entity);
      // input
      Document doc = input.getDocument();
      Element rootEl = doc.getDocumentElement();
      String username = XMLUtils.getTextValue(rootEl, "username");

      // output
      representation = new DomRepresentation(MediaType.TEXT_XML);

      // Generate a DOM document representing the list of
      // items.

      String res = "";
      try {
        ObjectifyService.register(Patient.class);
      } catch (Exception e) {
      }

      Objectify ofy = ObjectifyService.begin();
      Patient us = ofy.query(Patient.class).filter("username", username).get();
      if (us == null) {
        res = "user not found.";
      } else {

        ofy.delete(us);
        res = "OK, " + us.getUsername() + " deleted.";
      }
      getLogger().info("res: " + res);
      Map<String, String> map = new HashMap<String, String>();
      map.put("result", res);
      Document d = representation.getDocument();
      d = XMLUtils.createXMLResult("rehabDeleteUserOutput", map, d);

    } catch (IOException e) {
      representation = XMLUtils.createXMLError("user delete error", "" + e.getMessage());
    }

    // Returns the XML representation of this document.
    return representation;
  }
  @Override
  public void setUp() {
    try {
      helper.setUp();

      ModelFactory.setInstance(new ServerModelFactory());

      try {
        ObjectifyService.register(UserImpl.class);
        ObjectifyService.register(InterestImpl.class);
        ObjectifyService.register(C2DMConfig.class);
      } catch (IllegalArgumentException e) {
      }

      /*
       * Viene utilizzato Jetty v7.5.4 come Servlet Container
       * http://www.eclipse.org/jetty/
       */
      server = new Server(0);
      ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
      context.setContextPath("/");
      server.setHandler(context);
      context.addFilter(new FilterHolder(new FilterForTesting()), "/*", 0);
      context.addFilter(new FilterHolder(new ServletFilter()), "/*", 0);
      context.addServlet(new ServletHolder(new MockServlet()), "/*");

      server.start();
      port = server.getConnectors()[0].getLocalPort();

      // User utilizzato col solo scopo di ottenere un X-AccessToken valido per effettuare le
      // richieste
      UserImpl user1 =
          (UserImpl) ModelFactory.getInstance().createUser(12345, "Michele Piccirillo", null);
      fbAccessToken = "accessToken";
      user1.setAuthToken(fbAccessToken);
      ObjectifyService.begin().put(user1);

      Thread.sleep(
          15); // Ulizzato per assicurare che il tempo necessario per la persistenza sul Datatore
               // sia passato

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#26
0
  static {
    try {

      ObjectifyService.register(VoteDetails.class);
    } catch (Exception ex) {

      // System.out.println(ex.toString());
    }
  }
 /**
  * Assembles the Key for this entity. If an Entity has a Parent Key, that
  *
  * <p>key will be included in the returned Key heirarchy.
  *
  * @return
  */
 public <T> Key<T> getTypedKey() {
   if (this.getId() == null) {
     return null;
   } else {
     final com.google.appengine.api.datastore.Key rawKey =
         ObjectifyService.factory().getMetadataForEntity(this).getKeyMetadata().getRawKey(this);
     return Key.create(rawKey);
   }
 }
 @Override
 // @ApiMethod(name = "share.request.send", httpMethod = "post")
 public BookingInfo sendShareRequest(BookingInfo bookingInfo) {
   ObjectifyService.begin();
   Profil profil = bookingServiceManager.getProfil();
   BookingInfo parentBooking = bookingServiceManager.getBookingAsInfo(bookingInfo.getParentId());
   Mailer.sendShareRequest(parentBooking, bookingInfo, profil);
   return bookingInfo;
 }
 public static void put(String name, String value) {
   SettingStore setting =
       ObjectifyService.ofy().load().type(SettingStore.class).filter("name", name).first().now();
   if (setting == null) {
     setting = new SettingStore();
     setting.name = name;
   }
   setting.value = value;
   setting.save();
 }
示例#30
-3
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
      BufferedReader reader = request.getReader();
      while ((line = reader.readLine()) != null) jb.append(line);
    } catch (Exception e) {
      System.out.println("Erreur");
    }
    JSONObject json = new JSONObject(jb.toString());
    System.out.println(jb.toString());

    Petition p = new Petition();

    p.setTitle(json.getValue("title"));
    p.setDescription(json.getValue("text"));
    response.getWriter().println(p.toString());

    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    // Récupération de l'utilisateur google courant

    if (user != null) {
      System.out.println(user.toString());
    } else {
      System.out.println("user null");
    }

    ObjectifyService.ofy().save().entities(p).now();
    response.getWriter().println("Ajout effectué");
  }