ObservationRepositoryCustomImpl.java

/*
 * Copyright 2020 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.gringlobal.persistence.kpi;

import java.util.Set;
import java.util.stream.Collectors;

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;
import org.gringlobal.model.kpi.DimensionKey;
import org.gringlobal.model.kpi.ExecutionRun;
import org.gringlobal.model.kpi.Observation;
import org.gringlobal.model.kpi.QObservation;
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;

public class ObservationRepositoryCustomImpl implements ObservationCustomRepository {

	@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()));

		var dksExpressions = dks.stream().map(dk -> QObservation.observation.dimensions.any().eq(dk)).collect(Collectors.toList());
		for(BooleanExpression expression: dksExpressions) {
			filters = filters.and(expression);
		}

		JPAQuery<Observation> q = jpaQueryFactory.select(QObservation.observation)
				.from(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);
	}

}