ObservationRepositoryCustomImpl.java

/*
 * Copyright 2018 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.genesys.server.persistence.kpi;

import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.collections4.CollectionUtils;
import org.genesys.server.model.kpi.DimensionKey;
import org.genesys.server.model.kpi.Execution;
import org.genesys.server.model.kpi.ExecutionRun;
import org.genesys.server.model.kpi.Observation;
import org.genesys.server.model.kpi.QObservation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.PathBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;

@Repository
public class ObservationRepositoryCustomImpl implements ObservationCustomRepository {
    public static final Logger LOG = LoggerFactory.getLogger(ObservationRepositoryCustomImpl.class);

	@PersistenceContext
	private EntityManager entityManager;

	@Autowired
	private JPAQueryFactory jpaQueryFactory;

	@Override
	public Page<Observation> findObservations(ExecutionRun executionRun, Set<DimensionKey> dks, Pageable page) {
		BooleanExpression filters = QObservation.observation.executionRun().eq(executionRun).and(QObservation.observation.dimensionCount.eq(dks.size()));
		if (CollectionUtils.isNotEmpty(dks)) {
			filters.and(QObservation.observation.dimensions.any().in(dks));
		}

		JPAQuery<Observation> q = jpaQueryFactory.select(QObservation.observation)
				// where
				.where(filters);
		
		if (page.getSort().iterator().hasNext()) {
			PathBuilder<Observation> entityPath = new PathBuilder<>(Observation.class, "observation");
			page.getSort().forEach(order -> {
				// order
				PathBuilder<?> path = entityPath.get(order.getProperty());
				q.orderBy(new OrderSpecifier(com.querydsl.core.types.Order.valueOf(order.getDirection().name()), path));
			});
		} else {
			// this was the default
			q.orderBy(QObservation.observation.id.asc());
		}

		long total = q.fetchCount();

		q.offset(page.getOffset()).limit(page.getPageSize());
		return new PageImpl<>(q.fetch(), page, total);
	}

	@Override
	public Observation findLastObservation(Execution execution, Set<DimensionKey> dks) {
		StringBuilder where = new StringBuilder();
		final int OFFSET = 3;
		for (int i = 0; i < dks.size(); i++) {
			where.append("and ?").append(i + OFFSET).append(" member of o.dimensions ");
		}

		Query q = entityManager.createQuery("select o from Observation o where o.execution=?1 and o.dimensionCount=?2 " + where.toString()
				+ " order by o.timestamp desc", Observation.class);
		q.setMaxResults(1);
		q.setParameter(1, execution);
		q.setParameter(2, dks.size());

		int i = OFFSET;
		for (DimensionKey dk : dks) {
			q.setParameter(i, dk);
			i++;
		}

		return (Observation) q.getSingleResult();
	}
}