Java Code Examples for com.googlecode.objectify.ObjectifyService#begin()

The following examples show how to use com.googlecode.objectify.ObjectifyService#begin() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a wrapped class which contains a list of most downloaded
 * gallery apps and total number of results in database
 * @param start starting index of apps you want
 * @param count number of apps you want
 * @return list of {@link GalleryApp}
 */
@Override
public GalleryAppListResult getMostDownloadedApps(int start, final int count) {
  final List<GalleryApp> apps = new ArrayList<GalleryApp>();
  // If I try to run this in runjobwithretries, it tells me can't run
  // non-ancestor query as a transaction. ObjectifyStorageio has some samples
  // of not using transactions (run with) so I grabbed.

  Objectify datastore = ObjectifyService.begin();
  for (GalleryAppData appData:datastore.query(GalleryAppData.class).order("-numDownloads").filter("active", true).offset(start).limit(count)) {
    GalleryApp gApp = new GalleryApp();
    makeGalleryApp(appData, gApp);
    apps.add(gApp);
  }
  int totalCount = datastore.query(GalleryAppData.class).order("-numDownloads").filter("active", true).count();
  return new GalleryAppListResult(apps, totalCount);
}
 
Example 2
Source File: ExportUtilsTest.java    From tech-gallery with Apache License 2.0 6 votes vote down vote up
/**
 * Setup method for the test.
 */
@Before
public void setUp() {

  helper.setUp();
  ObjectifyService.register(TechGalleryUser.class);
  ObjectifyService.register(UserProfile.class);
  ObjectifyService.register(Technology.class);
  ObjectifyService.begin();

  createProfiles();

  ObjectifyService.ofy().save().entity(techGalleryUser).now();
  ObjectifyService.ofy().save().entity(techGalleryUser2).now();
  ObjectifyService.ofy().save().entity(userProfile).now();
  ObjectifyService.ofy().save().entity(userProfile2).now();
}
 
Example 3
Source File: SignGuestbookServletTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {

  MockitoAnnotations.initMocks(this);
  helper.setUp();
  ds = DatastoreServiceFactory.getDatastoreService();

  //  Set up some fake HTTP requests
  when(mockRequest.getRequestURI()).thenReturn(FAKE_URL);
  when(mockRequest.getParameter("guestbookName")).thenReturn("default2");
  when(mockRequest.getParameter("content")).thenReturn(testPhrase);

  stringWriter = new StringWriter();
  when(mockResponse.getWriter()).thenReturn(new PrintWriter(stringWriter));

  servletUnderTest = new SignGuestbookServlet();

  ObjectifyService.init();
  ObjectifyService.register(Guestbook.class);
  ObjectifyService.register(Greeting.class);

  closeable = ObjectifyService.begin();

  cleanDatastore(ds, "default");
}
 
Example 4
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of reports (flags) for all comments
 * @return list of {@link GalleryCommentReport}
 */
@Override
public List<GalleryCommentReport> getCommentReports() {
  final List<GalleryCommentReport> reports = new ArrayList<GalleryCommentReport>();
  Objectify datastore = ObjectifyService.begin();
  for (GalleryCommentReportData reportData : datastore.query(GalleryCommentReportData.class).order("-dateCreated")) {
    User commenter = storageIo.getUser(reportData.userId);
    String name="unknown";
    if (commenter!= null) {
       name = commenter.getUserName();
    }
    GalleryCommentReport galleryCommentReport = new GalleryCommentReport(reportData.galleryCommentKey.getId(),
        reportData.userId,reportData.report,reportData.dateCreated);
    galleryCommentReport.setUserName(name);
    reports.add(galleryCommentReport);
  }
  return reports;
}
 
Example 5
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the email with a particular emailId
 * @param emailId id of the email
 */  @Override
public Email getEmail(final long emailId) {
  final Result<Email> result = new Result<Email>();
  // if i try to run this in runjobwithretries it tells me can't run
  // non-ancestor query as a transaction. ObjectifyStorageio has some samples
  // of not using transactions (run with) so i grabbed
  Objectify datastore = ObjectifyService.begin();
  for (EmailData emailData : datastore.query(EmailData.class)
      .filter("id", emailId)/*.order("-datestamp")*/) {
    Email email = new Email(emailData.id, emailData.senderId, emailData.receiverId,
        emailData.title, emailData.body, emailData.datestamp);
    result.t = email;
    break;
  }
  return result.t;
}
 
Example 6
Source File: ObjectifyStorageIo.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
@Override
public User getUserFromEmail(String email) {
  String emaillower = email.toLowerCase();
  LOG.info("getUserFromEmail: email = " + email + " emaillower = " + emaillower);
  Objectify datastore = ObjectifyService.begin();
  String newId = UUID.randomUUID().toString();
  // First try lookup using entered case (which will be the case for Google Accounts)
  UserData user = datastore.query(UserData.class).filter("email", email).get();
  if (user == null) {
    LOG.info("getUserFromEmail: first attempt failed using " + email);
    // Now try lower case version
    user = datastore.query(UserData.class).filter("emaillower", emaillower).get();
    if (user == null) {       // Finally, create it (in lower case)
      LOG.info("getUserFromEmail: second attempt failed using " + emaillower);
      user = createUser(datastore, newId, email);
    }
  }
  User retUser = new User(user.id, email, user.name, user.link, 0, user.tosAccepted,
    false, user.type, user.sessionid);
  retUser.setPassword(user.password);
  return retUser;
}
 
Example 7
Source File: ObjectifyStorageIo.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
boolean isGcsFile(long projectId, String fileName) {
  Objectify datastore = ObjectifyService.begin();
  Key<FileData> fileKey = projectFileKey(projectKey(projectId), fileName);
  FileData fd;
  fd = (FileData) memcache.get(fileKey.getString());
  if (fd == null) {
    fd = datastore.find(fileKey);
  }
  if (fd != null) {
    return isTrue(fd.isGCS);
  } else {
    return false;
  }
}
 
Example 8
Source File: ShareTechnologyTest.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    SystemProperty.applicationVersion.set("test");
    helper.setUp();
    closeable = ObjectifyService.begin();
    currentUser = UserServiceFactory.getUserService().getCurrentUser();
}
 
Example 9
Source File: ObjectifyStorageIo.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void createRawUserFile(String userId, String fileName, byte[] content) {
  Objectify datastore = ObjectifyService.begin();
  UserFileData ufd = createUserFile(datastore, userKey(userId), fileName);
  if (ufd != null) {
    ufd.content = content;
    datastore.put(ufd);
  }
}
 
Example 10
Source File: ObjectifyStorageIo.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
public void cleanupNonces() {
  Objectify datastore = ObjectifyService.begin();
  // We do not use runJobWithRetries because if we fail here, we will be
  // called again the next time someone attempts to download a built APK
  // via a QR Code.
  try {
    datastore.delete(datastore.query(NonceData.class)
      .filter("timestamp <", new Date((new Date()).getTime() - 3600*3*1000L))
      .limit(10).fetchKeys());
  } catch (Exception ex) {
      LOG.log(Level.WARNING, "Exception during cleanupNonces", ex);
  }

}
 
Example 11
Source File: RemoteApiClient.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
protected void doOperationRemotely() throws IOException {

        String appUrl = ClientProperties.TARGET_URL.replaceAll("^https?://", "");
        String appDomain = appUrl.split(":")[0];
        int appPort = appUrl.contains(":") ? Integer.parseInt(appUrl.split(":")[1]) : 443;

        System.out.println("--- Starting remote operation ---");
        System.out.println("Going to connect to:" + appDomain + ":" + appPort);

        RemoteApiOptions options = new RemoteApiOptions().server(appDomain, appPort);

        if (ClientProperties.isTargetUrlDevServer()) {
            // Dev Server doesn't require credential.
            options.useDevelopmentServerCredential();
        } else {
            // Your Google Cloud SDK needs to be authenticated for Application Default Credentials
            // in order to run any script in production server.
            // Refer to https://developers.google.com/identity/protocols/application-default-credentials.
            options.useApplicationDefaultCredential();
        }

        RemoteApiInstaller installer = new RemoteApiInstaller();
        installer.install(options);

        OfyHelper.registerEntityClasses();
        Closeable objectifySession = ObjectifyService.begin();

        try {
            doOperation();
        } finally {
            objectifySession.close();
            installer.uninstall();
        }

        System.out.println("--- Remote operation completed ---");
    }
 
Example 12
Source File: UserServletTest.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
/**
 * Setup method for the test.
 */
@Before
public void setUp() {

  request = Mockito.mock(HttpServletRequest.class);
  response = Mockito.mock(HttpServletResponse.class);
  helper.setUp();
  ObjectifyService.begin();

}
 
Example 13
Source File: ObjectifyStorageIo.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
@Override
public String findUserByEmail(String inputemail) throws NoSuchElementException {
  String email = inputemail.toLowerCase();
  Objectify datastore = ObjectifyService.begin();
  // note: if there are multiple users with the same email we'll only
  // get the first one. we don't expect this to happen
  UserData userData = datastore.query(UserData.class).filter("email", inputemail).get();
  if (userData == null) {     // Mixed case didn't work, try lower case
    userData = datastore.query(UserData.class).filter("email", email).get();
    if (userData == null) {
      throw new NoSuchElementException("Couldn't find a user with email " + inputemail);
    }
  }
  return userData.id;
}
 
Example 14
Source File: MoveServletTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  helper.setUp();
  dbSession = ObjectifyService.begin();

  servletUnderTest = new MoveServlet();

  helper.setEnvIsLoggedIn(true);
  // Make sure there are no firebase requests if we don't expect it
  FirebaseChannel.getInstance().httpTransport = null;
}
 
Example 15
Source File: EndorsementServiceTest.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
/**
 * Setup method for the test.
 */
@Before
public void setUp() {
  helper.setUp();
  ObjectifyService.register(TechGalleryUser.class);
  ObjectifyService.register(Endorsement.class);
  ObjectifyService.begin();
}
 
Example 16
Source File: ObjectifyStorageIo.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
public void checkUpgrade(String userId) {
  if (!conversionEnabled)     // Unless conversion is enabled...
    return;
  Objectify datastore = ObjectifyService.begin();
  UserData userData = datastore.find(userKey(userId));
  if ((userData.upgradedGCS && useGcs) ||
    (!userData.upgradedGCS && !useGcs))
    return;                   // All done.
  Queue queue = QueueFactory.getQueue("blobupgrade");
  queue.add(TaskOptions.Builder.withUrl("/convert").param("user", userId)
    .etaMillis(System.currentTimeMillis() + 60000));
  return;
}
 
Example 17
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a wrapped class which contains a list of tutorial gallery app
 * @param start start index
 * @param count count number
 * @return list of gallery app
 */
public GalleryAppListResult getTutorialApp(int start, int count){
  final List<GalleryApp> apps = new ArrayList<GalleryApp>();
  Objectify datastore = ObjectifyService.begin();
  for (GalleryAppTutorialData appTutorialData:datastore.query(GalleryAppTutorialData.class).offset(start).limit(count)) {
    Long galleryId = appTutorialData.galleryKey.getId();
    GalleryApp gApp = new GalleryApp();
    GalleryAppData galleryAppData = datastore.find(galleryKey(galleryId));
    makeGalleryApp(galleryAppData, gApp);
    apps.add(gApp);
  }

  int totalCount = datastore.query(GalleryAppTutorialData.class).count();
  return new GalleryAppListResult(apps, totalCount);
}
 
Example 18
Source File: ObjectifyGalleryStorageIo.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a wrapped class which contains a list of featured gallery app
 * @param start start index
 * @param count count number
 * @return list of gallery app
 */
public GalleryAppListResult getFeaturedApp(int start, int count){
  final List<GalleryApp> apps = new ArrayList<GalleryApp>();
  Objectify datastore = ObjectifyService.begin();
  for (GalleryAppFeatureData appFeatureData:datastore.query(GalleryAppFeatureData.class).offset(start).limit(count)) {
    Long galleryId = appFeatureData.galleryKey.getId();
    GalleryApp gApp = new GalleryApp();
    GalleryAppData galleryAppData = datastore.find(galleryKey(galleryId));
    makeGalleryApp(galleryAppData, gApp);
    apps.add(gApp);
  }

  int totalCount = datastore.query(GalleryAppFeatureData.class).count();
  return new GalleryAppListResult(apps, totalCount);
}
 
Example 19
Source File: GreetingTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

  helper.setUp();
  ds = DatastoreServiceFactory.getDatastoreService();

  ObjectifyService.init();
  ObjectifyService.register(Guestbook.class);
  ObjectifyService.register(Greeting.class);

  closeable = ObjectifyService.begin();

  cleanDatastore(ds, "default");
}
 
Example 20
Source File: ObjectifyStorageIo.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
public void doUpgrade(String userId) {
  if (!conversionEnabled)     // Unless conversion is enabled...
    return;                   // shouldn't really ever happen but...
  Objectify datastore = ObjectifyService.begin();
  UserData userData = datastore.find(userKey(userId));
  if ((userData.upgradedGCS && useGcs) ||
    (!userData.upgradedGCS && !useGcs))
    return;                   // All done, another task did it!
  List<Long> projectIds = getProjects(userId);
  boolean anyFailed = false;
  for (long projectId : projectIds) {
    for (FileData fd : datastore.query(FileData.class).ancestor(projectKey(projectId))) {
      if (fd.isBlob) {
        if (useGcs) {         // Let's convert by just reading it!
          downloadRawFile(userId, projectId, fd.fileName);
        }
      } else if (isTrue(fd.isGCS)) {
        if (!useGcs) {        // Let's downgrade by just reading it!
          downloadRawFile(userId, projectId, fd.fileName);
        }
      }
    }
  }

  /*
   * If we are running low on time, we may have not moved all files
   * so exit now without marking the user as having been finished
   */
  if (ApiProxy.getCurrentEnvironment().getRemainingMillis() <= 5000)
    return;

  /* If anything failed, also return without marking user */
  if (anyFailed)
    return;

  datastore = ObjectifyService.beginTransaction();
  userData = datastore.find(userKey(userId));
  userData.upgradedGCS = useGcs;
  datastore.put(userData);
  datastore.getTxn().commit();
}