Example usage for org.hibernate CacheMode REFRESH

List of usage examples for org.hibernate CacheMode REFRESH

Introduction

In this page you can find the example usage for org.hibernate CacheMode REFRESH.

Prototype

CacheMode REFRESH

To view the source code for org.hibernate CacheMode REFRESH.

Click Source Link

Document

The session will never read items from the cache, but will add items to the cache as it reads them from the database.

Usage

From source file:com.heimaide.server.common.persistence.BaseDao.java

License:Open Source License

public <E> Page<E> queryBySqlFromDB(Page<E> page, String sqlString, Class<?> resultClass, List param) {
    // get count//from   ww w . j  a  va  2 s .  c om
    if (!page.isDisabled() && !page.isNotCount()) {
        String countSqlString = "select count(*) from ( " + sqlString + ") k";// ?????
        // page.setCount(Long.valueOf(createSqlQuery(countSqlString,
        // parameter).uniqueResult().toString()));
        Query query = createSqlQuery(countSqlString, param);
        query.setCacheMode(CacheMode.REFRESH);
        List<Object> list = query.list();
        if (list.size() > 0) {
            page.setCount(Long.valueOf(list.get(0).toString()));
        } else {
            page.setCount(list.size());
        }
        if (page.getCount() < 1) {
            return page;
        }
    }
    // order by
    String sql = sqlString;
    if (StringUtils.isNotBlank(page.getOrderBy())) {
        sql += " order by " + page.getOrderBy();
    }
    SQLQuery query = createSqlQuery(sql, param);
    query.setCacheMode(CacheMode.REFRESH);
    // set page
    if (!page.isDisabled()) {
        query.setFirstResult(page.getFirstResult());
        query.setMaxResults(page.getMaxResults());
    }
    /*
     * Field[] fields = resultClass.getFields(); for (Field f : fields) {
    * query.addScalar(f.getName());// }
    */
    query.setResultTransformer(Transformers.aliasToBean(resultClass));
    page.setList(query.list());
    return page;
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Initializes a Criteria Query.//  w ww.ja va2s  .  co  m
 * Mandatory Attributes:<ul>
 * <li><b>name</b>: The unqualified class name driving the criteria query.</li>
 * </ul>
 * Optional Attributes:<ul>
 * <li><b>prefix</b>: The package name of the class driving the criteria query. If null, no package is assumed.</li>
 * <li><b>maxSize</b>: The maximum number of rows to return from the database.</li>
 * <li><b>fetchSize</b>: The number of rows to fetch when rows are requested. Usually not useful for AA4H.</li>
 * <li><b>cacheEnabled</b>: Enables or disables caching for the queried objects.</li>
 * <li><b>cacheMode</b>: The cache options for the queried objects.</li>
 * <li><b>flushMode</b>: The session flush options.</li>
 * <li><b>fetchMode</b>: The collection fetch options for the query.</li>
 * <li><b>lockMode</b>: The row lock options for the queried rows.</li>
 * <li><b>timeOut</b>: The query timeout option.</li>
 * <li><b>rowCountOnly</b>: Returns a count of the query rows only.</li>
 * </ul>
 * @param attrs The attributes of the processed node.
 * @return An appended or new CriteriaSpecification
 * @throws SAXException
 */
protected CriteriaSpecification processCriteria(Attributes attrs) throws SAXException {
    if (inDetached) {
        return criteriaStack.peek();
    }
    String name = attrs.getValue("name");
    String prefix = attrs.getValue("prefix");
    if (prefix != null) {
        className = prefix + "." + name;
    } else {
        className = name;
    }
    String maxSize = attrs.getValue("maxSize");
    String fetchSize = attrs.getValue("fetchSize");
    String firstResult = attrs.getValue("firstResult");
    String cacheEnabled = attrs.getValue("cacheEnabled");
    String cacheMode = attrs.getValue("cacheMode");
    String flushMode = attrs.getValue("flushMode");
    String fetchMode = attrs.getValue("fetchMode");
    String lockMode = attrs.getValue("lockMode");
    String timeOut = attrs.getValue("timeOut");
    String rowCountOnly = attrs.getValue("rowCountOnly");
    Criteria newCriteria = null;
    try {
        if (criteriaStack.size() == 0) {
            newCriteria = session.createCriteria(className);
        } else {
            newCriteria = ((Criteria) criteriaStack.peek()).createCriteria(className);
        }
        criteriaStack.push(newCriteria);
        if ("true".equalsIgnoreCase(rowCountOnly)) {
            newCriteria.setProjection(Projections.projectionList().add(Projections.rowCount())

            );
            setRowCountOnly(true);
        }
        if (maxSize != null && isRowCountOnly() == false) {
            newCriteria.setMaxResults(Integer.parseInt(maxSize));
        }
        if (fetchSize != null && isRowCountOnly() == false) {
            newCriteria.setFetchSize(Integer.parseInt(fetchSize));
        }
        if (firstResult != null && isRowCountOnly() == false) {
            newCriteria.setFirstResult(Integer.parseInt(firstResult));
        }
        if (timeOut != null) {
            newCriteria.setTimeout(Integer.parseInt(timeOut));
        }

        if ("true".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(true);
        } else if ("false".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(false);
        }
        if (fetchMode != null && fetchMode.length() > 0) {
            if ("JOIN".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.JOIN);
            } else if ("SELECT".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.SELECT);
            } else {
                newCriteria.setFetchMode(name, FetchMode.DEFAULT);
            }
        } else {
            newCriteria.setFetchMode(name, FetchMode.DEFAULT);
        }
        if (cacheMode != null && cacheMode.length() > 0) {
            if ("GET".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.GET);
            } else if ("IGNORE".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.IGNORE);
            } else if ("NORMAL".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            } else if ("PUT".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.PUT);
            } else if ("REFRESH".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.REFRESH);
            } else {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            }
        }
        if (lockMode != null && lockMode.length() > 0) {
            if ("NONE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.NONE);
            } else if ("READ".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.READ);
            } else if ("UPGRADE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE);
            } else if ("UPGRADE_NOWAIT".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE_NOWAIT);
            } else if ("WRITE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.WRITE);
            } else {
                throw new SAXException("lockMode[" + lockMode + "] Not Recognized");
            }
        }
        if (flushMode != null && flushMode.length() > 0) {
            if ("ALWAYS".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.ALWAYS);
            } else if ("AUTO".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.AUTO);
            } else if ("COMMIT".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.COMMIT);
            } else if ("NEVER".equalsIgnoreCase(flushMode)) {
                // NEVER is deprecated, so we won't throw an exception but we'll ignore it.
            } else {
                throw new SAXException("flushMode[" + flushMode + "] Not Recognized");
            }
        }
        return newCriteria;

    } catch (Exception e) {
        throw new SAXException("Unable to configure class " + className, e);
    }
}

From source file:com.ikon.dao.LanguageDAO.java

License:Open Source License

/**
 * Refresh 2nd level cache
 */
public static void refresh() throws DatabaseException {
    findAll(CacheMode.REFRESH);
}

From source file:org.pentaho.platform.repository.datasource.DatasourceMgmtService.java

License:Open Source License

public void createDatasource(IDatasource newDatasource)
        throws DuplicateDatasourceException, DatasourceMgmtServiceException {
    Session session = HibernateUtil.getSession();
    if (newDatasource != null) {
        if (getDatasource(newDatasource.getName()) == null) {
            try {
                session.setCacheMode(CacheMode.REFRESH);
                IPasswordService passwordService = PentahoSystem.getObjectFactory().get(IPasswordService.class,
                        null);//from w  ww  .ja va  2s .c o m
                newDatasource.setPassword(passwordService.encrypt(newDatasource.getPassword()));
                session.save(newDatasource);
            } catch (ObjectFactoryException objface) {
                throw new DatasourceMgmtServiceException(Messages
                        .getErrorString("DatasourceMgmtService.ERROR_0009_UNABLE_TO_INIT_PASSWORD_SERVICE")); //$NON-NLS-1$
            } catch (PasswordServiceException pse) {
                session.evict(newDatasource);
                throw new DatasourceMgmtServiceException(
                        Messages.getErrorString("DatasourceMgmtService.ERROR_0007_UNABLE_TO_ENCRYPT_PASSWORD"), //$NON-NLS-1$
                        pse);
            } catch (HibernateException ex) {
                session.evict(newDatasource);
                throw new DatasourceMgmtServiceException(
                        Messages.getErrorString("DatasourceMgmtService.ERROR_0001_UNABLE_TO_CREATE_DATASOURCE", //$NON-NLS-1$
                                newDatasource.getName()),
                        ex);
            } finally {
                session.setCacheMode(CacheMode.NORMAL);
            }
        } else {
            throw new DuplicateDatasourceException(Messages.getErrorString(
                    "DatasourceMgmtService.ERROR_0005_DATASOURCE_ALREADY_EXIST", newDatasource.getName()));//$NON-NLS-1$
        }
    } else {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0010_NULL_DATASOURCE_OBJECT"));//$NON-NLS-1$
    }
    session.setCacheMode(CacheMode.NORMAL);
    HibernateUtil.flushSession();
}

From source file:org.pentaho.platform.repository.datasource.DatasourceMgmtService.java

License:Open Source License

public void deleteDatasource(IDatasource datasource)
        throws NonExistingDatasourceException, DatasourceMgmtServiceException {
    Session session = HibernateUtil.getSession();
    if (datasource != null) {
        try {//from ww w. j  av  a2  s.  c  o  m
            session.setCacheMode(CacheMode.REFRESH);
            session.delete(session.merge(datasource));
        } catch (HibernateException ex) {
            throw new DatasourceMgmtServiceException(ex.getMessage(), ex);
        } finally {
            session.setCacheMode(CacheMode.NORMAL);
        }
    } else {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0010_NULL_DATASOURCE_OBJECT"));//$NON-NLS-1$
    }

    HibernateUtil.flushSession();
}

From source file:org.pentaho.platform.repository.datasource.DatasourceMgmtService.java

License:Open Source License

public IDatasource getDatasource(String jndiName) throws DatasourceMgmtServiceException {
    Session session = HibernateUtil.getSession();
    IDatasource datasource = null;//w ww.j ava  2 s  .c  o  m
    try {
        session.setCacheMode(CacheMode.REFRESH);
        IDatasource pentahoDatasource = (IDatasource) session.get(Datasource.class, jndiName);
        if (pentahoDatasource != null) {
            datasource = clone(pentahoDatasource);
            IPasswordService passwordService = PentahoSystem.getObjectFactory().get(IPasswordService.class,
                    null);
            datasource.setPassword(passwordService.decrypt(datasource.getPassword()));
        }
        return datasource;
    } catch (ObjectFactoryException objface) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0009_UNABLE_TO_INIT_PASSWORD_SERVICE"), //$NON-NLS-1$
                objface);
    } catch (PasswordServiceException pse) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0008_UNABLE_TO_DECRYPT_PASSWORD"), pse);//$NON-NLS-1$
    } catch (HibernateException ex) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0004_UNABLE_TO_RETRIEVE_DATASOURCE"), ex);//$NON-NLS-1$
    } finally {
        session.setCacheMode(CacheMode.NORMAL);
    }
}

From source file:org.pentaho.platform.repository.datasource.DatasourceMgmtService.java

License:Open Source License

public List<IDatasource> getDatasources() throws DatasourceMgmtServiceException {
    Session session = HibernateUtil.getSession();
    try {//from w  ww  .j av  a  2  s.  co m
        session.setCacheMode(CacheMode.REFRESH);
        String nameQuery = "org.pentaho.platform.repository.datasource.Datasource.findAllDatasources"; //$NON-NLS-1$
        Query qry = session.getNamedQuery(nameQuery).setCacheable(true);
        List<IDatasource> pentahoDatasourceList = qry.list();
        List<IDatasource> datasourceList = new ArrayList<IDatasource>();
        for (IDatasource pentahoDatasource : pentahoDatasourceList) {
            IDatasource datasource = clone(pentahoDatasource);
            IPasswordService passwordService = PentahoSystem.getObjectFactory().get(IPasswordService.class,
                    null);
            datasource.setPassword(passwordService.decrypt(datasource.getPassword()));
            datasourceList.add(datasource);
        }
        return datasourceList;
    } catch (PasswordServiceException pse) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0007_UNABLE_TO_ENCRYPT_PASSWORD"), pse);//$NON-NLS-1$
    } catch (ObjectFactoryException objface) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0009_UNABLE_TO_INIT_PASSWORD_SERVICE"), //$NON-NLS-1$
                objface);
    } catch (HibernateException ex) {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0004_UNABLE_TO_RETRIEVE_DATASOURCE", ""), //$NON-NLS-1$//$NON-NLS-2$
                ex);
    } finally {
        session.setCacheMode(CacheMode.NORMAL);
    }
}

From source file:org.pentaho.platform.repository.datasource.DatasourceMgmtService.java

License:Open Source License

public void updateDatasource(IDatasource datasource)
        throws NonExistingDatasourceException, DatasourceMgmtServiceException {
    Session session = HibernateUtil.getSession();
    if (datasource != null) {
        IDatasource tmpDatasource = getDatasource(datasource.getName());
        if (tmpDatasource != null) {
            try {
                session.setCacheMode(CacheMode.REFRESH);
                IPasswordService passwordService = PentahoSystem.getObjectFactory().get(IPasswordService.class,
                        null);// w w w . j  a v  a  2  s  .  c  o  m
                // Store the new encrypted password in the datasource object
                datasource.setPassword(passwordService.encrypt(datasource.getPassword()));

                // BISERVER-5677 - clear the old datasource from the datasource service cache so updates will be available
                // without having to restart the server
                IDatasourceService datasourceService = PentahoSystem.getObjectFactory()
                        .get(IDatasourceService.class, null);
                datasourceService.clearDataSource(datasource.getName());

                session.update(session.merge(datasource));
            } catch (ObjectFactoryException objface) {
                throw new DatasourceMgmtServiceException(Messages.getErrorString(
                        "DatasourceMgmtService.ERROR_0009_UNABLE_TO_INIT_PASSWORD_SERVICE"), objface);//$NON-NLS-1$
            } catch (PasswordServiceException pse) {
                throw new DatasourceMgmtServiceException(
                        Messages.getErrorString("DatasourceMgmtService.ERROR_0007_UNABLE_TO_ENCRYPT_PASSWORD"), //$NON-NLS-1$
                        pse);
            } catch (HibernateException ex) {
                throw new DatasourceMgmtServiceException(Messages.getErrorString(
                        "DatasourceMgmtService.ERROR_0004_UNABLE_TO_RETRIEVE_DATASOURCE", datasource.getName()), //$NON-NLS-1$
                        ex);
            } finally {
                session.setCacheMode(CacheMode.NORMAL);
            }
        } else {
            throw new NonExistingDatasourceException(Messages.getErrorString(
                    "DatasourceMgmtService.ERROR_0006_DATASOURCE_DOES_NOT_EXIST", datasource.getName()));//$NON-NLS-1$
        }
    } else {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0010_NULL_DATASOURCE_OBJECT"));//$NON-NLS-1$
    }
}

From source file:org.unitime.banner.onlinesectioning.BannerStudentUpdates.java

License:Apache License

@SuppressWarnings("unchecked")
public void processMessage(org.hibernate.Session hibSession, Element rootElement) {
    if (!"studentUpdates".equalsIgnoreCase(rootElement.getName()))
        return;/*from w ww  .  j a v a2 s. c  om*/
    long maxElementTime = 0, minElementTime = 0;
    int elementCount = 0;
    boolean trimLeadingZerosFromExternalId = ApplicationProperty.DataExchangeTrimLeadingZerosFromExternalIds
            .isTrue();
    Map<String, List<Long>> session2ids = new HashMap<String, List<Long>>();
    Set<String> failedStudents = new HashSet<String>();
    Set<String> problemStudents = new HashSet<String>();
    Set<String> updatedStudents = new HashSet<String>();
    Map<Long, Set<Long>> session2studentIds = new HashMap<Long, Set<Long>>();
    long start = System.currentTimeMillis();
    for (Iterator<?> i = rootElement.elementIterator("student"); i.hasNext();) {
        Element studentElement = (Element) i.next();
        long t0 = System.currentTimeMillis();
        try {
            String externalId = studentElement.attributeValue("externalId");
            if (externalId == null) {
                error("No externalId was given for a student.");
                continue;
            }
            while (trimLeadingZerosFromExternalId && externalId.startsWith("0"))
                externalId = externalId.substring(1);

            String bannerSession = studentElement.attributeValue("session");
            if (bannerSession == null) {
                error("No session was given for a student.");
                continue;
            }
            List<Long> sessionIds = session2ids.get(bannerSession);
            if (sessionIds == null) {
                sessionIds = (List<Long>) hibSession.createQuery(
                        "select bs.session.uniqueId from BannerSession bs where bs.bannerTermCode = :termCode")
                        .setString("termCode", bannerSession).list();
                session2ids.put(bannerSession, sessionIds);
            }

            BannerUpdateStudentAction update = new BannerUpdateStudentAction();
            update.forStudent(externalId, bannerSession);
            update.withName(studentElement.attributeValue("firstName"),
                    studentElement.attributeValue("middleName"), studentElement.attributeValue("lastName"));
            update.withEmail(studentElement.attributeValue("email"));

            Element studentMajorsElement = studentElement.element("studentMajors");
            Element studentAcadAreaClassElement = studentElement.element("studentAcadAreaClass");
            if (studentMajorsElement != null) {
                // Student XML format
                update.updateAcadAreaClassificationMajors(true);
                for (Iterator<?> j = studentMajorsElement.elementIterator("major"); j.hasNext();) {
                    Element majorElement = (Element) j.next();
                    if (majorElement.attributeValue("academicClass") == null
                            && studentAcadAreaClassElement != null) {
                        for (Iterator<?> k = studentAcadAreaClassElement.elementIterator("acadAreaClass"); k
                                .hasNext();) {
                            Element areaClassElement = (Element) k.next();
                            if (majorElement.attributeValue("academicArea")
                                    .equals(areaClassElement.attributeValue("academicArea")))
                                update.withAcadAreaClassificationMajor(
                                        majorElement.attributeValue("academicArea"),
                                        areaClassElement.attributeValue("academicClass"),
                                        majorElement.attributeValue("code"),
                                        majorElement.attributeValue("campus"));
                        }
                    } else {
                        update.withAcadAreaClassificationMajor(majorElement.attributeValue("academicArea"),
                                majorElement.attributeValue("academicClass"),
                                majorElement.attributeValue("code"), majorElement.attributeValue("campus"));
                    }
                }
            } else {
                // Old banner update message format
                update.withAcadAreaClassificationMajor(studentElement.attributeValue("academicArea"),
                        studentElement.attributeValue("classification"), studentElement.attributeValue("major"),
                        studentElement.attributeValue("campus"));
            }

            Element studentGroupsElement = studentElement.element("studentGroups");
            if (studentGroupsElement != null) {
                // Student XML format
                for (Iterator<?> j = studentGroupsElement.elementIterator("studentGroup"); j.hasNext();) {
                    Element studentGroupElement = (Element) j.next();
                    update.withGroup(
                            studentGroupElement.attributeValue("externalId",
                                    studentGroupElement.attributeValue("group")),
                            studentGroupElement.attributeValue("campus"),
                            studentGroupElement.attributeValue("abbreviation",
                                    studentGroupElement.attributeValue("group")),
                            studentGroupElement.attributeValue("name"));
                }
            } else {
                // Old banner upadte message format
                for (Iterator<?> j = studentElement.elementIterator("studentGroup"); j.hasNext();) {
                    Element studentGroupElement = (Element) j.next();
                    update.withGroup(studentGroupElement.attributeValue("externalId"),
                            studentGroupElement.attributeValue("campus"),
                            studentGroupElement.attributeValue("abbreviation"),
                            studentGroupElement.attributeValue("name"));
                }
            }

            // Old banner update message format
            for (Iterator<?> j = studentElement.elementIterator("crn"); j.hasNext();) {
                Element crnElement = (Element) j.next();
                try {
                    update.withCRN(Integer.valueOf(crnElement.getTextTrim()));
                } catch (Exception e) {
                    error("An integer value is required for a crn element (student " + externalId + ").");
                    problemStudents.add(externalId);
                }
            }
            // Student enrollment XML format
            for (Iterator<?> j = studentElement.elementIterator("class"); j.hasNext();) {
                Element classElement = (Element) j.next();
                try {
                    update.withCRN(Integer.valueOf(classElement.attributeValue("externalId")));
                } catch (Exception e) {
                    error("An integer value is required as external id of a class element (student "
                            + externalId + ").");
                    problemStudents.add(externalId);
                }
            }

            // Overrides
            for (Iterator<?> j = studentElement.elementIterator("override"); j.hasNext();) {
                Element overrideElement = (Element) j.next();
                update.withOverride(overrideElement.attributeValue("type"),
                        overrideElement.attributeValue("subject"),
                        overrideElement.attributeValue("course", overrideElement.attributeValue("courseNbr")),
                        overrideElement.attributeValue("crn"));
            }

            // Student advisors
            for (Iterator<?> j = studentElement.elementIterator("advisor"); j.hasNext();) {
                Element advisorElement = (Element) j.next();
                String advisorExternalId = advisorElement.attributeValue("advisorId");
                if (advisorExternalId == null) {
                    error("No externalId was given for an advisor.");
                    continue;
                }
                while (trimLeadingZerosFromExternalId && advisorExternalId.startsWith("0"))
                    advisorExternalId = advisorExternalId.substring(1);
                update.withAdvisor(advisorExternalId, advisorElement.attributeValue("advisorType"));
            }

            // Sports
            for (Iterator<?> j = studentElement.elementIterator("sport"); j.hasNext();) {
                Element sportElement = (Element) j.next();
                update.withGroup(
                        sportElement.attributeValue("externalId", sportElement.attributeValue("group")),
                        sportElement.attributeValue("campus"), sportElement.attributeValue("group"),
                        sportElement.attributeValue("groupname", sportElement.attributeValue("group")),
                        "SPORT");
            }

            // Cohorts
            for (Iterator<?> j = studentElement.elementIterator("cohort"); j.hasNext();) {
                Element sportElement = (Element) j.next();
                update.withGroup(
                        sportElement.attributeValue("externalId", sportElement.attributeValue("group")),
                        sportElement.attributeValue("campus"), sportElement.attributeValue("group"),
                        sportElement.attributeValue("groupname", sportElement.attributeValue("group")),
                        "COHORT");
            }

            for (Long sessionId : sessionIds) {
                try {
                    OnlineSectioningServer server = (iContainer == null ? null
                            : iContainer.getSolver(sessionId.toString()));
                    if (server != null && server.isReady()) {
                        try {
                            switch (server.execute(update, user())) {
                            case OK:
                                updatedStudents.add(externalId);
                                break;
                            case FAILURE:
                                failedStudents.add(externalId);
                                break;
                            case PROBLEM:
                                problemStudents.add(externalId);
                                break;
                            case NO_CHANGE:
                            }
                        } finally {
                            _RootDAO.closeCurrentThreadSessions();
                        }
                    } else {
                        OnlineSectioningHelper h = new OnlineSectioningHelper(
                                QueueInDAO.getInstance().createNewSession(), user(), CacheMode.REFRESH);
                        try {
                            h.addMessageHandler(this);
                            UpdateResult result = update.execute(sessionId, h);
                            switch (result) {
                            case OK:
                                updatedStudents.add(externalId);
                                break;
                            case FAILURE:
                                failedStudents.add(externalId);
                                break;
                            case PROBLEM:
                                problemStudents.add(externalId);
                                break;
                            case NO_CHANGE:
                            }
                            if (update.getStudentId() != null
                                    && (result == UpdateResult.OK || result == UpdateResult.PROBLEM)) {
                                Set<Long> ids = session2studentIds.get(sessionId);
                                if (ids == null) {
                                    ids = new HashSet<Long>();
                                    session2studentIds.put(sessionId, ids);
                                }
                                ids.add(update.getStudentId());
                            }
                        } finally {
                            h.getHibSession().close();
                        }
                    }
                } catch (Exception e) {
                    error("Failed to update student " + externalId + ": " + e.getMessage());
                    failedStudents.add(externalId);
                }
            }

        } finally {
            long time = (System.currentTimeMillis() - t0);
            if (elementCount == 0 || time < minElementTime) {
                minElementTime = time;
            }
            if (elementCount == 0 || time > maxElementTime) {
                maxElementTime = time;
            }
            elementCount++;
        }
    }
    long end = System.currentTimeMillis();
    info(updatedStudents.size() + " student records updated in " + (end - start) + " milliseconds.");
    info(failedStudents.size() + " student records failed to update.");
    info(problemStudents.size() + " student records were updated, but had problems.");
    if (elementCount > 0) {
        info("Minimum milliseconds required to process a record = " + minElementTime);
        info("Maximum milliseconds required to process a record = " + maxElementTime);
        info("Average milliseconds required to process a record = " + ((end - start) / elementCount));
    }
    if (!failedStudents.isEmpty()) {
        error("The following student ids were not successfully processed:  ");
        for (String studentId : failedStudents)
            error("\t" + studentId);
    }
    if (!problemStudents.isEmpty()) {
        error("The following student ids were successfully processed, but may have had problems finding all classes the student was enrolled in:  ");
        for (String studentId : problemStudents)
            error("\t" + studentId);
    }
    for (Map.Entry<Long, Set<Long>> entry : session2studentIds.entrySet()) {
        StudentSectioningQueue.studentChanged(hibSession, null, entry.getKey(), entry.getValue());
    }
    hibSession.flush();
}

From source file:org.unitime.colleague.onlinesectioning.ColleagueStudentUpdates.java

License:Apache License

@SuppressWarnings("unchecked")
public void processMessage(org.hibernate.Session hibSession, Element rootElement) {
    if (!"studentUpdates".equalsIgnoreCase(rootElement.getName()))
        return;/* w ww. j a v a  2 s  . com*/
    long maxElementTime = 0, minElementTime = 0;
    int elementCount = 0;
    boolean trimLeadingZerosFromExternalId = ApplicationProperty.DataExchangeTrimLeadingZerosFromExternalIds
            .isTrue();
    Map<String, List<Long>> session2ids = new HashMap<String, List<Long>>();
    Set<String> failedStudents = new HashSet<String>();
    Set<String> problemStudents = new HashSet<String>();
    Set<String> updatedStudents = new HashSet<String>();
    Map<Long, Set<Long>> session2studentIds = new HashMap<Long, Set<Long>>();
    long start = System.currentTimeMillis();
    for (Iterator<?> i = rootElement.elementIterator("student"); i.hasNext();) {
        Element studentElement = (Element) i.next();
        long t0 = System.currentTimeMillis();
        try {
            String externalId = studentElement.attributeValue("externalId");
            if (externalId == null) {
                error("No externalId was given for a student.");
                continue;
            }
            while (trimLeadingZerosFromExternalId && externalId.startsWith("0"))
                externalId = externalId.substring(1);

            String colleagueSession = studentElement.attributeValue("session");
            if (colleagueSession == null) {
                error("No session was given for a student.");
                continue;
            }
            List<Long> sessionIds = session2ids.get(colleagueSession);
            if (sessionIds == null) {
                sessionIds = (List<Long>) hibSession.createQuery(
                        "select cs.session.uniqueId from ColleagueSession cs where cs.colleagueTermCode = :termCode")
                        .setString("termCode", colleagueSession).list();
                session2ids.put(colleagueSession, sessionIds);
            }

            ColleagueUpdateStudentAction update = new ColleagueUpdateStudentAction();
            update.forStudent(externalId, colleagueSession);
            update.withName(studentElement.attributeValue("firstName"),
                    studentElement.attributeValue("middleName"), studentElement.attributeValue("lastName"));
            update.withEmail(studentElement.attributeValue("email"));

            Element studentMajorsElement = studentElement.element("studentMajors");
            Element studentAcadAreaClassElement = studentElement.element("studentAcadAreaClass");
            if (studentMajorsElement != null) {
                // Student XML format
                update.updateAcadAreaClassificationMajors(true);
                for (Iterator<?> j = studentMajorsElement.elementIterator("major"); j.hasNext();) {
                    Element majorElement = (Element) j.next();
                    if (majorElement.attributeValue("academicClass") == null
                            && studentAcadAreaClassElement != null) {
                        for (Iterator<?> k = studentAcadAreaClassElement.elementIterator("acadAreaClass"); k
                                .hasNext();) {
                            Element areaClassElement = (Element) k.next();
                            if (majorElement.attributeValue("academicArea")
                                    .equals(areaClassElement.attributeValue("academicArea")))
                                update.withAcadAreaClassificationMajor(
                                        majorElement.attributeValue("academicArea"),
                                        areaClassElement.attributeValue("academicClass"),
                                        majorElement.attributeValue("code"));
                        }
                    } else {
                        update.withAcadAreaClassificationMajor(majorElement.attributeValue("academicArea"),
                                majorElement.attributeValue("academicClass"),
                                majorElement.attributeValue("code"));
                    }
                }
            } else {
                // Old banner update message format
                update.withAcadAreaClassificationMajor(studentElement.attributeValue("academicArea"),
                        studentElement.attributeValue("classification"),
                        studentElement.attributeValue("major"));
            }

            Element studentGroupsElement = studentElement.element("studentGroups");
            if (studentGroupsElement != null) {
                // Student XML format
                for (Iterator<?> j = studentGroupsElement.elementIterator("studentGroup"); j.hasNext();) {
                    Element studentGroupElement = (Element) j.next();
                    update.withGroup(
                            studentGroupElement.attributeValue("externalId",
                                    studentGroupElement.attributeValue("group")),
                            studentGroupElement.attributeValue("campus"),
                            studentGroupElement.attributeValue("abbreviation",
                                    studentGroupElement.attributeValue("group")),
                            studentGroupElement.attributeValue("name"));
                }
            } else {
                // Old colleague update message format
                for (Iterator<?> j = studentElement.elementIterator("studentGroup"); j.hasNext();) {
                    Element studentGroupElement = (Element) j.next();
                    update.withGroup(studentGroupElement.attributeValue("externalId"),
                            studentGroupElement.attributeValue("campus"),
                            studentGroupElement.attributeValue("abbreviation"),
                            studentGroupElement.attributeValue("name"));
                }
            }

            // Old colleague update message format
            for (Iterator<?> j = studentElement.elementIterator("colleagueSectionId"); j.hasNext();) {
                Element colleagueSectionIdElement = (Element) j.next();
                try {
                    update.withColleagueSectionId(Integer.valueOf(colleagueSectionIdElement.getTextTrim()));
                } catch (Exception e) {
                    error("An integer value is required for a colleagueSectionId element (student " + externalId
                            + ").");
                    problemStudents.add(externalId);
                }
            }
            // Student enrollment XML format
            for (Iterator<?> j = studentElement.elementIterator("class"); j.hasNext();) {
                Element classElement = (Element) j.next();
                try {
                    update.withColleagueSectionId(Integer.valueOf(classElement.attributeValue("externalId")));
                } catch (Exception e) {
                    error("An integer value is required as external id of a class element (student "
                            + externalId + ").");
                    problemStudents.add(externalId);
                }
            }

            // Overrides
            for (Iterator<?> j = studentElement.elementIterator("override"); j.hasNext();) {
                Element overrideElement = (Element) j.next();
                update.withOverride(overrideElement.attributeValue("type"),
                        overrideElement.attributeValue("subject"),
                        overrideElement.attributeValue("course", overrideElement.attributeValue("courseNbr")),
                        overrideElement.attributeValue("colleagueSectionId"));
            }

            for (Long sessionId : sessionIds) {
                try {
                    OnlineSectioningServer server = (iContainer == null ? null
                            : iContainer.getSolver(sessionId.toString()));
                    if (server != null && server.isReady()) {
                        try {
                            switch (server.execute(update, user())) {
                            case OK:
                                updatedStudents.add(externalId);
                                break;
                            case FAILURE:
                                failedStudents.add(externalId);
                                break;
                            case PROBLEM:
                                problemStudents.add(externalId);
                                break;
                            case NO_CHANGE:
                            }
                        } finally {
                            _RootDAO.closeCurrentThreadSessions();
                        }
                    } else {
                        OnlineSectioningHelper h = new OnlineSectioningHelper(
                                QueueInDAO.getInstance().createNewSession(), user(), CacheMode.REFRESH);
                        try {
                            h.addMessageHandler(this);
                            UpdateResult result = update.execute(sessionId, h);
                            switch (result) {
                            case OK:
                                updatedStudents.add(externalId);
                                break;
                            case FAILURE:
                                failedStudents.add(externalId);
                                break;
                            case PROBLEM:
                                problemStudents.add(externalId);
                                break;
                            case NO_CHANGE:
                            }
                            if (update.getStudentId() != null
                                    && (result == UpdateResult.OK || result == UpdateResult.PROBLEM)) {
                                Set<Long> ids = session2studentIds.get(sessionId);
                                if (ids == null) {
                                    ids = new HashSet<Long>();
                                    session2studentIds.put(sessionId, ids);
                                }
                                ids.add(update.getStudentId());
                            }
                        } finally {
                            h.getHibSession().close();
                        }
                    }
                } catch (Exception e) {
                    error("Failed to update student " + externalId + ": " + e.getMessage());
                    failedStudents.add(externalId);
                }
            }

        } finally {
            long time = (System.currentTimeMillis() - t0);
            if (elementCount == 0 || time < minElementTime) {
                minElementTime = time;
            }
            if (elementCount == 0 || time > maxElementTime) {
                maxElementTime = time;
            }
            elementCount++;
        }
    }
    long end = System.currentTimeMillis();
    info(updatedStudents.size() + " student records updated in " + (end - start) + " milliseconds.");
    info(failedStudents.size() + " student records failed to update.");
    info(problemStudents.size() + " student records were updated, but had problems.");
    if (elementCount > 0) {
        info("Minimum milliseconds required to process a record = " + minElementTime);
        info("Maximum milliseconds required to process a record = " + maxElementTime);
        info("Average milliseconds required to process a record = " + ((end - start) / elementCount));
    }
    if (!failedStudents.isEmpty()) {
        error("The following student ids were not successfully processed:  ");
        for (String studentId : failedStudents)
            error("\t" + studentId);
    }
    if (!problemStudents.isEmpty()) {
        error("The following student ids were successfully processed, but may have had problems finding all classes the student was enrolled in:  ");
        for (String studentId : problemStudents)
            error("\t" + studentId);
    }
    for (Map.Entry<Long, Set<Long>> entry : session2studentIds.entrySet()) {
        StudentSectioningQueue.studentChanged(hibSession, null, entry.getKey(), entry.getValue());
    }
    hibSession.flush();
}