Пример #1
0
	public GameEnded endGame(String gameUUID, String winnerUUID) {
		PersistenceManager pm = getPersistenceManager();
		GameEnded retObject;
		ArrayList<HashMap<String, String>> apnData =
				new ArrayList<HashMap<String, String>>();
		String winnerCode_Name;
		try {
			Game g = pm.getObjectById(Game.class, gameUUID);
			GameUser winner = pm.getObjectById(GameUser.class, winnerUUID);
			winnerCode_Name = winner.getUserCodeName();
			g.endGame(winner);
			winner.removeTarget(gameUUID);
			winner.addWin(); //Increments Winner's win count
			winner.setUserStatus("Registered");
			for (String usrUUID: g.getPlayerUUIDs()) {
				if (usrUUID != winnerUUID) {
					GameUser usr = pm.getObjectById(GameUser.class, usrUUID);
					usr.setUserStatus("Registered");
					HashMap<String, String> entry = 
							new HashMap<String, String>();
					entry.put("apn", usr.getAPN());
					entry.put("platformId", usr.getPlatformID());
					apnData.add(entry);
				}
			}
		} finally {
			pm.close();
		}
		retObject = new GameEnded(apnData, winnerCode_Name);
		return retObject;
	}
Пример #2
0
	public UserKilled killUser(String gameUUID, String assassinUUID, String victimUUID) {
		PersistenceManager pm = getPersistenceManager();
		ArrayList<HashMap<String, String>> victimAPN = new ArrayList<HashMap<String, String>>();
		ArrayList<HashMap<String, String>> otherAPN = new ArrayList<HashMap<String, String>>();
		String victimCodeName;
		String nextTargetUUID;
		try {
			Game g = pm.getObjectById(Game.class, gameUUID);
			GameUser assassin = pm.getObjectById(GameUser.class, assassinUUID);
			GameUser victim = pm.getObjectById(GameUser.class, victimUUID);
			victim.setUserStatus("Playing - Dead");
			
			nextTargetUUID = killUser(gameUUID, assassin, victim);
			victimCodeName = victim.getUserCodeName();
			
			//Collects APN information
			for (String usrUUID: g.getPlayerUUIDs()) {
				GameUser usr = pm.getObjectById(GameUser.class, usrUUID);
				HashMap<String, String> entry = new HashMap<String, String>();
				entry.put("apn",usr.getAPN());
				entry.put("platformId", usr.getPlatformID());
				if (usrUUID == victimUUID) {
					victimAPN.add(entry);
				} else if (usrUUID != assassinUUID) {
					otherAPN.add(entry);
				}
			}
		} finally {
			pm.close();
		}
		UserKilled retObject = new UserKilled(otherAPN, victimAPN, 
				victimCodeName, nextTargetUUID);
		return retObject;
	}
Пример #3
0
	public GameData getGamePlayData(String gameUUID) {
		PersistenceManager pm = getPersistenceManager();
		GameData retObject;
		try {
			Game g = pm.getObjectById(Game.class, gameUUID);
			retObject = pm.getObjectById(GameData.class, g.getGamePlayDataUUID());
		} finally {
			pm.close();
		}
		return retObject;
	}
Пример #4
0
	public GameUserImage getUsrThumbnail(String usrUUID) {
		PersistenceManager pm = getPersistenceManager();
		GameUserImage retObject;
		try {
			GameUser a = pm.getObjectById(GameUser.class, usrUUID);
			retObject = pm.getObjectById(GameUserImage.class, a.getThumbnailUUID());
		} finally {
			pm.close();
		}
		return retObject;
	}
Пример #5
0
  /** test batch loading. */
  @SuppressWarnings("unchecked")
  @Test
  public void testBatchLoading2() {
    System.out.println("Batch-test 2");
    PersistenceManager pm = null;
    Object oid = null;
    try {
      pm = TestTools.openPM();
      pm.currentTransaction().begin();
      DBArrayList<Object> dbv = new DBArrayList<Object>();
      for (int i = 0; i < 120; i++) {
        dbv.add(new PersistentDummyImpl());
      }
      pm.makePersistent(dbv);
      oid = pm.getObjectId(dbv);
      pm.currentTransaction().commit();
      pm.close();
      pm = null;

      pm = TestTools.openPM();
      pm.currentTransaction().begin();
      dbv = (DBArrayList<Object>) pm.getObjectById(oid);
      dbv.setBatchSize(110);
      for (Object o : dbv) {
        o.getClass();
      }
      pm.currentTransaction().commit();
    } finally {
      if (pm != null) {
        pm.close();
      }
    }
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Find listings under a percentage
    List<SteamMarketListing> listings = SteamMarketUtility.getSteamMarketListings();

    PersistenceManager pm = PMF.get().getPersistenceManager();
    String messageBody = "";
    for (int i = 0; i < listings.size(); i++) {
      SteamMarketListing listing = listings.get(i);
      MarketHistoryJDO history;
      try {
        history = (MarketHistoryJDO) pm.getObjectById(MarketHistoryJDO.class, listing.getLink());
        double average = history.averagePrice();
        double startingPrice = listing.getStartingPrice();
        if (startingPrice < (1 - PERCENT) * average) {
          messageBody += "Item:" + history.getUrl() + "<br />";
          messageBody += "Current: " + startingPrice + "<br />";
          messageBody += "Average: " + average + "<br />";
          messageBody += "<br />";
        }
      } catch (JDOObjectNotFoundException e) {
        // Item not found - listed since last crawl. Just wait for the item to be crawled.
      }
    }
    response.getWriter().write(messageBody);

    pm.close();
  }
Пример #7
0
 public ServiceResult<Page> findPage(Long id, boolean isIncreaseView) {
   ServiceResult<Page> result = new ServiceResult<Page>();
   Page page = null;
   PersistenceManager pm = null;
   try {
     pm = PMF.get().getPersistenceManager();
     page = pm.getObjectById(Page.class, id);
     if (page == null) {
       result.setOK(false);
       result.setMessage(Global.messages.getString("no_page_found"));
     } else {
       result.setMessage(Global.messages.getString("page_found"));
       result.setOK(true);
       result.setResult(page);
       if (isIncreaseView) {
         page.setPage_view(page.getPage_view() + 1);
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
     result.setMessage(Global.messages.getString("find_page_fail"));
   } finally {
     try {
       pm.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return result;
 }
  /**
   * Test serialisation.
   *
   * <p>If a transaction has only new objects (no modified objects) and if the new objects have
   * other persistent capable objects referenced (but no have called makePersistent() on them) and
   * if we are not in the first transaction in a session, then we get the following NPE. See issue
   * #57.
   */
  @Test
  public void testSerialization() {
    TestTools.defineSchema(ProjectPC.class, CoordinatePC.class);
    PersistenceManager pm = TestTools.openPM();
    pm.currentTransaction().begin();

    CoordinatePC x = new CoordinatePC();
    pm.makePersistent(x);

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

    ProjectPC s = new ProjectPC(new ProjectPC(null));
    pm.makePersistent(s);
    Object oid = pm.getObjectId(s);
    pm.currentTransaction().commit();
    TestTools.closePM();

    pm = TestTools.openPM();
    pm.currentTransaction().begin();
    ProjectPC s2 = (ProjectPC) pm.getObjectById(oid);
    assertNotNull(s2);
    pm.currentTransaction().commit();
    pm.close();
  }
Пример #9
0
  public Object loadPojo(final TypedOid oid) {

    // REVIEW: does it make sense to get these directly?  not sure, so for now have decided to fail
    // fast.
    if (oid instanceof AggregatedOid) {
      throw new UnsupportedOperationException(
          "Cannot retrieve aggregated objects directly, oid: " + oid.enString(getOidMarshaller()));
    }

    final RootOid rootOid = (RootOid) oid;

    Object result = null;
    try {
      final Class<?> cls = clsOf(rootOid);
      final Object jdoObjectId = JdoObjectIdSerializer.toJdoObjectId(rootOid);
      final PersistenceManager pm = getPersistenceManager();
      FetchPlan fetchPlan = pm.getFetchPlan();
      fetchPlan.addGroup(FetchGroup.DEFAULT);
      result = pm.getObjectById(cls, jdoObjectId);
    } catch (final RuntimeException e) {
      throw e;
    }

    if (result == null) {
      throw new ObjectNotFoundException(oid);
    }
    return result;
  }
Пример #10
0
 public ServiceResult<Void> updatePage(Page editPage) {
   ServiceResult<Void> result = new ServiceResult<Void>();
   Page page = null;
   PersistenceManager pm = null;
   try {
     pm = PMF.get().getPersistenceManager();
     page = pm.getObjectById(Page.class, editPage.getId());
     if (page == null) {
       result.setOK(false);
       result.setMessage(Global.messages.getString("no_page_found"));
     } else {
       page.setContent(editPage.getContent());
       page.setDate_post(editPage.getDate_post());
       page.setLast_modified(editPage.getLast_modified());
       page.setLink_thumbnail(editPage.getLink_thumbnail());
       page.setName(editPage.getName());
       page.setPage_view(editPage.getPage_view());
       page.setSetCategoryKeys(editPage.getSetCategoryKeys());
       page.setSetProduct(editPage.getSetProduct());
       result.setOK(true);
       result.setMessage(Global.messages.getString("update_page_successfully"));
     }
   } catch (Exception e) {
     result.setMessage(Global.messages.getString("update_page_fail"));
     result.setOK(false);
     e.printStackTrace();
   } finally {
     try {
       pm.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return result;
 }
Пример #11
0
  public static int addAndGet(String name, int delta) {
    PersistenceManager pm = PMF.get().getPersistenceManager();

    NamedCounter counter = null;

    try {
      // Detach the persisted objects after changes are commited since we
      // access members after the transaction is commited. Without this
      // setting, the counter members could be wiped after the transaction
      // is
      // closed.
      pm.setDetachAllOnCommit(true);
      pm.currentTransaction().begin();
      try {
        counter = pm.getObjectById(NamedCounter.class, KeyFactory.keyToString(getKeyForName(name)));
        counter.add(delta);
      } catch (JDOObjectNotFoundException e) {
        counter = new NamedCounter(name);
        // Only need this make persistent call here, since any counter
        // already retrieved using JDO will be marked as persistent once
        // we increment the counter; JDO will automatically write it to
        // the Datastore on commit.
        counter.add(delta);
        pm.makePersistent(counter);
      }
      pm.currentTransaction().commit();
    } finally {
      if (pm.currentTransaction().isActive()) {
        pm.currentTransaction().rollback();
      }
    }
    return counter.getCount();
  }
 @RequestMapping(value = "/mobileform/{id}", method = RequestMethod.POST)
 public MobileForm saveMobileForm(@RequestBody MobileForm mht) throws IOException {
   UserService userService = UserServiceFactory.getUserService();
   User user = userService.getCurrentUser();
   if (userService.isUserLoggedIn()) {
     PersistenceManager pm = PMF.get().getPersistenceManager();
     try {
       Date now = new Date();
       if (mht.getId().equalsIgnoreCase("123")) {
         mht.setId(KeyFactory.keyToString(KeyFactory.createKey(user.getEmail(), now.getTime())));
         mht.setCreator(user.getEmail());
         MobileForm mt = pm.makePersistent(mht);
         return mt;
       } else {
         Key k = KeyFactory.createKey(MobileForm.class.getSimpleName(), mht.getId());
         MobileForm m = pm.getObjectById(MobileForm.class, k);
         m.setMethod(mht.getMethod());
         return pm.makePersistent(m);
       }
     } finally {
       pm.close();
     }
   }
   return null;
 }
Пример #13
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String button = req.getParameter("id");
    System.out.println("Funtion Comes inside fetch servlet of AnswerConnect");
    resp.setContentType("text/json");
    PrintWriter out = resp.getWriter();
    PersistenceManager pmf = PMF.get().getPersistenceManager();
    /*Query q = pmf.newQuery(Fullclient.class);
    q.setFilter("ID==clickedId");
    q.declareParameters("String clickedId");*/
    System.out.println("data value is setted");
    try {
      AnswerConnect results = (AnswerConnect) pmf.getObjectById(AnswerConnect.class, button);
      System.out.println(results);
      System.out.println("query successfull");
      ObjectWriter objectwriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
      String json = objectwriter.writeValueAsString(results);
      System.out.println(json);
      out.print(json);
    } catch (JDOObjectNotFoundException e) {

    } finally {
      pmf.close();
      out.flush();
      System.out.println("AnswerConnect function closes here");
    }
  }
 @RequestMapping(value = "/resetforgotpassword", method = RequestMethod.POST)
 public String resetforgotPassword(HttpServletRequest request, ModelMap model) {
   String email = HtmlUtils.htmlEscape(request.getParameter("email"));
   if (email != null) {
     String userid = email;
     String password = HtmlUtils.htmlEscape(request.getParameter("password"));
     PersistenceManager pm = PMF.get().getPersistenceManager();
     Query q = pm.newQuery(User.class);
     q.setFilter("email==userid");
     q.declareParameters("String userid");
     List<User> result = (List<User>) q.execute(userid);
     try {
       User c = pm.getObjectById(User.class, result.get(0).getUserId());
       c.setPassword(password);
       model.addAttribute("registered", "Password reset successfully, Login now !!");
       model.addAttribute("subCategoryList", categoryDao.getSubCategoryList());
     } finally {
       pm.close();
     }
     return "login";
   } else {
     model.addAttribute("subCategoryList", categoryDao.getSubCategoryList());
     return "login";
   }
 }
  @Override
  public void onAddArticlesToDeliveryNote(
      User user, Store store, DeliveryNote deliveryNote, Collection<? extends Article> articles) {
    if (logger.isDebugEnabled())
      logger.debug(
          "onAddArticlesToDeliveryNote entered. organisationID="
              + getOrganisationID()
              + " deliveryNote="
              + deliveryNote.getPrimaryKey()
              + " articles.size()="
              + articles.size());

    //		super.onAddArticlesToDeliveryNote(user, store, deliveryNote, articles); // the super method
    // is a noop - at least now. Marco.
    PersistenceManager pm = getPersistenceManager();

    pm.getExtent(VoucherDeliveryNoteActionHandler.class);
    VoucherDeliveryNoteActionHandler deliveryNoteActionHandler =
        (VoucherDeliveryNoteActionHandler)
            pm.getObjectById(
                DeliveryNoteActionHandlerID.create(
                    Organisation.DEV_ORGANISATION_ID,
                    VoucherDeliveryNoteActionHandler.class.getName()));
    deliveryNote.getDeliveryNoteLocal().addDeliveryNoteActionHandler(deliveryNoteActionHandler);
  }
  @TransactionAttribute(
      TransactionAttributeType.SUPPORTS) // Never begin a transaction for report rendering
  @RolesAllowed({org.nightlabs.jfire.reporting.RoleConstants.renderReport_roleID})
  @Override
  public void processScheduledReport(TaskID taskID) throws Exception {

    PersistenceManager pm = createPersistenceManager();
    try {
      if (logger.isDebugEnabled())
        logger.debug("processScheduledReport started, determine parameters");
      Task task = (Task) pm.getObjectById(taskID);
      ScheduledReport scheduledReport = (ScheduledReport) task.getParam();
      if (logger.isDebugEnabled())
        logger.debug(
            "processScheduledReport have "
                + ScheduledReport.describeScheduledReport(scheduledReport));
      RenderReportRequest renderReportRequest = scheduledReport.getRenderReportRequest();
      if (renderReportRequest == null) {
        throw new RenderReportException(
            "Can not render ScheduledReport as the RenderReportRequest is not set. "
                + ScheduledReport.describeScheduledReport(scheduledReport));
      }
      ReportRegistryItemID reportLayoutID = scheduledReport.getReportLayoutID();
      if (reportLayoutID == null) {
        throw new RenderReportException(
            "Can not render ScheduledReport as no ReportLayout is set for it. "
                + ScheduledReport.describeScheduledReport(scheduledReport));
      }
      if (logger.isDebugEnabled())
        logger.debug("processScheduledReport have reportLayoutID " + reportLayoutID);

      Map<String, Object> newParams =
          convertScheduledReportParams(scheduledReport, renderReportRequest);
      renderReportRequest.setParameters(newParams);

      IScheduledReportDeliveryDelegate deliveryDelegate = scheduledReport.getDeliveryDelegate();
      if (deliveryDelegate == null) {
        throw new IllegalStateException(
            "Can not render ScheduledReport as no ScheduledReportDeliveryDelegate is set for it. "
                + ScheduledReport.describeScheduledReport(scheduledReport));
      }
      if (logger.isDebugEnabled())
        logger.debug("processScheduledReport have deliveryDelegate " + deliveryDelegate);

      renderReportRequest.setReportRegistryItemID(reportLayoutID);

      if (logger.isDebugEnabled())
        logger.debug("processScheduledReport rendering ReportLayout " + reportLayoutID);
      RenderedReportLayout renderedReportLayout =
          ReportLayoutRendererUtil.renderReport(pm, renderReportRequest);

      if (logger.isDebugEnabled())
        logger.debug("processScheduledReport delivering rendered report.");
      deliveryDelegate.deliverReportOutput(scheduledReport, renderedReportLayout);

    } finally {
      pm.close();
    }
  }
  @Override
  public T findById(Key key) {
    PersistenceManager pm = getPersistenceManager();

    T t = pm.getObjectById(getPersistentClass(), key);

    return t;
  }
Пример #18
0
 @Override
 public Set<EventCalendar> getOwnedItems(String id) {
   PersistenceManager pm = PMF.get().getPersistenceManager();
   User user = (User) pm.getObjectById(User.class, id);
   Set<EventCalendar> result = user.getOwnedCalendars();
   pm.close();
   return result;
 }
Пример #19
0
	//Game Play
	public TargetInfo getTarget(String gameUUID, String userUUID) {
		PersistenceManager pm = getPersistenceManager();
		String targetUUID, targetCodeName;
		GameUserImage targetThumbnail;
		try {
			GameUser a = pm.getObjectById(GameUser.class, userUUID);
			targetUUID = a.getTargetUUID(gameUUID);
			GameUser targetObject = pm.getObjectById(GameUser.class, targetUUID);
			targetCodeName = targetObject.getUserCodeName();
			targetThumbnail = pm.getObjectById(GameUserImage.class, targetObject.getThumbnailUUID());
		} finally {
			pm.close();
		}
		TargetInfo retObject = new TargetInfo(targetUUID, targetCodeName, 
							targetThumbnail);
		return retObject;
	}
 public User getUser(String email) {
   PersistenceManager persistenceManager = pmf.getPersistenceManager();
   try {
     return persistenceManager.getObjectById(User.class, email);
   } catch (JDOObjectNotFoundException e) {
     return null;
   }
 }
  @Override
  public void delete(T t) {
    PersistenceManager pm = getPersistenceManager();

    if (t.getKey() != null) {
      T atachedT = pm.getObjectById(getPersistentClass(), t.getKey());
      pm.deletePersistent(atachedT);
    }
  }
Пример #22
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
    }
  }
Пример #23
0
	public void deleteUser(String uuid) {
		PersistenceManager pm = getPersistenceManager();
		try {
			GameUser GameUserToDelete = pm.getObjectById(GameUser.class, uuid);
			pm.deletePersistent(GameUserToDelete);
		} finally {
			pm.close();
		}
	}
Пример #24
0
  public static StateRecord get(PersistenceManager pm, String resourceId) {
    try {
      return pm.getObjectById(StateRecord.class, resourceId);
    } catch (JDOObjectNotFoundException e) {

    }

    return null;
  }
Пример #25
0
 public <T> T getObj(Class<T> c, long id) {
   PersistenceManager pm = pmf.getPersistenceManager();
   try {
     T obj = pm.getObjectById(c, id);
     return obj;
   } finally {
     pm.close();
   }
 }
 @Override
 public InventoryObject getInventoryObject(String ID) {
   PersistenceManager persistenceManager = pmf.getPersistenceManager();
   try {
     return persistenceManager.getObjectById(InventoryObject.class, ID);
   } catch (JDOObjectNotFoundException e) {
     return null;
   }
 }
  /** This used to fail because deserialized DbCollection were marked dirty. */
  @SuppressWarnings("unchecked")
  @Test
  public void testSerialization() {
    PersistenceManager pm = TestTools.openPM();
    pm.currentTransaction().begin();
    DBHashMap<TestClass, TestClass> h1 = new DBHashMap<TestClass, TestClass>();
    DBHashMap<TestClass, TestClass> h2 = new DBHashMap<TestClass, TestClass>();
    TestClass k = new TestClass();
    h2.put(k, new TestClass());
    DBArrayList<TestClass> l1 = new DBArrayList<TestClass>();
    DBArrayList<TestClass> l2 = new DBArrayList<TestClass>();
    l2.add(new TestClass());
    pm.makePersistent(h1);
    pm.makePersistent(h2);
    pm.makePersistent(k);
    pm.makePersistent(l1);
    pm.makePersistent(l2);
    Object oid1 = pm.getObjectId(h1);
    Object oid2 = pm.getObjectId(h2);
    Object oidk = pm.getObjectId(k);
    Object oid3 = pm.getObjectId(l1);
    Object oid4 = pm.getObjectId(l2);
    pm.currentTransaction().commit();
    TestTools.closePM();

    pm = TestTools.openPM();
    pm.currentTransaction().begin();
    h1 = (DBHashMap<TestClass, TestClass>) pm.getObjectById(oid1);
    assertEquals(false, JDOHelper.isDirty(h1));
    h2 = (DBHashMap<TestClass, TestClass>) pm.getObjectById(oid2);
    assertEquals(false, JDOHelper.isDirty(h2));
    k = (TestClass) pm.getObjectById(oidk);
    assertEquals(false, JDOHelper.isDirty(k));
    assertEquals(false, JDOHelper.isDirty(h2.get(k)));

    l1 = (DBArrayList<TestClass>) pm.getObjectById(oid3);
    assertEquals(false, JDOHelper.isDirty(l1));
    l2 = (DBArrayList<TestClass>) pm.getObjectById(oid4);
    assertEquals(false, JDOHelper.isDirty(l2));
    assertEquals(false, JDOHelper.isDirty(l2.get(0)));

    pm.currentTransaction().commit();
    pm.close();
  }
 public static ApplicationProperties getApplicationProperties(PersistenceManager pm) {
   ApplicationProperties properties;
   try {
     properties =
         pm.getObjectById(ApplicationProperties.class, KeyMaster.getApplicationPropertiesKey());
   } catch (JDOObjectNotFoundException e) {
     properties = pm.makePersistent(new ApplicationProperties());
   }
   return properties;
 }
  // sets the attributes with the correct class variables
  public void setAtt(PersistenceManager pm, HttpServletRequest req) {
    req.setAttribute("siteName", this.siteName);
    req.setAttribute("teacherName", this.teacherName);
    req.setAttribute("userName", this.userName);

    String id = req.getParameter("id");
    long teacherKey = Long.parseLong(id);
    Teacher teacher = pm.getObjectById(Teacher.class, teacherKey);
    req.setAttribute("teacher", teacher);
  }
Пример #30
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();
   }
 }