Example usage for org.hibernate Session load

List of usage examples for org.hibernate Session load

Introduction

In this page you can find the example usage for org.hibernate Session load.

Prototype

void load(Object object, Serializable id);

Source Link

Document

Read the persistent state associated with the given identifier into the given transient instance.

Usage

From source file:br.mdarte.exemplo.academico.cd.EstudanteDAO.java

public List<AbstractEntity> select(long id) throws DAOException {
    List<AbstractEntity> lista = new ArrayList<AbstractEntity>();
    try {//from   w w  w  . j  a v  a 2 s  . c  o  m
        Session session = currentSession();
        EstudanteAbstract res = (EstudanteAbstract) session.load(EstudanteImpl.class, new Long(id));
        org.hibernate.Hibernate.initialize(res);
        lista.add(res);
    } catch (ObjectNotFoundException onfe) {
        throw new DAOException(onfe);
    } catch (HibernateException he1) {
        throw new DAOException(he1);
    }
    return lista;
}

From source file:ca.myewb.frame.servlet.ApiServlet.java

License:Open Source License

private Template handlePosts(HttpServletRequest req, Session s, Context ctx, String[] path, Logger log)
        throws ResourceNotFoundException, ParseErrorException, Exception {
    log.info("handling posts");

    HttpSession httpSession = req.getSession();

    log.info("path is now " + path.length);
    PostParamWrapper requestParams = new PostParamWrapper(req);
    GetParamWrapper urlParams = new GetParamWrapper(path);
    String feedType = path[1];//from  w  ww.  j  ava 2 s  .co  m
    String filterParam = path[2];

    log.info("feedType is " + feedType + " and filterParam is " + filterParam);

    boolean showFullPost = false;
    if (path.length > 3)
        if (path[3].equals("full"))
            showFullPost = true;

    log.info("putting into context");

    ctx.put("feedType", feedType);
    ctx.put("now", Helpers.formatRFCDate(new Date()));
    ctx.put("fullPost", showFullPost);

    //cache display settings from session
    String showReplies = (String) httpSession.getAttribute("showReplies");
    String showEmails = (String) httpSession.getAttribute("showEmails");
    String sortByLastReply = (String) httpSession.getAttribute("sortByLastReply");
    UserModel currentUser = (UserModel) s.load(UserModel.class, new Integer(1));

    httpSession.setAttribute("showReplies", "no");
    httpSession.setAttribute("showEmails", "yes");
    httpSession.setAttribute("sortByLastReply", "no");

    log.info("checking feedType");

    if (feedType.equals("posts")) {
        // handle legacy URLs
        if (filterParam.contains("Any plus Replies")) {
            httpSession.setAttribute("showReplies", "yes");
        } else {
            httpSession.setAttribute("showEmails", "no");
        }

        (new PostList(httpSession, s, requestParams, urlParams, currentUser)).list(ctx, "postsrss", 20, false);
    } else if (feedType.equals("list")) {

        PostList postList = (new PostList(httpSession, s, requestParams, urlParams, currentUser));

        GroupModel theGroup = null;
        try {
            int id = Integer.parseInt(filterParam);
            theGroup = (GroupModel) postList.getAndCheck(GroupModel.class, id);
        } catch (NumberFormatException nfe) {
            theGroup = (GroupChapterModel) HibernateUtil.currentSession()
                    .createQuery("FROM GroupChapterModel g where g.shortname=?").setString(0, filterParam)
                    .uniqueResult();
        }

        ctx.put("list", theGroup);
        if (Permissions.guestsCanReadPostsInGroup(theGroup)) {
            postList.list(ctx, "listposts", 20, false);
        }
    } else if (feedType.equals("hot")) {
        // handle legacy URLs
        if (filterParam.contains("Any plus Replies")) {
            httpSession.setAttribute("showReplies", "yes");
        }
        (new PostList(httpSession, s, requestParams, urlParams, currentUser)).list(ctx, "featuredpostsrss", 20,
                false);

    }

    //undo any changes to display settings in session
    httpSession.setAttribute("showReplies", showReplies);
    httpSession.setAttribute("showEmails", showEmails);
    httpSession.setAttribute("sortByLastReply", sortByLastReply);

    return getTemplate("frame/rsswrapper.vm");
}

From source file:ca.myewb.frame.servlet.ApiServlet.java

License:Open Source License

private Template handleEvents(HttpServletRequest req, Session s, Context ctx, String[] path, Logger log)
        throws ResourceNotFoundException, ParseErrorException, Exception {
    log.info("handling events (" + path.length + ")");

    String calType = path[1];//  w  ww  . j  a va 2  s  . c o  m
    String filterParam = path[2].replaceAll(".ics", "");

    log.info("calType is " + calType + " and filterParam is " + filterParam);

    if (calType.equals("calendar")) {
        UserModel currentUser = (UserModel) s.load(UserModel.class, new Integer(1));
        GroupChapterModel chapter = (GroupChapterModel) s
                .createQuery("FROM GroupChapterModel g where g.shortname=?").setString(0, filterParam)
                .uniqueResult();

        EventList eventList = new EventList(req.getSession(), HibernateUtil.currentSession(),
                new PostParamWrapper(req), new GetParamWrapper(Helpers.getURIComponents(req.getRequestURI())),
                currentUser);

        Collection<EventModel> events = eventList.listVisibleEventsForQuarter(new Date(), chapter);
        ctx.put("now", Helpers.formatRFCDate(new Date()));
        ctx.put("events", events);
        ctx.put("chapterShortName", filterParam);
    } else if (calType.equals("event")) {
        UserModel currentUser = WrapperServlet.getUser(Helpers.getDefaultURL(), log, s, req.getSession());

        EventModel e = (EventModel) s.load(EventModel.class, new Integer(filterParam));
        if (Permissions.canReadEvent(currentUser, e)) {
            Vector<EventModel> events = new Vector<EventModel>();
            events.add(e);
            ctx.put("events", events);
        }
    }

    log.info("and getting template for calendars");

    if (path[2].endsWith("ics")) {
        return getTemplate("frame/icalcalendarwrapper.vm");
    } else //assume legacy RSS
    {
        return getTemplate("frame/rsscalendarwrapper.vm");
    }
}

From source file:ca.myewb.frame.servlet.ApiServlet.java

License:Open Source License

private Template handlePerson(HttpServletRequest req, Session s, Context ctx, String[] path, Logger log)
        throws ResourceNotFoundException, ParseErrorException, Exception {
    String filterParam = path[2].substring(0, path[2].length() - 4);
    UserModel targetUser = (UserModel) s.load(UserModel.class, new Integer(filterParam));
    UserModel currentUser = WrapperServlet.getUser(Helpers.getDefaultURL(), log, s, req.getSession());
    if (Permissions.canReadPersonalDetails(currentUser, targetUser)) {
        ctx.put("u", targetUser);
    }/*from w ww .j  a v  a2  s. co  m*/

    return getTemplate("frame/vcard.vm");
}

From source file:ca.myewb.frame.servlet.ApiServlet.java

License:Open Source License

private Template handleChapter(HttpServletRequest req, Session s, Context ctx, String[] path, Logger log)
        throws ResourceNotFoundException, ParseErrorException, Exception {
    String filterParam = path[2];

    GroupChapterModel chapter = (GroupChapterModel) HibernateUtil.currentSession()
            .createQuery("FROM GroupChapterModel g where g.shortname=?").setString(0, filterParam)
            .uniqueResult();//www .  ja v  a  2s . com

    ctx.put("chapter", chapter);

    List execs = HibernateUtil.currentSession()
            .createQuery("SELECT u FROM UserModel u, RoleModel r "
                    + "WHERE r.user=u AND r.group=? AND r.level='l' AND r.end IS NULL")
            .setEntity(0, chapter).list();

    ctx.put("execs", execs);
    UserModel currentUser = (UserModel) s.load(UserModel.class, new Integer(1));
    ctx.put("lists", Permissions.visibleGroupsInChapter(currentUser, chapter));

    return getTemplate("frame/chapterxml.vm");
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public void deleteUser(List<Integer> ids) throws PigeException {

    PermissionHelper.checkUserManagementPermission(getThreadLocalRequest());

    logger.debug("Suppression des comptes [ids = " + ids.toString() + "] ...");

    Session session = null;
    Transaction tx = null;//from   www. java  2 s  .c om

    try {
        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        for (Integer id : ids) {
            User user = (User) session.load(User.class, id);
            session.delete(user);
        }

        tx.commit();
        logger.debug("Suppression russie!");
    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public void unfreezeUser(List<Integer> ids) throws PigeException {

    PermissionHelper.checkUserManagementPermission(getThreadLocalRequest());

    logger.debug("Dgle des comptes [ids = " + ids.toString() + "] ...");

    Session session = null;
    Transaction tx = null;//from w  w  w.jav  a2  s. c o  m

    try {
        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        for (Integer id : ids) {
            User user = (User) session.load(User.class, id);
            if (user.getStatus().equals(UserStatus.STATUS_FROZEN)) {
                user.setStatus(UserStatus.STATUS_ACTIVE);
                user.setServerMessage("");
                session.update(user);
            }
        }

        tx.commit();
        logger.debug("Dgle russi!");
    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public void createUser(UserDetail userDetail) throws PigeException, UserCreationException {

    PermissionHelper.checkUserManagementPermission(getThreadLocalRequest());

    logger.debug("Ajout d'un nouveau compte avec les dtails: " + userDetail.asString() + " ...");

    String password = userDetail.getPassword();
    userDetail.setPassword(ServerUtil.produceSHA1(userDetail.getPassword()));
    Session session = null;
    Transaction tx = null;/*w  w w.  jav  a  2  s .  c o m*/

    try {

        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        // S'assurer qu'aucun autre compte utilise le mme identifiant.
        Integer count = (Integer) session.createCriteria(User.class)
                .setProjection(Projections.count(User.IDENTIFIER_REF))
                .add(Restrictions.eq(User.IDENTIFIER_REF, userDetail.getIdentifier())).uniqueResult();
        tx.commit();

        if (count > 0) {
            throw new UserCreationException("L'identifiant choisi est dj utilis par un autre compte.");
        }

        tx = session.beginTransaction();
        User account = new User(userDetail);
        Role role = (Role) session.load(Role.class, userDetail.getRoleId());
        account.setRole(role);
        session.save(account);
        tx.commit();
        logger.debug("Ajout russie!");

        final Properties props = Configurations.getProperties();
        EmailService email = new EmailService();
        email.setRecipient(userDetail.getEmail());
        email.setSubjet(props.getProperty("msg.user.email.user_creation.subject"));
        email.setBody(MessageFormat.format(props.getProperty("msg.user.email.user_creation.body"),
                userDetail.getFirstname(), userDetail.getIdentifier(), password), true);
        email.sendAsync();

    } catch (HibernateException hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

}

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

/**
 * Pour le service d'importation d'usagers.
 *///  w ww  .jav a  2  s .  c  o m
public void createUser(UserDetail userDetail, HttpServletRequest request)
        throws PigeException, UserCreationException {

    PermissionHelper.checkUserManagementPermission(request);

    logger.debug("Ajout d'un nouveau compte avec les dtails: " + userDetail.asString() + " ...");

    String password = userDetail.getPassword();
    userDetail.setPassword(ServerUtil.produceSHA1(userDetail.getPassword()));
    Session session = null;
    Transaction tx = null;

    try {

        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        // S'assurer qu'aucun autre compte utilise le mme identifiant.
        Integer count = (Integer) session.createCriteria(User.class)
                .setProjection(Projections.count(User.IDENTIFIER_REF))
                .add(Restrictions.eq(User.IDENTIFIER_REF, userDetail.getIdentifier())).uniqueResult();
        tx.commit();

        if (count > 0) {
            throw new UserCreationException("L'identifiant choisi est dj utilis par un autre compte.");
        }

        tx = session.beginTransaction();
        User account = new User(userDetail);
        Role role = (Role) session.load(Role.class, userDetail.getRoleId());
        account.setRole(role);
        session.save(account);
        tx.commit();
        logger.debug("Ajout russie!");

        final Properties props = Configurations.getProperties();
        EmailService email = new EmailService();
        email.setRecipient(userDetail.getEmail());
        email.setSubjet(props.getProperty("msg.user.email.user_creation.subject"));
        email.setBody(MessageFormat.format(props.getProperty("msg.user.email.user_creation.body"),
                userDetail.getFirstname(), userDetail.getIdentifier(), password), true);
        email.sendAsync();

    } catch (HibernateException hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

}

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public void deleteRole(List<Integer> ids) throws PigeException {

    PermissionHelper.checkRoleManagementPermission(getThreadLocalRequest());

    logger.debug("Suppression des rle [ids = " + ids.toString() + "] ...");
    Session session = null;
    Transaction tx = null;// w  ww .  j a  v a  2 s .  co m

    try {
        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        for (Integer id : ids) {
            Role role = (Role) session.load(Role.class, id);
            session.delete(role);
        }
        tx.commit();
        logger.debug("Suppression russie!");
    } catch (ConstraintViolationException cvex) {
        if (tx != null) {
            tx.rollback();
        }
        logger.debug("ConstraintViolationException");
        throw new RoleDeletionException();
    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

}