Example usage for org.hibernate Session evict

List of usage examples for org.hibernate Session evict

Introduction

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

Prototype

void evict(Object object);

Source Link

Document

Remove this instance from the session cache.

Usage

From source file:lt.bsprendimai.ddesk.ChangeDetector.java

License:Apache License

/**
 * <pre>//from  ww w .j  a v  a  2 s.c  o  m
 * Create a ticket history and change entry for ticket accept operation.
 * 
 * This method populates TicketHistory object with changes and values from changed ticket.
 * Fetches the unchanged Ticket from the database and does the comparison.
 * 
 * Prepends {taskAccepted} to the changeNotes
 * 
 * Should be called when a Ticket is changed in case of Accept operation
 * </pre>
 * 
 * See {@link ChangeDetector#preUpdate(Ticket)}
 * 
 * @param updatedTicket
 *            the changed ticket
 * @return TicketHistory object populated with changed values and detected changes
 */
public TicketHistory preAccept(Ticket updatedTicket) {
    Session sess = SessionHolder.currentSession().getSess();
    sess.evict(updatedTicket);

    Ticket originalTicket = (Ticket) sess.get(Ticket.class, updatedTicket.getId());
    sess.evict(originalTicket);

    TicketHistory th = null;

    th = copyTicket(updatedTicket);

    Person person = null;

    try {
        person = (Person) sess.get(Person.class, updatedTicket.getEditBy());
    } catch (Exception ex) {
        person = new Person();
        person.setName("{empty}");
    }

    String changeNotes;
    String publicChangeNotes;

    String[] changes = this.detectChanges(updatedTicket, originalTicket, person);
    changeNotes = changes[0];
    publicChangeNotes = changes[1];

    changeNotes = "%hb%{taskAccepted} %fs%" + person.getName() + "%sf% %df%{["
            + updatedTicket.getEditDate().getTime() + "]}%fd%%bh%" + changeNotes;
    th.setChangeNotes(changeNotes);
    if (!publicChangeNotes.trim().equals("")) {
        publicChangeNotes = "%hb% {taskAccepted} %df%{[" + updatedTicket.getEditDate().getTime() + "]}%fd%%bh%"
                + publicChangeNotes;
        th.setNotesPublic(publicChangeNotes);
    } else {
        th.setNotesPublic(null);
    }
    return th;
}

From source file:lt.bsprendimai.ddesk.ChangeDetector.java

License:Apache License

/**
 * <pre>/*from  w ww.  j  a v  a2 s.  com*/
 * Create a ticket history and change entry for ticket close operation.
 * 
 * This method populates TicketHistory object with changes and values from changed ticket.
 * Fetches the unchanged Ticket from the database and does the comparison.
 * 
 * Prepends {taskClosed} to the changeNotes
 * 
 * Should be called when a Ticket is changed as a result of Close operation
 * </pre>
 * 
 * See {@link ChangeDetector#preUpdate(Ticket)}
 * 
 * @param updatedTicket
 *            the changed ticket
 * @return TicketHistory object populated with changed values and detected changes
 * 
 */
public TicketHistory preClose(Ticket updatedTicket) {
    Session sess = SessionHolder.currentSession().getSess();
    sess.evict(updatedTicket);

    Ticket originalTicket = (Ticket) sess.get(Ticket.class, updatedTicket.getId());
    sess.evict(originalTicket);

    Person person = null;

    try {
        person = (Person) sess.get(Person.class, updatedTicket.getClosedBy());
    } catch (Exception ex) {
        person = new Person();
        person.setName("{empty}");
    }

    String changeNotes;
    String publicChangeNotes;

    String[] changes = this.detectChanges(updatedTicket, originalTicket, person);
    changeNotes = changes[0];
    publicChangeNotes = changes[1];

    TicketHistory th = null;

    th = copyTicket(updatedTicket);

    changeNotes = "%hb%{taskClosed} %fs%" + person.getName() + "%sf% %df%{["
            + updatedTicket.getDateClosed().getTime() + "]}%fd%%bh%" + changeNotes;
    th.setChangeNotes(changeNotes);
    if (!publicChangeNotes.trim().equals("")) {
        publicChangeNotes = "%hb%{taskClosed}%df%{[" + updatedTicket.getEditDate().getTime() + "]}%fd%%bh%"
                + publicChangeNotes;
        th.setNotesPublic(publicChangeNotes);
    } else {
        th.setNotesPublic(null);
    }
    // String publicChangeNotes =
    // "{taskClosed} {["+updatedTicket.getDateClosed().getTime()+"]}\n";
    // th.setNotesPublic(publicChangeNotes);
    return th;
}

From source file:lt.bsprendimai.ddesk.ChangeDetector.java

License:Apache License

/**
 * <pre>//w  w w.  jav a2s  . com
 * Create a ticket history and change entry for ticket re-open operation.
 * 
 * This method populates TicketHistory object with changes and values from changed ticket.
 * Fetches the unchanged Ticket from the database and does the comparison.
 * 
 * Prepends {teskReopen} to the changeNotes
 * 
 * Should be called when a Ticket is changed as a result of ReOPen operation
 * </pre>
 * 
 * See {@link ChangeDetector#preUpdate(Ticket)}
 * 
 * @param updatedTicket
 *            the changed ticket
 * @return TicketHistory object populated with changed values and detected changes
 */
public TicketHistory preReopen(Ticket updatedTicket) {
    Session sess = SessionHolder.currentSession().getSess();
    sess.evict(updatedTicket);

    Ticket originalTicket = (Ticket) sess.get(Ticket.class, updatedTicket.getId());
    sess.evict(originalTicket);

    Person person = null;

    try {
        person = (Person) sess.get(Person.class, updatedTicket.getEditBy());
    } catch (Exception ex) {
        person = new Person();
        person.setName("{empty}");
    }

    String changeNotes;
    String publicChangeNotes;

    String[] changes = this.detectChanges(updatedTicket, originalTicket, person);
    changeNotes = changes[0];
    publicChangeNotes = changes[1];

    TicketHistory th = null;

    th = copyTicket(updatedTicket);

    changeNotes = "%hb%{teskReopen} %fs%" + person.getName() + "%sf% %df%{["
            + originalTicket.getEditDate().getTime() + "]}%fd%%bh%" + changeNotes;
    th.setChangeNotes(changeNotes);
    if (!publicChangeNotes.trim().equals("")) {
        publicChangeNotes = "%hb% {teskReopen} %df%{[" + updatedTicket.getEditDate().getTime() + "]}%fd%%bh%"
                + publicChangeNotes;
        th.setNotesPublic(publicChangeNotes);
    } else {
        th.setNotesPublic(null);
    }
    // String publicChangeNotes =
    // "{taskClosed} {["+updatedTicket.getDateClosed().getTime()+"]}\n";
    // th.setNotesPublic(publicChangeNotes);
    return th;
}

From source file:lt.bsprendimai.ddesk.ChangeDetector.java

License:Apache License

/**
 * <pre>/* w w  w  . j  a va  2s .c  o m*/
 * Create a ticket history and change entry for new comment on ticket.
 * 
 * This method populates TicketHistory object with changes and values from changed ticket.
 * Fetches the unchanged Ticket from the database and does the comparison.
 * 
 * Prepends {addedComment} to the changeNotes
 * 
 * Should be called when a Ticket is changed as a result of Comment operation
 * </pre>
 * 
 * See {@link ChangeDetector#preUpdate(Ticket)}
 * 
 * @param updatedTicket
 *            the changed ticket
 * @param comment
 *            text of the comment (Since there is no comment field in ticket)
 * @param clientInformed
 *            if true, then this comment will be sent to the appropriate client
 * @return TicketHistory object populated with changed values and detected changes
 */
public TicketHistory preComment(Ticket updatedTicket, String comment, boolean clientInformed) {
    Session sess = SessionHolder.currentSession().getSess();
    sess.evict(updatedTicket);

    Person person = null;

    try {
        person = (Person) sess.get(Person.class, updatedTicket.getEditBy());
    } catch (Exception ex) {
        person = new Person();
        person.setName("{empty}");
    }

    TicketHistory th = copyTicket(updatedTicket);
    th.setChangeNotes(
            "%hb%{addedComment} %fs%" + person.getName() + "%sf% %df%{[" + updatedTicket.getEditDate().getTime()
                    + "]}%fd% " + (clientInformed ? "{clientNotified}%bh%" : "%bh%"));

    if (clientInformed)
        th.setNotesPublic("%hb%{addedComment} %df%{[" + updatedTicket.getEditDate().getTime()
                + "]}%fd%%bh% %dt%%ft%" + comment + "%tf%%td%");

    return th;
}

From source file:lt.bsprendimai.ddesk.ClientAccessor.java

License:Apache License

public String updatePerson() {
    if (!userHandler.isOwner())
        return StandardResults.FAIL;
    try {//from   www  . j a  va 2 s.  c o  m
        String message;
        if ((userHandler.getUser().getLoginLevel() == null || userHandler.getUser().getLoginLevel() != 0)
                && person.getId() != userHandler.getUser().getId()) {
            message = UIMessenger.getMessage(userHandler.getUserLocale(), "application.unsaved");
            UIMessenger.addInfoMessage(message, "");
            return StandardResults.FAIL;
        }

        if (pwd1 != null && !pwd1.equals("")) {
            if (!pwd1.equals(pwd2)) {
                message = UIMessenger.getMessage(userHandler.getUserLocale(),
                        "application.login.passwordsDoNotMatch");
                UIMessenger.addErrorMessage(message, "");
                return StandardResults.FAIL;
            }

            String password = new BigInteger(1, MessageDigest.getInstance("MD5").digest(pwd2.getBytes()))
                    .toString(16);
            person.setPassword("");
            if (password.length() < 32) {
                for (int i = (32 - password.length()); i > 0; i--) {
                    password = "0" + password;
                }
            }
            person.setPassword(password);
        }

        String lang = ParameterAccess.getLanguages().get(getLanguage()).toLowerCase();
        person.setLanguage(lang);

        if (person.isLoginChange()) {

            Session sess = SessionHolder.currentSession().getSess();
            sess.evict(this.person);
            int i = (Integer) sess
                    .createQuery("SELECT count(*) FROM " + Person.class.getName() + " e WHERE e.loginCode = ? ")
                    .setString(0, person.getLoginCode()).iterate().next();

            if (i > 0) {
                message = UIMessenger.getMessage(userHandler.getUserLocale(), "application.login.loginExists");
                UIMessenger.addErrorMessage(message, "");
                return StandardResults.FAIL;
            } else {
                this.person.setLoginChange(false);
            }
        }

        if (!person.update().equals(StandardResults.SUCCESS)) {
            SessionHolder.endSession();
            UIMessenger.addFatalKeyMessage("error.transaction.abort", userHandler.getUserLocale());
            return StandardResults.FAIL;
        }

        // if(ret.equals(StandartResults.SUCCESS)){
        // message = Messenger.getMessage(userHandler.getUserLocale(),
        // "application.login.saved");
        // Messenger.addInfoMessage(message,"");
        // }

        return StandardResults.SUCCESS;
    } catch (Exception ex) {
        ex.printStackTrace();
        return StandardResults.FAIL;
    }
}

From source file:lt.bsprendimai.ddesk.ClientAccessor.java

License:Apache License

public String addPerson() {
    if (!userHandler.isOwner())
        return StandardResults.FAIL;
    try {//from  www  . j ava  2s  . co  m
        String message;
        // System.out.println("Add person "+userHandler+" "+this.getCompanyId()+" "+userHandler.getUser());
        if ((userHandler.getUser().getLoginLevel() == null || userHandler.getUser().getLoginLevel() != 0)
                && this.getCompanyId() == 0) {
            message = UIMessenger.getMessage(userHandler.getUserLocale(), "application.unsaved");
            UIMessenger.addInfoMessage(message, "");
            return StandardResults.FAIL;
        }

        if (!pwd1.equals(pwd2)) {
            message = UIMessenger.getMessage(userHandler.getUserLocale(),
                    "application.login.passwordsDoNotMatch");
            UIMessenger.addErrorMessage(message, "");
            return StandardResults.FAIL;
        }

        String password = new BigInteger(1, MessageDigest.getInstance("MD5").digest(pwd2.getBytes()))
                .toString(16);
        person.setPassword("");
        if (password.length() < 32) {
            for (int i = (32 - password.length()); i > 0; i--) {
                password = "0" + password;
            }
        }
        person.setPassword(password);
        person.setCompany(this.getCompanyId());
        String lang = ParameterAccess.getLanguages().get(getLanguage()).toLowerCase();
        person.setLanguage(lang);

        Session sess = SessionHolder.currentSession().getSess();
        sess.evict(this.person);
        int i = (Integer) sess
                .createQuery("SELECT count(*) FROM " + Person.class.getName() + " e WHERE e.loginCode = ? ")
                .setString(0, person.getLoginCode()).iterate().next();

        if (i > 0) {
            message = UIMessenger.getMessage(userHandler.getUserLocale(), "application.login.loginExists");
            UIMessenger.addErrorMessage(message, "");
            return StandardResults.FAIL;
        }
        person.setLastLogin(new Date());

        if (!person.add().equals(StandardResults.SUCCESS)) {
            SessionHolder.endSession();
            UIMessenger.addFatalKeyMessage("error.transaction.abort", userHandler.getUserLocale());
            return StandardResults.FAIL;
        }
        this.person = new Person();

        // if(ret.equals(StandartResults.SUCCESS)){
        // message = Messenger.getMessage(userHandler.getUserLocale(),
        // "application.login.saved");
        // Messenger.addInfoMessage(message,"");
        // }

        return StandardResults.SUCCESS;
    } catch (Exception ex) {
        SessionHolder.endSession();
        UIMessenger.addFatalKeyMessage("error.transaction.abort", userHandler.getUserLocale());
        ex.printStackTrace();
        return StandardResults.FAIL;
    }
}

From source file:model.AtendimentoModel.java

public Object getLastId() {
    Session objSession = this.objSessionFactory.openSession();
    try {//from  w  w w .j  a va 2  s  .co m
        Transaction t = objSession.beginTransaction();
        Query q = objSession.createSQLQuery("select * from ultimoatendimento()");
        Object obj = q.uniqueResult();
        t.commit();
        objSession.close();
        objSession.evict(objSession);
        return obj;
    } catch (Exception e) {
        System.out.println(e.toString());
        return null;
    }
}

From source file:monasca.thresh.infrastructure.persistence.hibernate.AlarmDefinitionSqlImpl.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public List<AlarmDefinition> listAll() {

    Session session = null;
    List<AlarmDefinition> alarmDefinitions = null;

    try {/*from  w  ww . ja v a  2 s. co m*/
        session = sessionFactory.openSession();
        List<AlarmDefinitionDb> alarmDefDbList = session.createCriteria(AlarmDefinitionDb.class)
                .add(Restrictions.isNull("deletedAt")).addOrder(Order.asc("createdAt")).setReadOnly(true)
                .list();

        if (alarmDefDbList != null) {
            alarmDefinitions = Lists.newArrayListWithExpectedSize(alarmDefDbList.size());

            for (final AlarmDefinitionDb alarmDefDb : alarmDefDbList) {
                final Collection<String> matchBy = alarmDefDb.getMatchByAsCollection();
                final boolean actionEnable = alarmDefDb.isActionsEnabled();

                alarmDefinitions.add(new AlarmDefinition(alarmDefDb.getId(), alarmDefDb.getTenantId(),
                        alarmDefDb.getName(), alarmDefDb.getDescription(),
                        AlarmExpression.of(alarmDefDb.getExpression()), alarmDefDb.getSeverity().name(),
                        actionEnable, this.findSubExpressions(session, alarmDefDb.getId()),
                        matchBy.isEmpty() ? Collections.<String>emptyList() : Lists.newArrayList(matchBy)));

                session.evict(alarmDefDb);
            }

        }

        return alarmDefinitions == null ? Collections.<AlarmDefinition>emptyList() : alarmDefinitions;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:monasca.thresh.infrastructure.persistence.hibernate.AlarmDefinitionSqlImpl.java

License:Apache License

@SuppressWarnings("unchecked")
private List<SubExpression> findSubExpressions(final Session session, final String alarmDefId) {

    final List<SubExpression> subExpressions = Lists.newArrayList();
    Map<String, Map<String, String>> dimensionMap = Maps.newHashMap();

    final DetachedCriteria subAlarmDefinitionCriteria = DetachedCriteria
            .forClass(SubAlarmDefinitionDb.class, "sad").createAlias("alarmDefinition", "ad")
            .add(Restrictions.conjunction(Restrictions.eqProperty("sad.alarmDefinition.id", "ad.id"),
                    Restrictions.eq("sad.alarmDefinition.id", alarmDefId)))
            .addOrder(Order.asc("sad.id")).setProjection(Projections.property("sad.id"));

    final ScrollableResults subAlarmDefinitionDimensionResult = session
            .createCriteria(SubAlarmDefinitionDimensionDb.class).add(Property
                    .forName("subAlarmDefinitionDimensionId.subExpression.id").in(subAlarmDefinitionCriteria))
            .setReadOnly(true).scroll(ScrollMode.FORWARD_ONLY);

    final ScrollableResults subAlarmDefinitionResult = session
            .getNamedQuery(SubAlarmDefinitionDb.Queries.BY_ALARMDEFINITION_ID).setString("id", alarmDefId)
            .setReadOnly(true).scroll(ScrollMode.FORWARD_ONLY);

    while (subAlarmDefinitionDimensionResult.next()) {

        final SubAlarmDefinitionDimensionDb dim = (SubAlarmDefinitionDimensionDb) subAlarmDefinitionDimensionResult
                .get()[0];//from   w w w.j a va 2  s .com
        final SubAlarmDefinitionDimensionId id = dim.getSubAlarmDefinitionDimensionId();

        final String subAlarmId = (String) session.getIdentifier(id.getSubExpression());
        final String name = id.getDimensionName();
        final String value = dim.getValue();

        if (!dimensionMap.containsKey(subAlarmId)) {
            dimensionMap.put(subAlarmId, Maps.<String, String>newTreeMap());
        }
        dimensionMap.get(subAlarmId).put(name, value);

        session.evict(dim);
    }

    while (subAlarmDefinitionResult.next()) {
        final SubAlarmDefinitionDb def = (SubAlarmDefinitionDb) subAlarmDefinitionResult.get()[0];

        final String id = def.getId();
        final AggregateFunction function = AggregateFunction.fromJson(def.getFunction());
        final String metricName = def.getMetricName();
        final AlarmOperator operator = AlarmOperator.fromJson(def.getOperator());
        final Double threshold = def.getThreshold();
        final Integer period = def.getPeriod();
        final Integer periods = def.getPeriods();
        final Boolean deterministic = def.isDeterministic();

        Map<String, String> dimensions = dimensionMap.get(id);

        if (dimensions == null) {
            dimensions = Collections.emptyMap();
        }

        subExpressions.add(new SubExpression(id,
                new AlarmSubExpression(function, new MetricDefinition(metricName, dimensions), operator,
                        threshold, period, periods, deterministic)));

        session.evict(def);
    }

    subAlarmDefinitionDimensionResult.close();
    subAlarmDefinitionResult.close();

    return subExpressions;
}

From source file:MyServlet.Driver.java

public static void main(String[] args) {
    Student s = new Student();

    s.setId(1);//from   w w w .  j ava 2 s . c  o  m
    s.setName("imtiaz");

    Configuration cf = new Configuration();
    cf.configure("controller/hibernate.cfg.xml");

    SessionFactory sf = cf.buildSessionFactory();
    Session ses = sf.openSession();

    ses.save(s);
    ses.beginTransaction().commit();
    ses.evict(s);
}