Ejemplo n.º 1
0
  // We need to iterate again - can be avoided with a query.
  // delete will fail if the pm is different than the one used to
  // load the object - we must close the object when we're done
  public void deleteRegistration(String regId) {
    if (ctx == null) {
      return;
    }
    PersistenceManager pm = DBHelper.getPMF(ctx).getPersistenceManager();
    try {
      List<DeviceInfo> registrations = DeviceInfo.getDeviceInfoForUserEmail(pm, userEmail);
      for (int i = 0; i < registrations.size(); i++) {
        DeviceInfo deviceInfo = registrations.get(i);
        if (deviceInfo.getDeviceRegistrationID().equals(regId)) {
          pm.deletePersistent(deviceInfo);
          // Keep looping in case of duplicates

          log.log(
              Level.INFO,
              "RequestInfo:deleteRegistration() : deleted deviceInfo for "
                  + deviceInfo.getDeviceRegistrationID());
        }
      }
    } catch (JDOObjectNotFoundException e) {
      log.warning("RequestInfo:deleteRegistration() : User unknown");
    } catch (Exception e) {
      log.warning(
          "RequestInfo:deleteRegistration() : Error unregistering device: " + e.getMessage());
    } finally {
      pm.close();
    }
  }
 public void delete(ProblemEntity problem) {
   for (String string : problem.getAnswers()) {
     AnswerEntity answerEntity = answerService.getAnswerByKey(string);
     answerService.delete(answerEntity);
   }
   persistenceManager.deletePersistent(problem);
 }
Ejemplo n.º 3
0
  /**
   * Gives friend (friendid) permission to given target to user's (uid) data
   *
   * @param pm
   * @param uid
   * @param friendid
   * @param target
   * @return
   */
  @SuppressWarnings("unchecked")
  public static boolean addUserToCircle(
      PersistenceManager pm, String uid, String friendid, int target) {

    if (logger.isLoggable(Level.FINER)) {
      logger.log(
          Level.FINER,
          "Adding user to circle: uid=" + uid + ", friendid=" + friendid + ", target=" + target);
    }

    boolean ok = true;

    // check if permission already found
    Query q = pm.newQuery(Circle.class);
    q.setFilter("openId == openIdParam && friendId == friendIdParam && target == targetParam");
    q.declareParameters(
        "java.lang.String openIdParam, java.lang.String friendIdParam, java.lang.Integer targetParam");
    q.setRange(0, 1);
    List<Circle> list = (List<Circle>) q.execute(uid, friendid, target);

    // if no previous permissions found
    if (list.size() != 0) {
      pm.deletePersistent(list.get(0));
      ok = true;
    }

    // remove users from cache
    // TODO needs improving
    WeekCache cache = new WeekCache();
    cache.removeUsers();

    return ok;
  }
Ejemplo n.º 4
0
	public void deleteUser(String uuid) {
		PersistenceManager pm = getPersistenceManager();
		try {
			GameUser GameUserToDelete = pm.getObjectById(GameUser.class, uuid);
			pm.deletePersistent(GameUserToDelete);
		} finally {
			pm.close();
		}
	}
  @Override
  public void delete(T t) {
    PersistenceManager pm = getPersistenceManager();

    if (t.getKey() != null) {
      T atachedT = pm.getObjectById(getPersistentClass(), t.getKey());
      pm.deletePersistent(atachedT);
    }
  }
Ejemplo n.º 6
0
 /**
  * This method removes the entity with primary key id. It uses HTTP DELETE method.
  *
  * @param id the primary key of the entity to be deleted.
  */
 @ApiMethod(name = "removeUser")
 public void removeUser(@Named("id") String id) {
   PersistenceManager mgr = getPersistenceManager();
   try {
     User user = mgr.getObjectById(User.class, id);
     mgr.deletePersistent(user);
   } finally {
     mgr.close();
   }
 }
Ejemplo n.º 7
0
 public void remove(Paciente paciente) {
   PersistenceManager pm = PMF.get().getPersistenceManager();
   try {
     Paciente c = pm.getObjectById(Paciente.class, paciente.getCpf());
     pm.deletePersistent(c);
   } catch (JDOObjectNotFoundException ex) {
     ex.printStackTrace();
   } finally {
     pm.close();
   }
 }
 @TransactionAttribute(TransactionAttributeType.REQUIRED)
 @RolesAllowed({RoleConstants.editScheduledReport_roleID})
 @Override
 public void deleteScheduledReport(ScheduledReportID scheduledReportID) {
   PersistenceManager pm = createPersistenceManager();
   try {
     ScheduledReport scheduledReport = (ScheduledReport) pm.getObjectById(scheduledReportID);
     pm.deletePersistent(scheduledReport);
   } finally {
     pm.close();
   }
 }
Ejemplo n.º 9
0
 // TODO非同期
 public void executeDelete(PersistenceManager pm, Collection<Long> accessLogsIds) {
   pm.currentTransaction().begin();
   for (Long id : accessLogsIds) {
     AccessLog accessLog = pm.getObjectById(AccessLog.class, id);
     StoreManager.unref(accessLog.getRequestHeaderDigest());
     StoreManager.unref(accessLog.getRequestBodyDigest());
     StoreManager.unref(accessLog.getResponseHeaderDigest());
     StoreManager.unref(accessLog.getResponseBodyDigest());
     pm.deletePersistent(accessLog);
   }
   pm.currentTransaction().commit();
 }
Ejemplo n.º 10
0
  /** 게시물 삭제 */
  public void remove() {
    PersistenceManager pm = persistenceManager();
    try {
      GuestBookTable guestBook = pm.getObjectById(GuestBookTable.class, this.id);

      // Verify the current user owns the task before removing it.
      if (UserServiceWrapper.get().getCurrentUser().getEmail().equals(guestBook.getEmail())) {
        pm.deletePersistent(guestBook);
      }
    } finally {
      pm.close();
    }
  }
Ejemplo n.º 11
0
 @Override
 @Transactional
 public void deletePin(Pin pin) {
   try {
     PersistenceManager pm = _pmf.getPersistenceManager();
     pm.deletePersistent(pin);
   } catch (JDOObjectNotFoundException e) {
     /* The pin was already deleted (maybe because the file was
      * deleted). We don't care.
      */
     _log.debug("Pin deletion failed: {}", e);
   }
 }
Ejemplo n.º 12
0
 public void removeOwnedItem(String id, String itemId) {
   PersistenceManager pm = PMF.get().getPersistenceManager();
   User user = pm.getObjectById(User.class, id);
   EventCalendar cal = null;
   Set<EventCalendar> items = user.getOwnedCalendars();
   for (EventCalendar item : items) {
     if (item.getId().equals(itemId)) {
       cal = item;
       pm.deletePersistent(cal);
     }
   }
   user.removeOwnedCalendar(cal);
   pm.makePersistent(user);
   pm.close();
 }
Ejemplo n.º 13
0
 @Test
 public void testDeletePersistentNew_NoTxn() {
   PersistenceManager pm = getPersistenceManager();
   KitchenSink ks = KitchenSink.newKitchenSink("key");
   pm.makePersistent(ks);
   String keyStr = ks.key;
   pm.deletePersistent(ks);
   pm.close();
   pm = PMF.get().getPersistenceManager();
   try {
     pm.getObjectById(KitchenSink.class, keyStr);
     fail("expected onfe");
   } catch (JDOObjectNotFoundException onfe) {
     // good
   }
 }
Ejemplo n.º 14
0
 /* (non-Javadoc)
  * @see com.volvo.ea.dao.VolvoDAO#delete(com.volvo.ea.entities.Integration)
  */
 @Override
 public void delete(Key pKey) throws Throwable {
   if (this.pmf != null) {
     if (pKey != null) {
       PersistenceManager pm = this.pmf.getPersistenceManager();
       try {
         Integration integration = pm.getObjectById(Integration.class, pKey);
         pm.deletePersistent(integration);
       } finally {
         pm.close();
       }
     } else {
       throw new Throwable("The integration to persist is null");
     }
   } else {
     throw new Throwable("No PersistenceManagerFactory defined to persist integrations");
   }
 }
Ejemplo n.º 15
0
  @Test
  public void testNonTransactionalDelete() {
    PersistenceManager pm = getPersistenceManager();
    String keyStr = "key";

    beginTxn();
    pm.makePersistent(KitchenSink.newKitchenSink(keyStr));
    commitTxn();
    KitchenSink ks = pm.getObjectById(KitchenSink.class, keyStr);
    assertNotNull(ks);
    pm.deletePersistent(ks);
    try {
      pm.getObjectById(KitchenSink.class, keyStr);
      fail("expected onfe");
    } catch (JDOObjectNotFoundException onfe) {
      // good
    }
  }
Ejemplo n.º 16
0
 @Test
 public void testDeletePersistentNew() {
   PersistenceManager pm = getPersistenceManager();
   beginTxn();
   KitchenSink ks = KitchenSink.newKitchenSink("key");
   pm.makePersistent(ks);
   String keyStr = ks.key;
   pm.deletePersistent(ks);
   commitTxn();
   beginTxn();
   try {
     pm.getObjectById(KitchenSink.class, keyStr);
     fail("expected onfe");
   } catch (JDOObjectNotFoundException onfe) {
     // good
   } finally {
     rollbackTxn();
   }
 }
Ejemplo n.º 17
0
 private void doUnregister(String deviceRegistrationID, String accountName) {
   log.info("in unregister: accountName = " + accountName);
   PersistenceManager pm = PMF.get().getPersistenceManager();
   try {
     List<DeviceInfo> registrations = DeviceInfo.getDeviceInfoForUser(accountName);
     for (int i = 0; i < registrations.size(); i++) {
       DeviceInfo deviceInfo = registrations.get(i);
       if (deviceInfo.getDeviceRegistrationID().equals(deviceRegistrationID)) {
         pm.deletePersistent(deviceInfo);
         // Keep looping in case of duplicates
       }
     }
   } catch (JDOObjectNotFoundException e) {
     log.warning("User " + accountName + " unknown");
   } catch (Exception e) {
     log.warning("Error unregistering device: " + e.getMessage());
   } finally {
     pm.close();
   }
 }
Ejemplo n.º 18
0
  public static void reset(String name) {
    PersistenceManager pm = PMF.get().getPersistenceManager();

    try {
      pm.currentTransaction().begin();
      try {
        NamedCounter counter =
            pm.getObjectById(NamedCounter.class, KeyFactory.keyToString(getKeyForName(name)));
        pm.deletePersistent(counter);
      } catch (JDOObjectNotFoundException e) {
        // Object isn't there, so ignore it.
        return;
      }
      pm.currentTransaction().commit();
    } finally {
      if (pm.currentTransaction().isActive()) {
        pm.currentTransaction().rollback();
      }
    }
  }
Ejemplo n.º 19
0
 public void removeStock(String symbol) throws NotLoggedInException {
   checkLoggedIn();
   PersistenceManager pm = getPersistenceManager();
   try {
     long deleteCount = 0;
     Query q = pm.newQuery(Stock.class, "user == u");
     q.declareParameters("com.google.appengine.api.users.User u");
     List<Stock> stocks = (List<Stock>) q.execute(getUser());
     for (Stock stock : stocks) {
       if (symbol.equals(stock.getSymbol())) {
         deleteCount++;
         pm.deletePersistent(stock);
       }
     }
     if (deleteCount != 1) {
       LOG.log(Level.WARNING, "removeStock deleted " + deleteCount + " Stocks");
     }
   } finally {
     pm.close();
   }
 }
Ejemplo n.º 20
0
 @SuppressWarnings({"unchecked"})
 private void logOut(HttpServletRequest req, HttpServletResponse resp, PersistenceManager pm)
     throws IOException {
   long id = Long.parseLong(req.getRequestURI().substring("/log-out/".length()));
   SqlCloudSession session = lookupCloudSessionById(id, pm);
   long deleted = 0;
   Transaction tx = pm.currentTransaction();
   tx.begin();
   try {
     pm.deletePersistent(session);
     deleted++;
     tx.commit();
   } finally {
     if (tx.isActive()) tx.rollback();
   }
   if (deleted >= 1) {
     resp.setStatus(200);
   } else {
     setResponse(resp, 404, "no such session");
   }
 }
Ejemplo n.º 21
0
  @Override
  public ArrayList<ProductDTO> deleteProduct(ProductDTO productDTO) throws NotLoggedInException {
    Product productItem = null;
    boolean delete = true;
    PersistenceManager pm = getPersistenceManager();
    try {
      productItem = pm.getObjectById(Product.class, productDTO.getId());
      if (delete) {
        pm.deletePersistent(productItem);
      }

    } finally {
      pm.close();
    }

    if (delete) {
      return getProducts();
    } else {
      return null;
    }
  }
  @Test
  public void testCallBack() {
    PersistenceManager pm = TestTools.openPM();
    pm.currentTransaction().begin();

    TestPreStore ps = new TestPreStore();
    TestPostLoad pl = new TestPostLoad();
    TestPreClear pc = new TestPreClear();
    TestPreDelete pd = new TestPreDelete();

    pm.makePersistent(ps);
    pm.makePersistent(pl);
    pm.makePersistent(pc);
    pm.makePersistent(pd);

    assertFalse(TestPreStore.storeCalled);
    assertFalse(TestPostLoad.loadCalled);
    assertFalse(TestPreClear.clearCalled);
    assertFalse(TestPreDelete.deleteCalled);

    pm.currentTransaction().commit();

    assertTrue(TestPreStore.storeCalled);
    assertTrue(TestPreClear.clearCalled);
    assertFalse(TestPostLoad.loadCalled);
    assertFalse(TestPreDelete.deleteCalled);

    pm.currentTransaction().begin();

    pl.getI();
    assertTrue(TestPostLoad.loadCalled);

    pm.deletePersistent(pd);
    assertFalse(TestPreDelete.deleteCalled);

    pm.currentTransaction().commit();
    assertTrue(TestPreDelete.deleteCalled);

    TestTools.closePM();
  }
Ejemplo n.º 23
0
  public static Question execute(Question aQuestion) {

    PersistenceManager pm = null;
    Question question = null;
    try {
      pm = PMF.get().getPersistenceManager();

      // Get managed instance.  aQuestion might be transient.
      question = QuestionGetSingle.getQuestion(pm, aQuestion.getKey().getId());
      pm.deletePersistent(question);

      aQuestion.setLastUpdateTime(new Date());
      aQuestion.setLastUpdateUserId(aQuestion.getLastUpdateUserId());
      QuestionHistory questionHistory = new QuestionHistory(aQuestion, DataConstants.DELETE);
      pm.makePersistent(questionHistory);
    } finally {
      if (pm != null) {
        pm.close();
      }
    }
    return question;
  }
Ejemplo n.º 24
0
 @Override
 @SuppressWarnings("unchecked")
 public void removeEntries(List<DictionaryEntry> entries) throws NotLoggedInException {
   checkLoggedIn();
   PersistenceManager pm = getPersistenceManager();
   try {
     Query q = pm.newQuery(PersistentDictionaryEntry.class, "user == u");
     q.declareParameters("com.google.appengine.api.users.User u");
     List<PersistentDictionaryEntry> existingEntries =
         (List<PersistentDictionaryEntry>) q.execute(getUser());
     Set<String> encodedEntries = encodeEntries(entries);
     for (PersistentDictionaryEntry entry : existingEntries) {
       if (encodedEntries.contains(encodeEntry(entry))) {
         pm.deletePersistent(entry);
       }
     }
     LOG.log(
         Level.INFO, "user " + getUser().getUserId() + " deleted " + entries.size() + " entries");
   } finally {
     pm.close();
   }
 }
Ejemplo n.º 25
0
  public static String sendMessage(ServletContext context, String recipient, String message) {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
      UserService userService = UserServiceFactory.getUserService();
      User user = userService.getCurrentUser();
      String sender = "nobody";
      if (user != null) {
        sender = user.getEmail();
      }
      log.info("sendMessage: sender = " + sender);
      log.info("sendMessage: recipient = " + recipient);
      log.info("sendMessage: message = " + message);

      // ok = we sent to at least one device.
      boolean ok = false;

      // Send push message to phone
      C2DMessaging push = C2DMessaging.get(context);
      boolean res = false;

      String collapseKey = "" + message.hashCode();

      // delete will fail if the pm is different than the one used to
      // load the object - we must close the object when we're done

      List<DeviceInfo> registrations = null;
      registrations = DeviceInfo.getDeviceInfoForUser(recipient);
      log.info("sendMessage: got " + registrations.size() + " registrations");

      // Deal with upgrades and multi-device:
      // If user has one device with an old version and few new ones -
      // the old registration will be deleted.
      if (registrations.size() > 1) {
        // Make sure there is no 'bare' registration
        // Keys are sorted - check the first
        DeviceInfo first = registrations.get(0);
        Key oldKey = first.getKey();
        if (oldKey.toString().indexOf("#") < 0) {
          // multiple devices, first is old-style.
          registrations.remove(0); // don't send to it
          pm.deletePersistent(first);
        }
      }

      int numSendAttempts = 0;
      for (DeviceInfo deviceInfo : registrations) {
        if (!"ac2dm".equals(deviceInfo.getType())) {
          continue; // user-specified device type
        }

        res = doSendViaC2dm(message, sender, push, collapseKey, deviceInfo);
        numSendAttempts++;

        if (res) {
          ok = true;
        }
      }

      if (ok) {
        return "Success: Message sent";
      } else if (numSendAttempts == 0) {
        return "Failure: User " + recipient + " not registered";
      } else {
        return "Failure: Unable to send message";
      }
    } catch (Exception e) {
      return "Failure: Got exception " + e;
    } finally {
      pm.close();
    }
  }
Ejemplo n.º 26
0
 public void deletePersistent(Object persistent) {
   pm.deletePersistent(persistent);
 }
Ejemplo n.º 27
0
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    log.log(Level.INFO, "RegisterServlet.doPOST() : START RegisterServlet.doPOST()");

    resp.setContentType("text/plain");

    GeatteRegisterRequestInfo reqInfo =
        GeatteRegisterRequestInfo.processRequest(req, resp, getServletContext());
    if (reqInfo == null) {
      log.severe("RegisterServlet.doPOST() : can not load RequestInfo!!");
      return;
    }

    // Because the deviceRegistrationId isn't static, we use a static
    // identifier for the device. (Can be null in older clients)
    String deviceId = reqInfo.getParameter(Config.DEVICE_ID_PARAM);

    if (deviceId == null) {
      resp.setStatus(400);
      resp.getWriter().println(ERROR_STATUS + "(Must specify " + Config.DEVICE_ID_PARAM + ")");
      log.severe(
          "RegisterServlet.doPOST() : Missing device id, " + Config.DEVICE_ID_PARAM + " is null");
      return;
    } else {
      log.log(
          Level.INFO,
          "RegisterServlet.doPOST() : user sent a " + Config.DEVICE_ID_PARAM + " = " + deviceId);
    }

    String phoneNumber = reqInfo.getParameter(Config.DEV_PHONE_NUMBER_PARAM);

    if (phoneNumber == null) {
      resp.setStatus(400);
      resp.getWriter()
          .println(ERROR_STATUS + "(Must specify " + Config.DEV_PHONE_NUMBER_PARAM + ")");
      log.severe(
          "RegisterServlet.doPOST() : Missing phone number, "
              + Config.DEV_PHONE_NUMBER_PARAM
              + " is null");
      return;
    } else {
      log.log(
          Level.INFO,
          "RegisterServlet.doPOST() : user sent a "
              + Config.DEV_PHONE_NUMBER_PARAM
              + " = "
              + phoneNumber);
    }

    String phoneCountryIso = reqInfo.getParameter(Config.DEV_PHONE_COUNTRY_ISO_PARAM);

    if (phoneCountryIso == null) {
      // default is us
      phoneCountryIso = "us";
      log.severe(
          "RegisterServlet.doPOST() : Missing phone country iso, "
              + Config.DEV_PHONE_COUNTRY_ISO_PARAM
              + " is null");
      return;
    } else {
      log.log(
          Level.INFO,
          "RegisterServlet.doPOST() : user sent a "
              + Config.DEV_PHONE_COUNTRY_ISO_PARAM
              + " = "
              + phoneCountryIso);
    }

    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    PhoneNumber numberProto = null;
    try {
      numberProto = phoneUtil.parse(phoneNumber, phoneCountryIso);
    } catch (NumberParseException npe) {
      log.log(Level.WARNING, "RegisterServlet.doPOST(): NumberParseException was thrown: ", npe);
    }

    if (numberProto != null && phoneUtil.isValidNumber(numberProto)) {
      phoneNumber = phoneUtil.format(numberProto, PhoneNumberFormat.E164);
    } else {
      log.log(
          Level.WARNING,
          "RegisterServlet.doPOST() : Invalid phone number so use passed-in number, "
              + Config.DEV_PHONE_NUMBER_PARAM
              + " = "
              + phoneNumber
              + ", countryIso = "
              + phoneCountryIso);
    }

    if (reqInfo.deviceRegistrationID == null) {
      resp.setStatus(400);
      resp.getWriter().println(ERROR_STATUS + "(Must specify " + Config.DEV_REG_ID_PARAM + ")");
      log.severe(
          "RegisterServlet.doPOST() : Missing registration id, reqInfo.deviceRegistrationID is null");
      return;
    } else {
      log.log(
          Level.INFO,
          "RegisterServlet.doPOST() : reqInfo.deviceRegistrationID = "
              + reqInfo.deviceRegistrationID);
    }

    String deviceName = reqInfo.getParameter(Config.DEVICE_NAME_PARAM);

    if (deviceName == null) {
      deviceName = "Phone";
      log.log(
          Level.INFO,
          "RegisterServlet.doPOST() : use default "
              + Config.DEVICE_NAME_PARAM
              + " = "
              + deviceName);
    } else {
      log.log(
          Level.INFO,
          "RegisterServlet.doPOST() : user sent a "
              + Config.DEVICE_NAME_PARAM
              + " = "
              + deviceName);
    }
    // TODO: generate the device name by adding a number suffix for multiple
    // devices of same type. Change android app to send model/type.

    String deviceType = reqInfo.getParameter(Config.DEVICE_TYPE_PARAM);

    if (deviceType == null) {
      deviceType = DeviceInfo.TYPE_AC2DM;
      log.log(
          Level.INFO,
          "RegisterServlet.doPOST() : use default "
              + Config.DEVICE_TYPE_PARAM
              + " = "
              + deviceType);
    } else {
      log.log(
          Level.INFO,
          "RegisterServlet.doPOST() : user sent a "
              + Config.DEVICE_TYPE_PARAM
              + " = "
              + deviceType);
    }

    // Context-shared PMF.
    PersistenceManager pm = DBHelper.getPMF(getServletContext()).getPersistenceManager();

    try {
      List<DeviceInfo> registrations = reqInfo.devices;

      if (registrations.size() > MAX_DEVICES) {
        log.log(
            Level.INFO,
            "RegisterServlet.doPOST() : user has too many devices, registrations.size = "
                + registrations.size());
        // we could return an error - but user can't handle it yet.
        // we can't let it grow out of bounds.
        // TODO: we should also define a 'ping' message and
        // expire/remove
        // unused registrations
        DeviceInfo oldest = registrations.get(0);
        if (oldest.getRegistrationTimestamp() == null) {
          log.log(
              Level.INFO,
              "RegisterServlet.doPOST() : user has too many devices, trying to remove old one = "
                  + oldest.getDeviceRegistrationID());
          pm.deletePersistent(oldest);
        } else {
          long oldestTime = oldest.getRegistrationTimestamp().getTime();
          for (int i = 1; i < registrations.size(); i++) {
            if (registrations.get(i).getRegistrationTimestamp().getTime() < oldestTime) {
              oldest = registrations.get(i);
              oldestTime = oldest.getRegistrationTimestamp().getTime();
            }
          }
          log.log(
              Level.INFO,
              "RegisterServlet.doPOST() : user has too many devices, trying to remove old one = "
                  + oldest.getDeviceRegistrationID());
          pm.deletePersistent(oldest);
        }
      }

      // Get device if it already exists, else create
      // String suffix = (deviceId != null ? "#" +
      // Long.toHexString(Math.abs(deviceId.hashCode())) : "");
      // Key key = KeyFactory.createKey(DeviceInfo.class.getSimpleName(),
      // reqInfo.userName + suffix);
      Key key = KeyFactory.createKey(DeviceInfo.class.getSimpleName(), deviceId);

      DeviceInfo device = null;
      try {
        device = pm.getObjectById(DeviceInfo.class, key);
      } catch (JDOObjectNotFoundException e) {
      }
      if (device == null) {
        log.log(
            Level.INFO,
            "RegisterServlet.doPOST() : can not find a DeviceInfo by key = "
                + key
                + ", create a new one");

        // clean devices for same phone number, only one device allowed for one phone
        try {
          List<DeviceInfo> devicesForSameNumber =
              DeviceInfo.getDeviceInfoForNumber(pm, phoneNumber, phoneCountryIso);
          for (DeviceInfo deviceSameNumber : devicesForSameNumber) {
            pm.deletePersistent(deviceSameNumber);
          }
        } catch (JDOObjectNotFoundException e) {
        }

        device = new DeviceInfo(key, reqInfo.deviceRegistrationID);
        device.setType(deviceType);
      } else {
        log.log(
            Level.INFO,
            "RegisterServlet.doPOST() : find a DeviceInfo by key = "
                + key
                + ", update deviceRegistrationID to "
                + reqInfo.deviceRegistrationID);

        // update registration id
        device.setDeviceRegistrationID(reqInfo.deviceRegistrationID);
        device.setRegistrationTimestamp(new Date());
      }

      device.setPhoneNumber(phoneNumber); // update phoneNumber
      device.setCountryCode(phoneCountryIso); // update country code
      device.setUserEmail(reqInfo.getUserEmail()); // update user email
      device.setDeviceName(deviceName); // update display name
      // TODO: only need to write if something changed, for chrome nothing
      // changes, we just create a new channel
      pm.makePersistent(device);

      log.log(
          Level.INFO,
          "RegisterServlet.doPOST() : Registered device userEmail = "
              + reqInfo.getUserEmail()
              + ", deviceType = "
              + deviceType
              + ", deviceRegistrationID = "
              + reqInfo.deviceRegistrationID
              + ", key = "
              + key);

      // if type is IOS, register to Urban
      if (device.getType().equalsIgnoreCase(DeviceInfo.TYPE_IOS)) {
        doRegisterIOSToUrban(device);
        resp.getWriter().println(OK_STATUS);
      } else if (device.getType().equalsIgnoreCase(DeviceInfo.TYPE_ANDROID)
          || device.getType().equalsIgnoreCase(DeviceInfo.TYPE_AC2DM)) {
        resp.getWriter().println(OK_STATUS);
      } else {
        resp.getWriter().println(ERROR_STATUS + "(Wrong " + Config.DEVICE_TYPE_PARAM + ")");
      }

      log.log(Level.INFO, "RegisterServlet.doPOST() : END RegisterServlet.doPOST()");
    } catch (Exception e) {
      resp.setStatus(500);
      resp.getWriter().println(ERROR_STATUS + " (Error registering device)");
      log.log(Level.WARNING, "RegisterServlet.doPOST() : Error registering device.", e);
    } finally {
      pm.close();
    }
  }
Ejemplo n.º 28
0
  private void doRegister(
      String deviceRegistrationId, String deviceType, String deviceId, String accountName)
      throws Exception {
    log.info("in register: accountName = " + accountName);
    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
      List<DeviceInfo> registrations = DeviceInfo.getDeviceInfoForUser(accountName);

      log.info("got registrations");
      if (registrations.size() > MAX_DEVICES) {
        log.info("got registrations > MAX_DEVICES");
        // we could return an error - but user can't handle it yet.
        // we can't let it grow out of bounds.
        // TODO: we should also define a 'ping' message and expire/remove
        // unused registrations
        DeviceInfo oldest = registrations.get(0);
        if (oldest.getRegistrationTimestamp() == null) {
          pm.deletePersistent(oldest);
        } else {
          long oldestTime = oldest.getRegistrationTimestamp().getTime();
          for (int i = 1; i < registrations.size(); i++) {
            if (registrations.get(i).getRegistrationTimestamp().getTime() < oldestTime) {
              oldest = registrations.get(i);
              oldestTime = oldest.getRegistrationTimestamp().getTime();
            }
          }
          pm.deletePersistent(oldest);
        }
      }

      // Get device if it already exists, else create
      String suffix =
          (deviceId != null ? "#" + Long.toHexString(Math.abs(deviceId.hashCode())) : "");
      log.info("suffix = " + suffix);
      Key key = KeyFactory.createKey(DeviceInfo.class.getSimpleName(), accountName + suffix);
      log.info("key = " + key);

      DeviceInfo device = null;
      try {
        device = pm.getObjectById(DeviceInfo.class, key);
      } catch (JDOObjectNotFoundException e) {
        log.info("Caught JDOObjectNotFoundException");
      }
      if (device == null) {
        device = new DeviceInfo(key, deviceRegistrationId);
        device.setType(deviceType);
      } else {
        // update registration id
        device.setDeviceRegistrationID(deviceRegistrationId);
        device.setRegistrationTimestamp(new Date());
      }

      pm.makePersistent(device);
      return;
    } catch (Exception e) {
      log.info("Caught exception: " + e);
      throw e;
    } finally {
      pm.close();
    }
  }
Ejemplo n.º 29
0
 public void elminarLugarPedido(String codLugar) {
   PersistenceManager pm = getPersistenceManager();
   LugarPedido l = pm.getObjectById(LugarPedido.class, codLugar);
   pm.deletePersistent(l);
 }
Ejemplo n.º 30
0
  /**
   * Tests extent across transaction boundaries. The problem here is that extents are pos-indices,
   * which are COWed. So during a commit, object may get rewritten, changing the index, meaning that
   * the positions in the extents are wrong.
   *
   * <p>In this test, we iterate over the extent and delete previous objects, but never ahead of the
   * extent. That should work fine.
   */
  @Test
  public void testExtentDeletionAcrossCommit() {
    int N = 10000;
    PersistenceManager pm = TestTools.openPM();
    // pm.setIgnoreCache(false);
    pm.currentTransaction().begin();

    for (int i = 0; i < N; i++) {
      TestClass tc = new TestClass();
      tc.setInt(i);
      pm.makePersistent(tc);
    }

    pm.currentTransaction().commit();
    pm.currentTransaction().begin();

    // modify all --> create empty space in the beginning of the DB
    for (TestClass tc : pm.getExtent(TestClass.class)) {
      tc.setLong(12);
    }

    pm.currentTransaction().commit();
    pm.currentTransaction().begin();

    // start iterating
    Iterator<TestClass> it = pm.getExtent(TestClass.class).iterator();
    int n = 0;
    int currentI = -1;
    while (it.hasNext()) {
      n++;
      TestClass tc = it.next();
      assertEquals(currentI + 1, tc.getInt());
      currentI = tc.getInt();
      pm.deletePersistent(tc);
      if (n % 1000 == 0) {
        pm.currentTransaction().commit();
        pm.currentTransaction().begin();
        break;
      }
    }

    try {
      it.hasNext();
      fail();
    } catch (JDOUserException e) {
      // good
    }

    try {
      it.next();
      fail();
    } catch (JDOUserException e) {
      // good
    }

    pm.currentTransaction().commit();
    pm.currentTransaction().begin();

    // Assert that not all have been removed
    it = pm.getExtent(TestClass.class).iterator();
    assertTrue(it.hasNext());
    while (it.hasNext()) {
      n++;
      TestClass tc = it.next();
      assertEquals(currentI + 1, tc.getInt());
      currentI = tc.getInt();
      pm.deletePersistent(tc);
    }
    assertFalse(pm.getExtent(TestClass.class).iterator().hasNext());

    assertEquals(N, n);
    assertEquals(N, currentI + 1);

    pm.currentTransaction().commit();
    TestTools.closePM();
  }