Java 类org.hibernate.internal.SessionImpl 实例源码

项目:coodoo-listing    文件:AbstractDbUnitTest.java   
/**
 * Set up memory database and insert data from test-dataset.xml
 * 
 * @throws DatabaseUnitException
 * @throws HibernateException
 * @throws SQLException
 */
@BeforeClass
public static void initEntityManager() throws HibernateException, DatabaseUnitException, SQLException {
    entityManagerFactory = Persistence.createEntityManagerFactory("listing-test-db");
    entityManager = entityManagerFactory.createEntityManager();
    connection = new DatabaseConnection(((SessionImpl) (entityManager.getDelegate())).connection());
    connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());

    InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(datasetXml);
    if (inputStream != null) {
        FlatXmlDataSetBuilder flatXmlDataSetBuilder = new FlatXmlDataSetBuilder();
        flatXmlDataSetBuilder.setColumnSensing(true);
        dataset = flatXmlDataSetBuilder.build(inputStream);
        DatabaseOperation.CLEAN_INSERT.execute(connection, dataset);
    }
}
项目:database-rider    文件:DataSetProcessor.java   
/**
 * unfortunately there is no standard way to get jdbc connection from JPA entity manager
 *
 * @return JDBC connection
 */
private Connection createConnection() {
    try {
        EntityTransaction tx = this.em.getTransaction();
        if (isHibernatePresentOnClasspath() && em.getDelegate() instanceof Session) {
            connection = ((SessionImpl) em.unwrap(Session.class)).connection();
        } else {
            /**
             * see here:http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager
             */
            tx.begin();
            connection = em.unwrap(Connection.class);
            tx.commit();
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not create database connection", e);
    }

    return connection;
}
项目:database-rider    文件:EntityManagerProvider.java   
private void init(String unitName) {
    if (emf == null) {
        log.debug("creating emf for unit "+unitName);
        emf = Persistence.createEntityManagerFactory(unitName);
        em = emf.createEntityManager();
        tx = em.getTransaction();
        if (isHibernateOnClasspath() && em.getDelegate() instanceof Session) {
            conn = ((SessionImpl) em.unwrap(Session.class)).connection();
        } else{
            /**
             * see here:http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager
             */
            tx.begin();
            conn = em.unwrap(Connection.class);
            tx.commit();
        }

    }
    emf.getCache().evictAll();
}
项目:devwars.tv    文件:TransactionalInterceptor.java   
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
    try {
        HandlerMethod handlerMethod = (HandlerMethod) o;

        Transactional transactional = handlerMethod.getMethodAnnotation(Transactional.class);

        if (transactional != null) {

            SessionImpl session = (SessionImpl) DatabaseManager.getSession();
            session.beginTransaction();

            httpServletRequest.setAttribute("session", session);
        }
    } catch (Exception ignored) {
    }

    return true;
}
项目:devwars.tv    文件:TransactionalInterceptor.java   
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    try {
        HandlerMethod handlerMethod = (HandlerMethod) o;

        Transactional transactional = handlerMethod.getMethodAnnotation(Transactional.class);

        if (transactional != null) {
            SessionImpl session = (SessionImpl) httpServletRequest.getAttribute("session");

            session.getTransaction().commit();
            session.close();
        }
    } catch (Exception ignored) {
    }
}
项目:devwars.tv    文件:GameController.java   
/**
 * Sets the game to active and all other games to inactive (Allows the currentGame method to bring back result)
 *
 * @param id ID of game to activate
 * @return
 */
@Transactional
@PreAuthorization(minRole = User.Role.ADMIN)
@RequestMapping("/{id}/activate")
public ResponseEntity activateGame(SessionImpl session, @PathVariable("id") int id) {
    Game game = (Game) session.get(Game.class, id);

    if (game != null) {
        Query query = session.createQuery("update Game set active = false where active = true");
        query.executeUpdate();

        game.setActive(true);

        return new ResponseEntity(game, HttpStatus.OK);
    } else {
        return new ResponseEntity(HttpMessages.NO_GAME_FOUND, HttpStatus.NOT_FOUND);
    }
}
项目:devwars.tv    文件:GameController.java   
@Transactional
@PreAuthorization(minRole = User.Role.ADMIN)
@RequestMapping("/{id}/resetwinner")
public ResponseEntity resetGameWinner(@PathVariable("id") int id, SessionImpl session) {
    Game game = (Game) session.get(Game.class, id);

    game.getTeams().values().stream()
        .forEach(team -> {
            team.setWin(false);

            team.getPlayers().stream().forEach(player -> {
                int xpChanged = player.getXpChanged();
                int pointsChanged = player.getPointsChanged();

                player.getUser().getRanking().addPoints(pointsChanged * -1);
                player.getUser().getRanking().addXP(xpChanged * -1);

                player.setXpChanged(0);
                player.setPointsChanged(0);
            });
        });

    return new ResponseEntity("Successfully reset game winner", HttpStatus.OK);
}
项目:devwars.tv    文件:GameController.java   
/**
 * Removes a user from the game and penlizes them with some value
 *
 * @param session
 * @param player  The player to remove
 * @return
 */
@Transactional
@PreAuthorization(minRole = User.Role.ADMIN)
@RequestMapping(value = "/forfeituser", method = RequestMethod.POST)
public ResponseEntity forfeitUser(SessionImpl session,
                                  @JSONParam("player") Player player) {
    player = (Player) session.get(Player.class, player.getId());

    Ranking ranking = player.getUser().getRanking();
    ranking.addPoints(-50);
    ranking.addXP(-50);

    session.delete(player);

    return new ResponseEntity(player, HttpStatus.OK);
}
项目:devwars.tv    文件:GameController.java   
@Transactional
@PreAuthorization(minRole = User.Role.USER)
@RequestMapping("/{id}/resign")
public ResponseEntity resignFromGame(SessionImpl session, @AuthedUser User user, @PathVariable("id") int id) {
    Game game = (Game) session.get(Game.class, id);

    Optional<GameSignup> foundSignup = game.getSignups().stream()
        .filter(a -> a.getUser().getId() == user.getId())
        .findFirst();

    if (foundSignup.isPresent()) {
        session.delete(foundSignup.get());

        return new ResponseEntity("Successfully resigned", HttpStatus.OK);
    }

    return new ResponseEntity("Sign Up not found", HttpStatus.NOT_FOUND);
}
项目:devwars.tv    文件:UserTeamController.java   
/**
 * Change a teams avatar
 *
 * @param session       (Resolved)
 * @param multipartFile (Image)
 * @param id            ID of team to change picture
 * @return Response
 * @throws IOException
 */
@UnitOfWork
@RequestMapping(value = "/{id}/avatar", method = RequestMethod.POST)
public ResponseEntity changeAvatar(SessionImpl session,
                                   @AuthedUser User user,
                                   @RequestParam("image") MultipartFile multipartFile,
                                   @PathVariable("id") int id) throws IOException, DbxException {
    UserTeam userTeam = (UserTeam) session.get(UserTeam.class, id);

    if (userTeam == null)
        return new ResponseEntity("Team not found", HttpStatus.NOT_FOUND);

    if (!userTeamService.doesUserHaveAuthorization(user, userTeam))
        return new ResponseEntity("You cannot do that", HttpStatus.FORBIDDEN);

    userTeamService.changeTeamPicture(userTeam, multipartFile.getInputStream());

    return new ResponseEntity("Successfully changed picture", HttpStatus.OK);
}
项目:devwars.tv    文件:UserTeamController.java   
/**
 * Deletes a team
 *
 * @param session  (Resolved)
 * @param id       ID of the team to delete
 * @param teamName Team name confirmation
 * @return Message
 */
@Transactional
@PreAuthorization(minRole = User.Role.USER)
@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
public ResponseEntity deleteTeam(SessionImpl session, @AuthedUser User user, @PathVariable("id") int id, @RequestParam("name") String teamName, @RequestParam(value = "newOwner", required = false) Integer newOwner) {
    UserTeam userTeam = (UserTeam) session.get(UserTeam.class, id);

    if (!teamName.equals(userTeam.getName()))
        return new ResponseEntity("Team name did not match", HttpStatus.BAD_REQUEST);

    if (!userTeamService.doesUserHaveAuthorization(user, userTeam))
        return new ResponseEntity("You are not allowed to do this", HttpStatus.FORBIDDEN);

    userTeamService.disbandTeam(userTeam, newOwner);
    user.setTeam(null);

    return new ResponseEntity(userTeam, HttpStatus.OK);
}
项目:devwars.tv    文件:UserTeamController.java   
/**
 * Kick a player from a team
 *
 * @param session (Resolved)
 * @param id      ID Of the team to kick from
 * @param userID  User to kick
 * @return Response
 */
@Transactional
@PreAuthorization(minRole = User.Role.USER)
@RequestMapping("/{id}/kick/{user}")
public ResponseEntity kickUser(SessionImpl session,
                               @AuthedUser User authedUser,
                               @PathVariable("id") int id,
                               @PathVariable("user") int userID) {
    UserTeam userTeam = (UserTeam) session.get(UserTeam.class, id);

    if (userTeam == null)
        return new ResponseEntity("Team not found", HttpStatus.NOT_FOUND);

    if (!userTeamService.doesUserHaveAuthorization(authedUser, userTeam))
        return new ResponseEntity("You're not allowed to do that", HttpStatus.FORBIDDEN);

    userTeam.getMembers().removeIf(
        user -> user.getId() == userID);

    return new ResponseEntity("Successfully kicked player", HttpStatus.OK);
}
项目:devwars.tv    文件:UserTeamController.java   
/**
 * Leave the team (Remove yourself from the member list)
 *
 * @param session (Resolved)
 * @param user    (Resolved)
 * @param id      The ID of the team to leave
 * @return Response
 */
@Transactional
@PreAuthorization(minRole = User.Role.USER)
@RequestMapping("/{id}/leave")
public ResponseEntity leaveTeam(SessionImpl session,
                                @AuthedUser User user,
                                @PathVariable("id") int id) {
    UserTeam userTeam = (UserTeam) session.get(UserTeam.class, id);

    if (userTeam == null)
        return new ResponseEntity("Team not found", HttpStatus.NOT_FOUND);

    userTeam.getMembers().removeIf(currentUser ->
        currentUser.getId() == user.getId());

    return new ResponseEntity("Successfully left team", HttpStatus.OK);
}
项目:devwars.tv    文件:UserTeamController.java   
/**
 * Gets the game history of a team
 *
 * @param session (Resolved)
 * @param id      ID of the team
 * @param page    Page offset
 * @param count   Number of results
 * @return history
 */
@UnitOfWork
@RequestMapping("/{id}/history")
public ResponseEntity getHistory(SessionImpl session,
                                 @PathVariable("id") int id,
                                 @RequestParam(value = "page", defaultValue = "1", required = false) int page,
                                 @RequestParam(value = "count", defaultValue = "8", required = false) int count) {
    UserTeam userTeam = (UserTeam) session.get(UserTeam.class, id);

    if (userTeam != null) {
        page = page < 1 ? 1 : page;
        count = count < 1 || count > 8 ? 8 : count;

        List<Game> games = userTeamService.getGamesForUserTeam(userTeam, page, count);

        return new ResponseEntity(games, HttpStatus.OK);
    }

    return new ResponseEntity("That team was not found", HttpStatus.NOT_FOUND);
}
项目:devwars.tv    文件:BlogController.java   
/**
 * Created new blog post
 *
 * @param blogPost JSON of the new post
 * @param user
 * @param session
 * @return
 */
@Transactional
@PreAuthorization(minRole = User.Role.BLOGGER)
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity createBlog(@JSONParam("post") BlogPost blogPost,
                                 @AuthedUser User user,
                                 SessionImpl session) {

    Errors errors = new BeanPropertyBindingResult(blogPost, "blogPost");
    blogPostValidator.validate(blogPost, errors);

    if (errors.hasErrors()) {
        return new ResponseEntity(errors.getAllErrors(), HttpStatus.BAD_REQUEST);
    }

    blogPost.setUser(user);

    session.save(blogPost);

    return new ResponseEntity(blogPost, HttpStatus.OK);
}
项目:devwars.tv    文件:BlogController.java   
/**
 * Updates a blog posts with given information
 *
 * @param session
 * @param id       The ID of the blog post to update
 * @param blogPost JSON of post to update with
 * @return The new blog post
 */
@Transactional
@PreAuthorization(minRole = User.Role.BLOGGER)
@RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
public ResponseEntity updateBlog(SessionImpl session,
                                 @PathVariable("id") int id,
                                 @JSONParam("post") BlogPost blogPost) {
    BlogPost oldPost = (BlogPost) session.get(BlogPost.class, id);

    if (oldPost != null) {
        blogPost.setId(id);

        session.merge(blogPost);

        return new ResponseEntity(blogPost, HttpStatus.OK);
    } else {
        return new ResponseEntity("No post found", HttpStatus.NOT_FOUND);
    }
}
项目:devwars.tv    文件:UserController.java   
@PreAuthorization(minRole = User.Role.PENDING)
@Transactional
@RequestMapping(value = "/notifications/read", method = RequestMethod.POST)
public ResponseEntity markNotificationsAsRead(@JSONParam("notifications") Notification[] notificationList, @AuthedUser User user, SessionImpl session) {
    List notificationIDs = Arrays.asList(notificationList).stream()
        .map(Notification::getId)
        .collect(Collectors.toList());

    if (notificationList.length > 0) {
        List<Notification> notifications = session.createCriteria(Notification.class)
            .add(Restrictions.eq("user.id", user.getId()))
            .add(Restrictions.in("id", notificationIDs))
            .list();

        notifications.stream()
            .forEach(a -> a.setHasRead(true));
    }

    return new ResponseEntity(notificationList, HttpStatus.OK);
}
项目:devwars.tv    文件:DevBitsController.java   
/**
 * Updates users earned bets so we can see how much they've won from betting
 *
 * @param session
 * @param earnedBets The amount of Devbits earned
 * @return
 */
@Transactional
@PreAuthorization(minRole = User.Role.ADMIN)
@RequestMapping(value = "/earnedbets", method = RequestMethod.POST)
public ResponseEntity earnBetsForUsers(SessionImpl session, @JSONParam("bets") EarnedBet[] earnedBets) {
    for (EarnedBet earnedBet : earnedBets) {
        Query userQuery = session.createQuery("select u from User u left join u.connectedAccounts as a where (lower(substring(u.username, 1, length(u.username)-4)) = :username and u.provider = 'TWITCH') or (lower(a.username) = :username and a.provider = 'TWITCH')");
        userQuery.setString("username", earnedBet.getTwitchUsername().toLowerCase());

        User user = (User) userQuery.uniqueResult();

        if (user != null) {
            user.setBettingBitsEarned(user.getBettingBitsEarned() + earnedBet.getPointsEarned());
        }
    }

    return null;
}
项目:devwars.tv    文件:DevBitsController.java   
/**
 * Adds a watched game to a user
 *
 * @param session
 * @param usernames JSON Array of twitch usernames
 * @return
 */
@Transactional
@PreAuthorization(minRole = User.Role.ADMIN)
@RequestMapping(value = "/watched", method = RequestMethod.POST)
public ResponseEntity earnBetsForUsers(SessionImpl session, @JSONParam("usernames") String[] usernames) {
    List<User> updatedUsers = new ArrayList<>();

    for (String username : usernames) {
        User user = userService.userForTwitchUsername(username);

        if (user != null) {
            user = (User) session.merge(user);

            user.setGamesWatched(user.getGamesWatched() + 1);
            updatedUsers.add(user);
        }
    }

    return new ResponseEntity(updatedUsers, HttpStatus.OK);
}
项目:hibernate-filter    文件:TableFilter.java   
public static String showSql(Criteria criteria){
    try {
        CriteriaImpl c = (CriteriaImpl) criteria;
        SessionImpl s = (SessionImpl) c.getSession();
        SessionFactoryImplementor factory = (SessionFactoryImplementor) s.getSessionFactory();
        String[] implementors = factory.getImplementors(c.getEntityOrClassName());
        LoadQueryInfluencers lqis = new LoadQueryInfluencers();
        CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable) factory.getEntityPersister(implementors[0]), factory, c, implementors[0], lqis);
        Field f = OuterJoinLoader.class.getDeclaredField("sql");
        f.setAccessible(true);
        return (String) f.get(loader);
    }catch (Exception e){
        e.printStackTrace();
        return "";
    }
}
项目:evosuite    文件:DBManagerIntTest.java   
@Test
public void testTableInitialization() throws SQLException {
    Connection c = ((SessionImpl) DBManager.getInstance().getCurrentEntityManager().getDelegate()).connection();
    Statement s = c.createStatement();

    Set<String> tables = new LinkedHashSet<>();
    ResultSet rs = s.executeQuery("select table_name " +
            "from INFORMATION_SCHEMA.system_tables " +
            "where table_type='TABLE' and table_schem='PUBLIC'");
    while (rs.next()) {
        if (!rs.getString(1).startsWith("DUAL_")) {
            tables.add(rs.getString(1));
        }
    }
    rs.close();
    s.close();

    Assert.assertTrue(tables.contains("KVPair_table".toUpperCase()));
}
项目:evosuite    文件:DBManagerIntTest.java   
@Test
public void testDirectSQLInsertFollowedByClear() throws SQLException {

    String tableName = "KVPair_table";

    Connection c = ((SessionImpl) DBManager.getInstance().getCurrentEntityManager().getDelegate()).connection();
    Statement s = c.createStatement();

    ResultSet rs = null;

    s.executeUpdate("INSERT INTO KVPair_table VALUES 'a', 'b'");

    rs = s.executeQuery("SELECT * from "+tableName);
    Assert.assertTrue(rs.next());
    rs.close();
    s.close();

    DBManager.getInstance().clearDatabase();

    s = c.createStatement();
    rs = s.executeQuery("SELECT * from " + tableName);
    Assert.assertFalse(rs.next()); // no data
    rs.close();
    s.close();
}
项目:raguel    文件:RaguelDataMigrator.java   
private void migrateV1toV2() throws SQLException {
    SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);
    Connection connection = session.getJdbcConnectionAccess().obtainConnection();

    String forumTable = "raguel_forum";
    String forumThreadTable = "raguel_thread";
    String forumLastPostTable = "raguel_forum_last_post";

    Statement statement = connection.createStatement();
    String threadQuery = "SELECT * FROM " + forumThreadTable + " ORDER BY timeUpdate DESC;";
    ResultSet resultSet = statement.executeQuery(threadQuery);
    while (resultSet.next()) {
        String forumJid  = resultSet.getString("forumJid");
        String userUpdate = resultSet.getString("userUpdate");
        long timeUpdate = resultSet.getLong("timeUpdate");

        updateForumAndParentsLastPost(connection, forumTable, forumLastPostTable, forumJid, userUpdate, timeUpdate);
    }
}
项目:uriel    文件:UrielDataMigrator.java   
private void migrateV7toV8() throws SQLException {
    SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);
    Connection connection = session.getJdbcConnectionAccess().obtainConnection();

    String contestScoreboardTable = "uriel_contest_scoreboard";

    Statement statement = connection.createStatement();
    String scoreboardModuleQuery = "SELECT * FROM " + contestScoreboardTable + ";";
    ResultSet resultSet = statement.executeQuery(scoreboardModuleQuery);
    while (resultSet.next()) {
        long id = resultSet.getLong("id");
        long timeUpdate = resultSet.getLong("timeUpdate");
        PreparedStatement preparedStatement = connection.prepareStatement("UPDATE " + contestScoreboardTable + " SET time = ? WHERE id = " + id + ";");
        preparedStatement.setLong(1, timeUpdate);
        preparedStatement.executeUpdate();
    }
}
项目:uriel    文件:UrielDataMigrator.java   
private void migrateV4toV5() throws SQLException {
    SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);
    Connection connection = session.getJdbcConnectionAccess().obtainConnection();

    String jidCacheTable = "uriel_jid_cache";
    Statement statement = connection.createStatement();
    String jidCacheQuery = "SELECT * FROM " + jidCacheTable + ";";
    ResultSet resultSet = statement.executeQuery(jidCacheQuery);

    while (resultSet.next()) {
        long id = resultSet.getLong("id");
        String jid = resultSet.getString("jid");
        String displayName = resultSet.getString("displayName");

        if (jid.startsWith("JIDUSER")) {
            if (displayName.contains("(")) {
                displayName = displayName.substring(0, displayName.indexOf("(") - 1);

                PreparedStatement preparedStatement = connection.prepareStatement("UPDATE " + jidCacheTable + " SET displayName= ? WHERE id=" + id + ";");
                preparedStatement.setString(1, displayName);
                preparedStatement.executeUpdate();
            }
        }
    }
}
项目:spring4probe    文件:JPAAssertions.java   
public static void assertTableHasColumn(EntityManager manager, final String tableName, final String columnName) {
  SessionImpl session = (SessionImpl) manager.unwrap(Session.class);

  final ResultCollector rc = new ResultCollector();

  session.doWork(new Work() {
    @Override
    public void execute(Connection connection) throws SQLException {
      ResultSet columns = connection.getMetaData().getColumns(null, null, tableName.toUpperCase(), null);
      while(columns.next()) {
        if (columns.getString(4).toUpperCase().equals(columnName.toUpperCase())) {
          rc.found=true;
        }
      }
    }
  });

  if (!rc.found) {
    fail("Column [" + columnName + "] not found on table : " + tableName);
  }
}
项目:spring4probe    文件:JPAAssertions.java   
public static void assertTableExists(EntityManager manager, final String name) {
  SessionImpl session = (SessionImpl) manager.unwrap(Session.class);

  final ResultCollector rc = new ResultCollector();

  session.doWork(new Work() {
    @Override
    public void execute(Connection connection) throws SQLException {
      ResultSet tables = connection.getMetaData().getTables(null, null, "%", null);
      while(tables.next()) {
        if (tables.getString(3).toUpperCase().equals(name.toUpperCase())) {
          rc.found=true;
        }
      }
    }
  });

  if (!rc.found) {
    fail("Table not found in schema : " + name);
  }
}
项目:cdi-test    文件:HibernateConnectionWrapper.java   
@Override
public boolean runWithConnection() {
    Object delegate = entityManager.getDelegate();
    if (delegate instanceof SessionImpl) {
        SessionImpl session = (SessionImpl) delegate;
        if(!cleaner.isUnsatisfied()) {
            session.doWork(new org.hibernate.jdbc.Work() {
                @Override
                public void execute(Connection connection) throws SQLException {
                    cleaner.get().run(connection);
                }
            });
        }
        return true;
    } else {
        return false;
    }
}
项目:debop4j    文件:ConnectionInterceptor.java   
@Around( "@annotation(ReadOnlyConnection)" )
public Object proceed(ProceedingJoinPoint pjp) throws Throwable {

    log.debug("읽기전용 작업을 수행하기 위해 현 connection를 readonly로 설정합니다...");

    SessionImpl session = (SessionImpl) sessionFactory.getCurrentSession();
    Connection connection = session.connection();

    boolean autoCommit = connection.getAutoCommit();
    boolean readOnly = connection.isReadOnly();

    try {
        // MySQL SLAVE 서버에 접속하기 위해 Connection 속성을 설정합니다.
        connection.setAutoCommit(false);
        connection.setReadOnly(true);

        // @ReadOnlyConnection이 선언된 메소드를 실행합니다.
        return pjp.proceed();

    } finally {
        connection.setAutoCommit(autoCommit);
        connection.setReadOnly(readOnly);
        log.debug("읽기전용 작업을 수행하고, connection의 원래 설정으로 재설정했습니다.");
    }
}
项目:bandwidth-on-demand    文件:HibernateJpaDialectWithTransactionIsolationSupport.java   
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
    throws PersistenceException, SQLException, TransactionException {

  Session session = (Session) entityManager.getDelegate();
  if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
    getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
  }

  Connection connection = ((SessionImpl) session).connection();
  Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(connection, definition);

  entityManager.getTransaction().begin();

  Object transactionDataFromHibernateJpaDialect = prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
  return new IsolationSupportSessionTransactionData(transactionDataFromHibernateJpaDialect, previousIsolationLevel, connection);
}
项目:ARCLib    文件:DbTest.java   
public void setSyntax() throws SQLException {
    Connection c = ((SessionImpl) em.getDelegate()).connection();
    Statement s = c.createStatement();

    s.execute("SET DATABASE SQL SYNTAX PGS TRUE");
    s.close();
}
项目:ARCLib    文件:DbTest.java   
public void clearDatabase() throws SQLException {
    Connection c = ((SessionImpl) em.getDelegate()).connection();
    Statement s = c.createStatement();

    //s.execute("DROP SCHEMA PUBLIC CASCADE ");
    s.execute("TRUNCATE SCHEMA PUBLIC AND COMMIT");
    s.close();
}
项目:database-rider    文件:DeltaspikeIt.java   
private Connection createConnection() {
    /* eclipselink
   entityManager.getTransaction().begin();
    Connection connection = entityManager.unwrap(java.sql.Connection.class);
    entityManager.getTransaction().commit();*/
    Connection connection = ((SessionImpl) entityManager.unwrap(Session.class)).connection();
    assertNotNull(connection);
    return connection;

}
项目:devwars.tv    文件:PlayerController.java   
/**
 * Removes a player from a team without penalizing
 *
 * @param playerID ID of player to remove
 * @return The player which was removed
 */
@Transactional
@PreAuthorization(minRole = User.Role.ADMIN)
@RequestMapping("/{playerID}/remove")
public ResponseEntity removePlayer(SessionImpl session, @PathVariable("playerID") int playerID) {
    Player player = (Player) session.get(Player.class, playerID);

    if (player != null) {
        session.delete(player);

        return new ResponseEntity("Successfully deleted player", HttpStatus.OK);
    }

    return new ResponseEntity("Player could not be found", HttpStatus.NOT_FOUND);
}
项目:devwars.tv    文件:PlayerController.java   
/**
 * Adds a player to a team
 *
 * @param teamID   ID of team to add to
 * @param language The language that the user will be playing
 * @param newUser  The user that will be playing
 * @return The newly added player
 */
@Transactional
@PreAuthorization(minRole = User.Role.ADMIN)
@RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity addPlayer(@RequestParam("teamID") int teamID,
                                @RequestParam("language") String language,
                                @JSONParam("user") User newUser,
                                @AuthedUser User user,
                                SessionImpl session) {
    Team team = (Team) session.get(Team.class, teamID);

    if (team != null) {
        Player newPlayer = new Player(team, newUser, language);

        session.save(newPlayer);

        String message = "You were added to the game on " + new SimpleDateFormat("EEE, MMM d @ K:mm a").format(new Date(team.getGame().getTimestamp().getTime()));
        Activity activity = new Activity(newPlayer.getUser(), user, message, 0, 0);

        session.save(activity);

        if (newPlayer.getUser().getEmail() != null) {
            String subject = "Accepted to play a game of DevWars";
            String activityMessage = "Dear " + newPlayer.getUser().getUsername() + ", you've been accepted to play a game of DevWars on " + new Date(team.getGame().getTimestamp().getTime()).toString();

            Util.sendEmail(Reference.getEnvironmentProperty("emailUsername"), Reference.getEnvironmentProperty("emailPassword"), subject, activityMessage, newPlayer.getUser().getEmail());
        }

        return new ResponseEntity(newPlayer, HttpStatus.OK);
    }

    return null;
}
项目:devwars.tv    文件:TeamController.java   
/**
 * Upload for the teams data straight from cloud nine
 *
 * @param session
 * @param id      ID of team to set
 * @param zipFile tar.gz file from Cloud Nine
 * @return
 * @throws IOException
 */
@PreAuthorization(minRole = User.Role.ADMIN)
@UnitOfWork
@RequestMapping(value = "/{id}/upload", method = RequestMethod.POST)
public ResponseEntity uploadSite(SessionImpl session, @PathVariable("id") int id, @RequestPart("zip") MultipartFile zipFile) throws IOException, DbxException {
    Team team = (Team) session.get(Team.class, id);

    TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(new GZIPInputStream(zipFile.getInputStream()));

    String destPath = fileStorage.SITE_STORAGE_PATH + "/" + team.getGame().getId() + "/" + team.getName();

    TarArchiveEntry tarArchiveEntry = null;
    while ((tarArchiveEntry = tarArchiveInputStream.getNextTarEntry()) != null) {
        String fileName = tarArchiveEntry.getName();

        fileName = fileName.split("_")[fileName.split("_").length - 1];
        fileName = fileName.replace("workspace", "");

        boolean isIgnored = Arrays.asList(ignored).stream().anyMatch(fileName::contains);

        if (!isIgnored) {
            System.out.println(fileName);

            if (!tarArchiveEntry.isDirectory()) {
                fileStorage.uploadFile(destPath + fileName, tarArchiveInputStream);
            }
        }

    }

    return new ResponseEntity("Successfully Uploaded Team's files", HttpStatus.OK);
}
项目:devwars.tv    文件:GameController.java   
/**
 * Get list of games moving backwards from starting point
 *
 * @return List of games in descending order
 */
@UnitOfWork
@RequestMapping("/pastgamelist")
public ResponseEntity getGameList(
    @RequestParam("firstGame") int id,
    @RequestParam(value = "count", required = false, defaultValue = "10") int count,
    SessionImpl session) {
    List<Game> pastGames = session.createCriteria(Game.class)
        .add(Restrictions.le("id", id))
        .setMaxResults(count)
        .addOrder(Order.desc("id"))
        .list();

    return new ResponseEntity(pastGames, HttpStatus.OK);
}
项目:devwars.tv    文件:GameController.java   
/**
 * Creates a game with the default information
 *
 * @param timestamp The time in UTC which the game will start
 * @param name      Name of the game (Classic or Zen Garden)
 * @return New game
 */
@Transactional
@PreAuthorization(minRole = User.Role.ADMIN)
@RequestMapping("/create")
public ResponseEntity createGame(SessionImpl session,
                                 @RequestParam(value = "time", required = false, defaultValue = "0") long timestamp,
                                 @RequestParam(required = false, value = "name") String name,
                                 @RequestParam(required = false, value = "tournament") Integer tournamentID) {

    Tournament tournament = tournamentID == null ? null : tournamentService.byID(tournamentID);

    Game game = gameService.defaultGame(tournament);

    if (name != null) {
        game.setName(name);

        if (name.equals("Team Classic")) {
            game.setTeamGame(true);
        }
    }

    if (timestamp != 0) {
        game.setTimestamp(new Timestamp(timestamp));
    }

    session.save(game);

    return new ResponseEntity(game.toString(), HttpStatus.OK);
}
项目:devwars.tv    文件:GameController.java   
/**
 * Sets the game to inactive
 *
 * @param id ID of game to deactivate
 * @return
 */
@Transactional
@PreAuthorization(minRole = User.Role.ADMIN)
@RequestMapping("/{id}/deactivate")
public ResponseEntity deactivateGame(SessionImpl session, @PathVariable("id") int id) {
    Game game = (Game) session.get(Game.class, id);

    if (game != null) {
        game.setActive(false);

        return new ResponseEntity(game, HttpStatus.OK);
    } else {
        return new ResponseEntity(HttpMessages.NO_GAME_FOUND, HttpStatus.NOT_FOUND);
    }
}