play.db.jpa.JPA Java Examples

The following examples show how to use play.db.jpa.JPA. 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: FilesystemStore.java    From restcommander with Apache License 2.0 6 votes vote down vote up
public void rebuildAllIndexes() throws Exception {
    stop();
    File fl = new File(DATA_PATH);
    Files.deleteDirectory(fl);
    fl.mkdirs();
    List<ApplicationClass> classes = Play.classes.getAnnotatedClasses(Indexed.class);
    for (ApplicationClass applicationClass : classes) {
        List<JPABase> objects = JPA.em().createQuery(
                                        "select e from " + applicationClass.javaClass.getCanonicalName() + " as e")
                                        .getResultList();
        for (JPABase jpaBase : objects) {
            index(jpaBase, applicationClass.javaClass.getName());
        }
    }
    Logger.info("Rebuild index finished");
}
 
Example #2
Source File: SecurityTest.java    From htwplus with MIT License 6 votes vote down vote up
/**
 * Tests, if the method "isMemberOfGroup()" works as expected.
 */
@Test
public void testIsMemberOfGroup() {
    final Account testAccount1 = this.getTestAccount(1);
    final Account testAccount2 = this.getTestAccount(2);
    final Account testAccount3 = this.getTestAccount(3);
    final Group testGroup = this.getTestGroup(1, testAccount1);
    this.establishGroupMembership(testAccount2, testGroup);
    this.removeGroupMembership(testAccount3, testGroup);

    // test, that we have exactly one notification
    JPA.withTransaction(new F.Callback0() {
        @Override
        public void invoke() throws Throwable {
            assertThat(Secured.isMemberOfGroup(testGroup, testAccount1)).isTrue();
            assertThat(Secured.isMemberOfGroup(testGroup, testAccount2)).isTrue();
            assertThat(Secured.isMemberOfGroup(testGroup, testAccount3)).isFalse();
        }
    });
}
 
Example #3
Source File: NotificationTest.java    From htwplus with MIT License 6 votes vote down vote up
/**
 * Tests, if no notification is created, when no recipient is set.
 */
@Test
public void testNoNotification() throws Throwable {
    final MockNotifiable notifiable = new MockNotifiable();
    notifiable.sender = this.getTestAccount(1);
    notifiable.rendered = "MOCK NO NOTIFICATION";
    NotificationService.getInstance().createNotification(notifiable);
    this.sleep(5); // sleep to ensure, that Akka would be done with notification creation

    JPA.withTransaction(new F.Callback0() {
        @Override
        @SuppressWarnings("unused")
        public void invoke() throws Throwable {
            List<Notification> notifications = Notification.findByRenderedContent(notifiable.rendered);
            assertThat(notifications.size()).isEqualTo(0);
        }
    });
}
 
Example #4
Source File: GroupManager.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Returns true, if an account is member of a group.
 *
 * @param group   Group instance
 * @param account Account instance
 * @return True, if account is member of group
 */
public static boolean isMember(Group group, Account account) {
    @SuppressWarnings("unchecked")
    List<GroupAccount> groupAccounts = (List<GroupAccount>) JPA
            .em()
            .createQuery(
                    "SELECT g FROM GroupAccount g WHERE g.account.id = ?1 and g.group.id = ?2 AND linkType = ?3")
            .setParameter(1, account.id).setParameter(2, group.id)
            .setParameter(3, LinkType.establish).getResultList();

    return !groupAccounts.isEmpty();
}
 
Example #5
Source File: AbstractJudgelsDataMigrator.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final void migrate() throws SQLException {
    checkTable();

    long currentDataVersion = dataVersionDao.getVersion();
    long latestDataVersion = getLatestDataVersion();
    if (currentDataVersion != latestDataVersion) {
        migrate(currentDataVersion);

        JPA.withTransaction(() -> dataVersionDao.update(latestDataVersion));
    }
}
 
Example #6
Source File: FakeApplicationTest.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Returns an account by email.
 *
 * @param email E-Mail address of account to fetch
 * @return Account instance
 */
public Account getAccountByEmail(final String email) {
    try {
        return JPA.withTransaction(new F.Function0<Account>() {
            @Override
            public Account apply() throws Throwable {
                return Account.findByEmail(email);
            }
        });
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        return null;
    }
}
 
Example #7
Source File: FakeApplicationTest.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Returns a test account, creates one before if not exists.
 *
 * @param number Number of test account
 * @return Account instance
 */
public Account getTestAccount(final int number) {
    final String testAccountEmail = "test" + String.valueOf(number) + "@htwplus.de";
    Account storedTestAccount = this.getAccountByEmail(testAccountEmail);

    // if there is this test account, return
    if (storedTestAccount != null) {
        return storedTestAccount;
    }

    // there is no test account with that number right now, create a persistent one
    try {
        return JPA.withTransaction(new F.Function0<Account>() {
            @Override
            public Account apply() throws Throwable {
                Account testAccount = new Account();
                testAccount.firstname = "Test";
                testAccount.lastname = "User " + String.valueOf(number);
                testAccount.email = testAccountEmail;
                testAccount.avatar = "a1";
                testAccount.role = AccountRole.STUDENT;
                testAccount.password = Component.md5(FakeApplicationTest.TEST_ACCOUNT_PASSWORD);
                testAccount.create();

                return testAccount;
            }
        });
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        return null;
    }
}
 
Example #8
Source File: FakeApplicationTest.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Removes a friendship between test accounts.
 *
 * @param testAccountA First test account
 * @param testAccountB Second test account
 */
public void removeFriendshipTestAccounts(final Account testAccountA, final Account testAccountB) {
    JPA.withTransaction(new F.Callback0() {
        @Override
        public void invoke() throws Throwable {
            if (Friendship.alreadyFriendly(testAccountA, testAccountB)) {
                Friendship.findFriendLink(testAccountA, testAccountB).delete();
            }
            if (Friendship.alreadyFriendly(testAccountB, testAccountA)) {
                Friendship.findFriendLink(testAccountB, testAccountA).delete();
            }
        }
    });
}
 
Example #9
Source File: FakeApplicationTest.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Returns a group by title.
 *
 * @param title Title of group to fetch
 * @return Group instance
 */
public Group getGroupByTitle(final String title) {
    try {
        return JPA.withTransaction(new F.Function0<Group>() {
            @Override
            public Group apply() throws Throwable {
                return Group.findByTitle(title);
            }
        });
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        return null;
    }
}
 
Example #10
Source File: FakeApplicationTest.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Returns a test group, creates one before if not exists.
 *
 * @param number Number of test group
 * @param groupOwner the optional group owner
 * @return Group instance
 */
public Group getTestGroup(final int number, final Account groupOwner) {
    final String testGroupTitle = "Test Group " + String.valueOf(number);
    Group storedTestGroup = this.getGroupByTitle(testGroupTitle);

    // if there is this test group, return
    if (storedTestGroup != null) {
        return storedTestGroup;
    }

    // there is no test account with that number right now, create a persistent one
    try {
        return JPA.withTransaction(new F.Function0<Group>() {
            @Override
            public Group apply() throws Throwable {
                Group testGroup = new Group();
                testGroup.groupType = GroupType.close;
                testGroup.setTitle(testGroupTitle);

                if (groupOwner != null) {
                    testGroup.createWithGroupAccount(groupOwner);
                } else {
                    testGroup.create();
                }

                return testGroup;
            }
        });
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        return null;
    }
}
 
Example #11
Source File: FakeApplicationTest.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Returns a group account for an account to a group.
 *
 * @param account Account
 * @param group Group
 * @return GroupAccount instance if found, otherwise null
 */
public GroupAccount getGroupAccount(final Account account, final Group group) {
    try {
        return JPA.withTransaction(new F.Function0<GroupAccount>() {
            @Override
            public GroupAccount apply() throws Throwable {
                return GroupAccount.find(account, group);
            }
        });
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        return null;
    }
}
 
Example #12
Source File: FakeApplicationTest.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Establishes a group membership of an account to a group.
 *
 * @param account Account
 * @param group Group
 */
public void establishGroupMembership(final Account account, final Group group) {
    JPA.withTransaction(new F.Callback0() {
        @Override
        public void invoke() throws Throwable {
            if (!Group.isMember(group, account)) {
                groupAccount.account = account;
                groupAccount.group = group;
                groupAccount.linkType = LinkType.establish;
                testGroupAccount.create();
                group.update();
            }
        }
    });
}
 
Example #13
Source File: FakeApplicationTest.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Removes a membership of an account to a group.
 *
 * @param account Account
 * @param group Group
 */
public void removeGroupMembership(final Account account, final Group group) {
    JPA.withTransaction(new F.Callback0() {
        @Override
        public void invoke() throws Throwable {
            if (Group.isMember(group, account)) {
                GroupAccount groupAccount = GroupAccount.find(account, group);
                groupAccount.delete();
            }
        }
    });
}
 
Example #14
Source File: SecurityTest.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Tests, if the method "isOwnerOfAccount()" works as expected.
 */
@Test
public void testIsOwnerOfAccount() {
    final Account testAccount1 = this.getTestAccount(1);
    final Account testAccount2 = this.getTestAccount(2);
    this.loginAccount(testAccount1);

    JPA.withTransaction(new F.Callback0() {
        @Override
        public void invoke() throws Throwable {
            assertThat(Secured.isOwnerOfAccount(testAccount1.id)).isTrue();
            assertThat(Secured.isOwnerOfAccount(testAccount2.id)).isFalse();
        }
    });
}
 
Example #15
Source File: SecurityTest.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Tests, if the method "viewGroup()" works as expected.
 */
@Test
public void testViewGroup() {
    Account testAccount1 = this.getTestAccount(1);
    final Group testGroup = this.getTestGroup(1, testAccount1);

    // test, if admin is allowed to view
    this.loginAdminAccount();
    JPA.withTransaction(new F.Callback0() {
        @Override
        public void invoke() throws Throwable {
            assertThat(Secured.viewGroup(testGroup)).isTrue();
        }
    });

    // test, if member of group is allowed to view
    this.loginAccount(testAccount1);
    JPA.withTransaction(new F.Callback0() {
        @Override
        public void invoke() throws Throwable {
            assertThat(Secured.viewGroup(testGroup)).isTrue();
        }
    });

    // test, if no member of group is disallowed to view
    Account testAccount3 = this.getTestAccount(3);
    this.removeGroupMembership(testAccount3, testGroup);
    this.loginAccount(testAccount3);
    JPA.withTransaction(new F.Callback0() {
        @Override
        public void invoke() throws Throwable {
            assertThat(Secured.viewGroup(testGroup)).isFalse();
        }
    });
}
 
Example #16
Source File: Shop.java    From pfe-samples with MIT License 5 votes vote down vote up
private <A> A withTransaction(Function<EntityManager, A> f) {
    try {
        return JPA.withTransaction(() -> f.apply(JPA.em()));
    } catch (Throwable throwable) {
        throw new RuntimeException(throwable);
    }
}
 
Example #17
Source File: FilesystemStore.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public List<ManagedIndex> listIndexes() {
    List<ManagedIndex> indexes = new ArrayList<ManagedIndex>();
    List<ApplicationClass> classes = Play.classes.getAnnotatedClasses(Indexed.class);
    for (ApplicationClass applicationClass : classes) {
        ManagedIndex index = new ManagedIndex();
        index.name = applicationClass.javaClass.getName();
        index.optimized = getIndexSearcher(index.name).getIndexReader().isOptimized();
        index.documentCount = getIndexSearcher(index.name).getIndexReader().numDocs();
        index.jpaCount =  (Long ) JPA.em().createQuery("select count (*) from " + applicationClass.javaClass.getCanonicalName()+ ")").getSingleResult();
        indexes.add(index);
    }
    return indexes;
}
 
Example #18
Source File: JpaHelper.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public static Query execute(String sql, Object ... params) {
    Query query = JPA.em().createQuery(sql);
    int index = 0;
    for (Object param : params) {
        query.setParameter(++index, param);
    }
    return query;
}
 
Example #19
Source File: JpaHelper.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public static Query executeList(String sql, List<Object> params) {
    Query query = JPA.em().createQuery(sql);
    int index = 0;
    for (Object param : params) {
        query.setParameter(++index, param);
    }
    return query;
}
 
Example #20
Source File: GroupManager.java    From htwplus with MIT License 5 votes vote down vote up
@Override
public void update(Object model) {
    JPA.em().merge(model);
    try {
        elasticsearchService.index(model);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #21
Source File: MessageProcessor.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    JPA.withTransaction(() -> {
            try {
                GradingResponse response = MAPPER.readValue(message.getContent(), GradingResponse.class);

                boolean gradingExists = false;

                // temporary solution
                // problem is: grading response arrives before the grading model persistance has been flushed

                for (int i = 0; i < 3; i++) {
                    if (submissionService.gradingExists(response.getGradingJid())) {
                        gradingExists = true;
                        break;
                    }

                    Thread.sleep(TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
                }

                if (gradingExists) {
                    submissionService.grade(response.getGradingJid(), response.getResult(), message.getSourceJid(), "localhost");
                } else {
                    System.out.println("Grading JID " + response.getGradingJid() + " not found!");
                }
                messageService.confirmMessage(sealtielClientAuthHeader, message.getId());
            } catch (RemoteException | IOException e) {
                System.out.println("Bad grading response!");
                e.printStackTrace();
            }
        });
}
 
Example #22
Source File: PostManager.java    From htwplus with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static List<Post> getCommentsForPost2(Long id, int limit, int offset) {
    Query query = JPA.em()
            .createQuery("SELECT p FROM Post p WHERE p.parent.id = ?1 ORDER BY p.createdAt ASC")
            .setParameter(1, id);

    query = limit(query, limit, offset);

    return (List<Post>) query.getResultList();
}
 
Example #23
Source File: GroupAccountManager.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Retrieve Accounts from Group with given LinkType.
 */
@SuppressWarnings("unchecked")
public static List<Account> staticFindAccountsByGroup(final Group group, final LinkType type) {
    return JPA.createFor("defaultPersistenceUnit").withTransaction(() -> {
        return (List<Account>) JPA
                .em()
                .createQuery(
                        "SELECT ga.account FROM GroupAccount ga WHERE ga.group.id = ?1 AND ga.linkType = ?2")
                .setParameter(1, group.id).setParameter(2, type)
                .getResultList();
    });
}
 
Example #24
Source File: FriendshipManager.java    From htwplus with MIT License 5 votes vote down vote up
public static boolean alreadyFriendly2(Account me, Account potentialFriend) {
    try {
        JPA.em().createQuery("SELECT fs FROM Friendship fs WHERE fs.account.id = ?1 and fs.friend.id = ?2 AND fs.linkType = ?3")
                .setParameter(1, me.id).setParameter(2, potentialFriend.id).setParameter(3, LinkType.establish).getSingleResult();
    } catch (NoResultException exp) {
        return false;
    }
    return true;
}
 
Example #25
Source File: NotificationManager.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Returns a list of unread notifications by a specific user account ID.
 *
 * @param accountId User account ID
 * @return List of notifications
 * @throws Throwable
 */
public static List<Notification> findByAccountIdUnread(final Long accountId) throws Throwable {
    return JPA.em()
            .createQuery("FROM Notification n WHERE n.recipient.id = :accountId AND n.isRead = false", Notification.class)
            .setParameter("accountId", accountId)
            .setMaxResults(10)
            .getResultList();
}
 
Example #26
Source File: NotificationManager.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Returns a notification by a reference ID and a recipient ID.
 *
 * @param referenceId Reference ID
 * @param recipientId Recipient ID
 * @return Notification instance
 * @throws NoResultException
 */
public static Notification findByReferenceIdAndRecipientId(Long referenceId, Long recipientId) throws NoResultException {
    return JPA.createFor("defaultPersistenceUnit").withTransaction(() -> {
            return JPA.em().createQuery("FROM Notification n WHERE n.referenceId = :referenceId AND n.recipient.id = :recipientId", Notification.class)
                .setParameter("referenceId", referenceId)
                .setParameter("recipientId", recipientId)
                .getSingleResult();
    });
}
 
Example #27
Source File: NotificationManager.java    From htwplus with MIT License 5 votes vote down vote up
/**
 * Counts all unread notifications for an account ID.
 *
 * @param accountId User account ID
 * @return Number of notifications
 */
public static int countUnreadNotificationsForAccountId(final Long accountId) {
    return ((Number) JPA.em()
            .createQuery("SELECT COUNT(n) FROM Notification n WHERE n.recipient.id = :accountId AND n.isRead = false")
            .setParameter("accountId", accountId)
            .getSingleResult()).intValue();
}
 
Example #28
Source File: PostBookmarkManager.java    From htwplus with MIT License 5 votes vote down vote up
public PostBookmark findByAccountAndPost(Account account, Post post) {
    try {
        return (PostBookmark) JPA.em().createQuery("SELECT pl FROM PostBookmark pl WHERE pl.owner.id = :accountId AND pl.post.id = :postId")
                .setParameter("accountId", account.id)
                .setParameter("postId", post.id)
                .getSingleResult();
    } catch (NoResultException exp) {
        return null;
    }
}
 
Example #29
Source File: PostBookmarkManager.java    From htwplus with MIT License 5 votes vote down vote up
public static boolean isPostBookmarkedByAccount(Account account, Post post) {
    Query query = JPA.em().createQuery("SELECT COUNT(pl) FROM PostBookmark pl WHERE pl.owner.id = :accountId AND pl.post.id = :postId")
            .setParameter("accountId", account.id)
            .setParameter("postId", post.id);

    if(((Number) query.getSingleResult()).intValue() > 0)
        return true;

    return false;
}
 
Example #30
Source File: GroupManager.java    From htwplus with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Group findByTitle2(String title) {
    List<Group> groups = (List<Group>) JPA.em()
            .createQuery("FROM Group g WHERE g.title = ?1")
            .setParameter(1, title).getResultList();

    if (groups.isEmpty()) {
        return null;
    } else {
        return groups.get(0);
    }
}