Search in sources :

Example 1 with PaginationFilter

use of uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter in project miso-lims by miso-lims.

the class HibernateRunDao method list.

@Override
public List<Run> list(Consumer<String> errorHandler, int offset, int limit, boolean sortDir, String sortCol, PaginationFilter... filter) throws IOException {
    List<Run> runs = HibernatePaginatedDataSource.super.list(errorHandler, offset, limit, sortDir, sortCol, filter);
    if (runs.isEmpty()) {
        return runs;
    }
    @SuppressWarnings("unchecked") List<Object[]> results = currentSession().createCriteria(Run.class).createAlias("runPositions", "position").createAlias("position.container", "container").createAlias("container.partitions", "partition").createAlias("partition.pool", "pool").createAlias("pool.poolElements", "element").createAlias("element.aliquot", "aliquot").createAlias("aliquot.parentLibrary", "library").createAlias("library.parentSample", "sample").createAlias("sample.parentProject", "project").setProjection(Projections.distinct(Projections.projectionList().add(Projections.property("id")).add(Projections.property("project.shortName")).add(Projections.property("project.name")))).add(Restrictions.in("id", runs.stream().map(Run::getId).toArray())).list();
    for (Run run : runs) {
        run.setProjectsLabel(results.stream().filter(arr -> ((Long) arr[0]).longValue() == run.getId()).map(arr -> (String) (arr[1] == null ? arr[2] : arr[1])).collect(Collectors.joining(", ")));
    }
    return runs;
}
Also used : JoinType(org.hibernate.sql.JoinType) java.util(java.util) RunStore(uk.ac.bbsrc.tgac.miso.persistence.RunStore) Criteria(org.hibernate.Criteria) PaginationFilter(uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter) SessionFactory(org.hibernate.SessionFactory) SQLQuery(org.hibernate.SQLQuery) Session(org.hibernate.Session) Autowired(org.springframework.beans.factory.annotation.Autowired) HealthType(uk.ac.bbsrc.tgac.miso.core.data.type.HealthType) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) DbUtils(uk.ac.bbsrc.tgac.miso.persistence.util.DbUtils) Consumer(java.util.function.Consumer) Run(uk.ac.bbsrc.tgac.miso.core.data.Run) LimsUtils(uk.ac.bbsrc.tgac.miso.core.util.LimsUtils) PlatformType(uk.ac.bbsrc.tgac.miso.core.data.type.PlatformType) DateType(uk.ac.bbsrc.tgac.miso.core.util.DateType) Repository(org.springframework.stereotype.Repository) LongType(org.hibernate.type.LongType) org.hibernate.criterion(org.hibernate.criterion) Transactional(org.springframework.transaction.annotation.Transactional) Run(uk.ac.bbsrc.tgac.miso.core.data.Run)

Example 2 with PaginationFilter

use of uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter in project miso-lims by miso-lims.

the class JQueryDataTableBackend method get.

public DataTablesResponseDto<Dto> get(HttpServletRequest request, AdvancedSearchParser advancedSearchParser, PaginationFilter... filters) throws IOException {
    if (request.getParameterMap().size() > 0) {
        long numItems = getSource().count(filters);
        // get request params from DataTables
        Integer iDisplayStart = Integer.parseInt(request.getParameter("iDisplayStart"));
        Integer iDisplayLength = Integer.parseInt(request.getParameter("iDisplayLength"));
        String sSearch = request.getParameter("sSearch");
        String sSortDir = request.getParameter("sSortDir_0");
        String sortColIndex = request.getParameter("iSortCol_0");
        String sortCol = request.getParameter("mDataProp_" + sortColIndex);
        // get requested subset of item
        Long numMatches;
        DataTablesResponseDto<Dto> dtResponse = new DataTablesResponseDto<>();
        List<PaginationFilter> additionalFilters = new ArrayList<>(Arrays.asList(filters));
        StringWriter errorBuffer = new StringWriter();
        Consumer<String> errorHandler = message -> {
            if (errorBuffer.getBuffer().length() > 0) {
                errorBuffer.append("<br/>");
            }
            try {
                StringEscapeUtils.escapeHtml(errorBuffer, message);
            } catch (IOException e) {
                log.error("Failed to write to string writer.", e);
            }
        };
        if (!isStringEmptyOrNull(sSearch)) {
            additionalFilters.addAll(Arrays.asList(advancedSearchParser.parseQuery(sSearch, SecurityContextHolder.getContext().getAuthentication().getName(), errorHandler)));
            numMatches = getSource().count(additionalFilters.toArray(filters));
        } else {
            numMatches = numItems;
        }
        Collection<Model> models = getSource().list(errorHandler, iDisplayStart, iDisplayLength, "asc".equalsIgnoreCase(sSortDir), sortCol, additionalFilters.toArray(filters));
        List<Dto> dtos = new ArrayList<>();
        for (Model model : models) {
            Dto dto = asDto(model);
            dtos.add(dto);
        }
        dtResponse.setITotalRecords(numItems);
        dtResponse.setITotalDisplayRecords(numMatches);
        dtResponse.setAaData(dtos);
        dtResponse.setSEcho(Long.valueOf(request.getParameter("sEcho")));
        String errorMessage = errorBuffer.toString();
        if (errorMessage.length() > 0) {
            dtResponse.setSError(errorMessage);
        }
        return dtResponse;
    } else {
        throw new RestException("Request must specify DataTables parameters.");
    }
}
Also used : Arrays(java.util.Arrays) Logger(org.slf4j.Logger) PaginationFilter(uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter) AdvancedSearchParser(uk.ac.bbsrc.tgac.miso.webapp.controller.component.AdvancedSearchParser) StringWriter(java.io.StringWriter) Collection(java.util.Collection) DataTablesResponseDto(uk.ac.bbsrc.tgac.miso.dto.DataTablesResponseDto) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) ArrayList(java.util.ArrayList) Consumer(java.util.function.Consumer) List(java.util.List) HttpServletRequest(javax.servlet.http.HttpServletRequest) LimsUtils.isStringEmptyOrNull(uk.ac.bbsrc.tgac.miso.core.util.LimsUtils.isStringEmptyOrNull) PaginatedDataSource(uk.ac.bbsrc.tgac.miso.core.util.PaginatedDataSource) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) StringEscapeUtils(org.apache.commons.lang.StringEscapeUtils) DataTablesResponseDto(uk.ac.bbsrc.tgac.miso.dto.DataTablesResponseDto) ArrayList(java.util.ArrayList) IOException(java.io.IOException) StringWriter(java.io.StringWriter) PaginationFilter(uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter) DataTablesResponseDto(uk.ac.bbsrc.tgac.miso.dto.DataTablesResponseDto)

Example 3 with PaginationFilter

use of uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter in project miso-lims by miso-lims.

the class PoolPickerResponse method populate.

public <T> void populate(PaginatedDataSource<T> source, boolean sortOrder, String sortColumn, Integer limit, WhineyFunction<T, PoolPickerEntry> transform, PaginationFilter... filters) throws IOException {
    Consumer<String> errorHandler = message -> errors.add(message);
    Map<Long, List<PoolPickerEntry>> groupedByPool = source.list(errorHandler, 0, limit, sortOrder, sortColumn, filters).stream().map(WhineyFunction.rethrow(transform)).collect(Collectors.groupingBy(entry -> entry.getPool().getId()));
    items = groupedByPool.values().stream().map(listOfPicks -> {
        List<SequencingOrderCompletionDto> completionsByPool = listOfPicks.stream().flatMap(pick -> pick.getOrders().stream()).collect(Collectors.toList());
        PoolDto pool = listOfPicks.get(0).getPool();
        return new PoolPickerEntry(pool, completionsByPool);
    }).collect(Collectors.toList());
    numMatches = source.count(filters);
}
Also used : Consumer(java.util.function.Consumer) List(java.util.List) SequencingOrderCompletionDto(uk.ac.bbsrc.tgac.miso.dto.SequencingOrderCompletionDto) PaginationFilter(uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter) PoolDto(uk.ac.bbsrc.tgac.miso.dto.PoolDto) WhineyFunction(uk.ac.bbsrc.tgac.miso.core.util.WhineyFunction) Map(java.util.Map) IOException(java.io.IOException) PaginatedDataSource(uk.ac.bbsrc.tgac.miso.core.util.PaginatedDataSource) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) SequencingOrderCompletionDto(uk.ac.bbsrc.tgac.miso.dto.SequencingOrderCompletionDto) PoolDto(uk.ac.bbsrc.tgac.miso.dto.PoolDto) List(java.util.List) ArrayList(java.util.ArrayList)

Example 4 with PaginationFilter

use of uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter in project miso-lims by miso-lims.

the class HibernatePaginatedDataSource method count.

@Override
public default long count(Consumer<String> errorHandler, PaginationFilter... filters) throws IOException {
    if (filters.length == 0) {
        // try a quicker approach
        Table tableAnnotation = getRealClass().getAnnotation(Table.class);
        if (tableAnnotation != null) {
            Query query = currentSession().createSQLQuery("SELECT COUNT(*) FROM " + tableAnnotation.name());
            return ((BigInteger) query.uniqueResult()).longValueExact();
        }
    }
    Criteria criteria = createPaginationCriteria();
    for (PaginationFilter filter : filters) {
        filter.apply(this, criteria, errorHandler);
    }
    criteria.setProjection(Projections.countDistinct("id"));
    return (Long) criteria.uniqueResult();
}
Also used : Table(javax.persistence.Table) Query(org.hibernate.Query) PaginationFilter(uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter) BigInteger(java.math.BigInteger) Criteria(org.hibernate.Criteria)

Example 5 with PaginationFilter

use of uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter in project miso-lims by miso-lims.

the class HibernatePaginatedDataSource method list.

@Override
public default List<T> list(Consumer<String> errorHandler, int offset, int limit, boolean sortDir, String sortCol, PaginationFilter... filters) throws IOException {
    if (offset < 0 || limit < 0)
        throw new IOException("Limit and Offset must not be less than zero");
    String sortProperty = propertyForSortColumn(sortCol);
    Order primaryOrder = null;
    if (sortProperty != null && !"id".equals(sortProperty)) {
        primaryOrder = sortDir ? Order.asc(sortProperty) : Order.desc(sortProperty);
    }
    Criteria idCriteria = null;
    if (filters.length == 0 && (sortProperty == null || !sortProperty.contains("."))) {
        // Faster method
        ProjectionList projections = Projections.projectionList().add(Projections.property("id"));
        if (primaryOrder != null) {
            projections.add(Projections.property(sortProperty));
        }
        idCriteria = currentSession().createCriteria(getRealClass()).setProjection(projections);
    } else {
        // We need to keep both the id column and the sort column in the result set for the database to provide us with sorted, duplicate-free
        // results. We will throw the sort property out later.
        ProjectionList projections = Projections.projectionList().add(Projections.groupProperty("id"));
        if (primaryOrder != null) {
            projections.add(Projections.groupProperty(sortProperty));
        }
        idCriteria = createPaginationCriteria().setProjection(projections);
    }
    Order idOrder = null;
    if (primaryOrder != null) {
        idCriteria.addOrder(primaryOrder);
        idOrder = Order.asc("id");
    } else {
        idOrder = sortDir ? Order.asc("id") : Order.desc("id");
    }
    // Always add second sort by IDs to ensure consistent order between pages (primary sort may not be deterministic)
    idCriteria.addOrder(idOrder);
    for (PaginationFilter filter : filters) {
        filter.apply(this, idCriteria, errorHandler);
    }
    idCriteria.setFirstResult(offset);
    if (limit > 0) {
        idCriteria.setMaxResults(limit);
    }
    // IDs are usually Longs, but could be composite ID classes, or something else
    List<Object> ids;
    if (primaryOrder == null) {
        @SuppressWarnings("unchecked") List<Object> idResults = idCriteria.list();
        ids = idResults;
    } else {
        @SuppressWarnings("unchecked") List<Object[]> idResults = idCriteria.list();
        ids = idResults.stream().map(x -> x[0]).collect(Collectors.toList());
    }
    if (ids.isEmpty()) {
        return Collections.emptyList();
    }
    // We do this in two steps to make a smaller query that that the database can optimise
    Criteria criteria = createPaginationCriteria();
    if (primaryOrder != null) {
        criteria.addOrder(primaryOrder);
    }
    criteria.addOrder(idOrder);
    criteria.add(Restrictions.in("id", ids));
    @SuppressWarnings("unchecked") List<T> records = criteria.list();
    return records;
}
Also used : Order(org.hibernate.criterion.Order) PaginationFilter(uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter) IOException(java.io.IOException) Criteria(org.hibernate.Criteria) ProjectionList(org.hibernate.criterion.ProjectionList)

Aggregations

PaginationFilter (uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter)5 IOException (java.io.IOException)4 Consumer (java.util.function.Consumer)3 Criteria (org.hibernate.Criteria)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 PaginatedDataSource (uk.ac.bbsrc.tgac.miso.core.util.PaginatedDataSource)2 StringWriter (java.io.StringWriter)1 BigInteger (java.math.BigInteger)1 java.util (java.util)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 Map (java.util.Map)1 Table (javax.persistence.Table)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 StringEscapeUtils (org.apache.commons.lang.StringEscapeUtils)1 Query (org.hibernate.Query)1 SQLQuery (org.hibernate.SQLQuery)1 Session (org.hibernate.Session)1