Search in sources :

Example 16 with HibernateCallback

use of org.springframework.orm.hibernate3.HibernateCallback in project gocd by gocd.

the class AgentDao method findAgentCookieByUuid.

private AgentCookie findAgentCookieByUuid(final AgentIdentifier agentIdentifier) {
    return (AgentCookie) getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createQuery("from AgentCookie where uuid = :uuid");
            query.setString("uuid", agentIdentifier.getUuid());
            return query.uniqueResult();
        }
    });
}
Also used : Query(org.hibernate.Query) HibernateCallback(org.springframework.orm.hibernate3.HibernateCallback) AgentCookie(com.thoughtworks.go.server.domain.AgentCookie) Session(org.hibernate.Session)

Example 17 with HibernateCallback

use of org.springframework.orm.hibernate3.HibernateCallback in project gocd by gocd.

the class PipelineRepository method updatePipelineTimeline.

@SuppressWarnings({ "unchecked" })
public void updatePipelineTimeline(final PipelineTimeline pipelineTimeline, final List<PipelineTimelineEntry> tempEntriesForRollback) {
    getHibernateTemplate().execute(new HibernateCallback() {

        private static final int PIPELINE_NAME = 0;

        private static final int ID = 1;

        private static final int COUNTER = 2;

        private static final int MODIFIED_TIME = 3;

        private static final int FINGERPRINT = 4;

        private static final int NATURAL_ORDER = 5;

        private static final int REVISION = 6;

        private static final int FOLDER = 7;

        private static final int MOD_ID = 8;

        private static final int PMR_ID = 9;

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            LOGGER.info("Start updating pipeline timeline");
            List<Object[]> matches = retrieveTimeline(session, pipelineTimeline);
            List<PipelineTimelineEntry> newPipelines = populateFrom(matches);
            addEntriesToPipelineTimeline(newPipelines, pipelineTimeline, tempEntriesForRollback);
            updateNaturalOrdering(session, newPipelines);
            LOGGER.info("Pipeline timeline updated");
            return null;
        }

        private void updateNaturalOrdering(Session session, List<PipelineTimelineEntry> pipelines) {
            for (PipelineTimelineEntry pipeline : pipelines) {
                if (pipeline.hasBeenUpdated()) {
                    updateNaturalOrderForPipeline(session, pipeline.getId(), pipeline.naturalOrder());
                }
            }
        }

        private List<Object[]> loadTimeline(SQLQuery query) {
            long startedAt = System.currentTimeMillis();
            List<Object[]> matches = (List<Object[]>) query.list();
            long duration = System.currentTimeMillis() - startedAt;
            if (duration > 1000) {
                LOGGER.warn("updating in memory pipeline-timeline took: " + duration + " ms");
            }
            return matches;
        }

        private List<Object[]> retrieveTimeline(Session session, PipelineTimeline pipelineTimeline) {
            SQLQuery query = session.createSQLQuery(queryExtensions.retrievePipelineTimeline());
            query.setLong(0, pipelineTimeline.maximumId());
            List<Object[]> matches = loadTimeline(query);
            sortTimeLineByPidAndPmrId(matches);
            return matches;
        }

        private void sortTimeLineByPidAndPmrId(List<Object[]> matches) {
            Collections.sort(matches, new Comparator<Object[]>() {

                @Override
                public int compare(Object[] m1, Object[] m2) {
                    long id1 = id(m1);
                    long id2 = id(m2);
                    if (id1 == id2) {
                        return (int) (pmrId(m1) - pmrId(m2));
                    }
                    return (int) (id1 - id2);
                }
            });
        }

        private List<PipelineTimelineEntry> populateFrom(List<Object[]> matches) {
            ArrayList<PipelineTimelineEntry> newPipelines = new ArrayList<>();
            if (matches.isEmpty()) {
                return newPipelines;
            }
            Map<String, List<PipelineTimelineEntry.Revision>> revisions = new HashMap<>();
            String name = null;
            long curId = -1;
            Integer counter = null;
            double naturalOrder = 0.0;
            PipelineTimelineEntry entry = null;
            for (int i = 0; i < matches.size(); i++) {
                Object[] row = matches.get(i);
                long id = id(row);
                if (curId != id) {
                    name = pipelineName(row);
                    curId = id;
                    counter = counter(row);
                    revisions = new HashMap<>();
                    naturalOrder = naturalOrder(row);
                }
                String fingerprint = fingerprint(row);
                if (!revisions.containsKey(fingerprint)) {
                    revisions.put(fingerprint, new ArrayList<>());
                }
                revisions.get(fingerprint).add(rev(row));
                int nextI = i + 1;
                if ((//new pipeline instance starts in next record, so capture this one
                (nextI < matches.size() && id(matches.get(nextI)) != curId) || nextI == matches.size())) {
                    //this is the last record, so capture it
                    entry = new PipelineTimelineEntry(name, curId, counter, revisions, naturalOrder);
                    newPipelines.add(entry);
                }
            }
            return newPipelines;
        }

        private String folder(Object[] row) {
            return (String) row[FOLDER];
        }

        private PipelineTimelineEntry.Revision rev(Object[] row) {
            return new PipelineTimelineEntry.Revision(modifiedTime(row), stringRevision(row), folder(row), modId(row));
        }

        private long pmrId(Object[] row) {
            return ((BigInteger) row[PMR_ID]).longValue();
        }

        private long modId(Object[] row) {
            return ((BigInteger) row[MOD_ID]).longValue();
        }

        private double naturalOrder(Object[] row) {
            return (Double) row[NATURAL_ORDER];
        }

        private Date modifiedTime(Object[] row) {
            return (Date) row[MODIFIED_TIME];
        }

        private String stringRevision(Object[] row) {
            return (String) row[REVISION];
        }

        private String fingerprint(Object[] row) {
            return String.valueOf(row[FINGERPRINT]);
        }

        private String pipelineName(Object[] row) {
            return (String) row[PIPELINE_NAME];
        }

        private int counter(Object[] row) {
            return row[COUNTER] == null ? -1 : ((BigInteger) row[COUNTER]).intValue();
        }

        private long id(Object[] first) {
            return ((BigInteger) first[ID]).longValue();
        }
    });
}
Also used : SQLException(java.sql.SQLException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SQLQuery(org.hibernate.SQLQuery) PipelineTimelineEntry(com.thoughtworks.go.domain.PipelineTimelineEntry) PipelineTimeline(com.thoughtworks.go.server.domain.PipelineTimeline) Comparator(java.util.Comparator) ArrayList(java.util.ArrayList) List(java.util.List) HibernateCallback(org.springframework.orm.hibernate3.HibernateCallback) HibernateException(org.hibernate.HibernateException) Date(java.util.Date) BigInteger(java.math.BigInteger) BigInteger(java.math.BigInteger) HashMap(java.util.HashMap) Map(java.util.Map) Session(org.hibernate.Session)

Example 18 with HibernateCallback

use of org.springframework.orm.hibernate3.HibernateCallback in project gocd by gocd.

the class ServerBackupRepository method lastBackup.

public ServerBackup lastBackup() {
    List results = (List) getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = session.createCriteria(ServerBackup.class);
            criteria.setMaxResults(1);
            criteria.addOrder(Order.desc("id"));
            return criteria.list();
        }
    });
    return results.isEmpty() ? null : (ServerBackup) results.get(0);
}
Also used : List(java.util.List) HibernateCallback(org.springframework.orm.hibernate3.HibernateCallback) Criteria(org.hibernate.Criteria) Session(org.hibernate.Session)

Example 19 with HibernateCallback

use of org.springframework.orm.hibernate3.HibernateCallback in project gocd by gocd.

the class MaterialRepository method getModificationsFor.

public Modifications getModificationsFor(final MaterialInstance materialInstance, final Pagination pagination) {
    String key = materialModificationsWithPaginationKey(materialInstance);
    String subKey = materialModificationsWithPaginationSubKey(pagination);
    Modifications modifications = (Modifications) goCache.get(key, subKey);
    if (modifications == null) {
        synchronized (key) {
            modifications = (Modifications) goCache.get(key, subKey);
            if (modifications == null) {
                List<Modification> modificationsList = getHibernateTemplate().executeFind(new HibernateCallback() {

                    public Object doInHibernate(Session session) throws HibernateException, SQLException {
                        Query q = session.createQuery("FROM Modification WHERE materialId = ? ORDER BY id DESC");
                        q.setFirstResult(pagination.getOffset());
                        q.setMaxResults(pagination.getPageSize());
                        q.setLong(0, materialInstance.getId());
                        return q.list();
                    }
                });
                if (!modificationsList.isEmpty()) {
                    modifications = new Modifications(modificationsList);
                    goCache.put(key, subKey, modifications);
                }
            }
        }
    }
    return modifications;
}
Also used : SQLException(java.sql.SQLException) CaseInsensitiveString(com.thoughtworks.go.config.CaseInsensitiveString) HibernateCallback(org.springframework.orm.hibernate3.HibernateCallback)

Example 20 with HibernateCallback

use of org.springframework.orm.hibernate3.HibernateCallback in project gocd by gocd.

the class MaterialRepository method findModificationsForPipelineIds.

public Map<Long, List<ModificationForPipeline>> findModificationsForPipelineIds(final List<Long> pipelineIds) {
    final int MODIFICATION = 0;
    final int RELEVANT_PIPELINE_ID = 1;
    final int RELEVANT_PIPELINE_NAME = 2;
    final int MATERIAL_TYPE = 3;
    final int MATERIAL_FINGERPRINT = 4;
    //noinspection unchecked
    return (Map<Long, List<ModificationForPipeline>>) getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            if (pipelineIds.isEmpty()) {
                return new HashMap<Long, List<ModificationForPipeline>>();
            }
            Map<PipelineId, Set<Long>> relevantToLookedUpMap = relevantToLookedUpDependencyMap(session, pipelineIds);
            SQLQuery query = session.createSQLQuery("SELECT mods.*, pmr.pipelineId as pmrPipelineId, p.name as pmrPipelineName, m.type as materialType, m.fingerprint as fingerprint" + " FROM modifications mods " + "     INNER JOIN pipelineMaterialRevisions pmr ON (mods.id >= pmr.fromRevisionId AND mods.id <= pmr.toRevisionId) AND mods.materialId = pmr.materialId " + "     INNER JOIN pipelines p ON pmr.pipelineId = p.id" + "     INNER JOIN materials m ON mods.materialId = m.id" + " WHERE pmr.pipelineId IN (:ids)");
            @SuppressWarnings({ "unchecked" }) List<Object[]> allModifications = query.addEntity("mods", Modification.class).addScalar("pmrPipelineId", new LongType()).addScalar("pmrPipelineName", new StringType()).addScalar("materialType", new StringType()).addScalar("fingerprint", new StringType()).setParameterList("ids", CollectionUtil.map(relevantToLookedUpMap.keySet(), PipelineId.MAP_ID)).list();
            Map<Long, List<ModificationForPipeline>> modificationsForPipeline = new HashMap<>();
            CollectionUtil.CollectionValueMap<Long, ModificationForPipeline> modsForPipeline = CollectionUtil.collectionValMap(modificationsForPipeline, new CollectionUtil.ArrayList<>());
            for (Object[] modAndPmr : allModifications) {
                Modification mod = (Modification) modAndPmr[MODIFICATION];
                Long relevantPipelineId = (Long) modAndPmr[RELEVANT_PIPELINE_ID];
                String relevantPipelineName = (String) modAndPmr[RELEVANT_PIPELINE_NAME];
                String materialType = (String) modAndPmr[MATERIAL_TYPE];
                String materialFingerprint = (String) modAndPmr[MATERIAL_FINGERPRINT];
                PipelineId relevantPipeline = new PipelineId(relevantPipelineName, relevantPipelineId);
                Set<Long> longs = relevantToLookedUpMap.get(relevantPipeline);
                for (Long lookedUpPipeline : longs) {
                    modsForPipeline.put(lookedUpPipeline, new ModificationForPipeline(relevantPipeline, mod, materialType, materialFingerprint));
                }
            }
            return modificationsForPipeline;
        }
    });
}
Also used : LongType(org.hibernate.type.LongType) StringType(org.hibernate.type.StringType) CaseInsensitiveString(com.thoughtworks.go.config.CaseInsensitiveString) PipelineId(com.thoughtworks.go.server.ui.PipelineId) HibernateCallback(org.springframework.orm.hibernate3.HibernateCallback) ModificationForPipeline(com.thoughtworks.go.server.ui.ModificationForPipeline) CollectionUtil(com.thoughtworks.go.server.util.CollectionUtil)

Aggregations

HibernateCallback (org.springframework.orm.hibernate3.HibernateCallback)27 Session (org.hibernate.Session)15 CaseInsensitiveString (com.thoughtworks.go.config.CaseInsensitiveString)10 SQLException (java.sql.SQLException)7 Query (org.hibernate.Query)6 List (java.util.List)5 Criteria (org.hibernate.Criteria)5 Test (org.junit.Test)4 OnmsCriteria (org.opennms.netmgt.model.OnmsCriteria)4 AgentCookie (com.thoughtworks.go.server.domain.AgentCookie)3 BigInteger (java.math.BigInteger)3 HibernateException (org.hibernate.HibernateException)3 AgentIdentifier (com.thoughtworks.go.remote.AgentIdentifier)2 ArrayList (java.util.ArrayList)2 SQLQuery (org.hibernate.SQLQuery)2 LongType (org.hibernate.type.LongType)2 RunIf (com.googlecode.junit.ext.RunIf)1 AbstractMaterial (com.thoughtworks.go.config.materials.AbstractMaterial)1 DependencyMaterial (com.thoughtworks.go.config.materials.dependency.DependencyMaterial)1 HgMaterial (com.thoughtworks.go.config.materials.mercurial.HgMaterial)1