Example usage for javax.persistence.criteria CriteriaBuilder desc

List of usage examples for javax.persistence.criteria CriteriaBuilder desc

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder desc.

Prototype

Order desc(Expression<?> x);

Source Link

Document

Create an ordering by the descending value of the expression.

Usage

From source file:org.sparkcommerce.core.catalog.dao.ProductDaoImpl.java

protected void attachOrderBy(ProductSearchCriteria searchCriteria, From<?, ? extends Product> product,
        Path<? extends Sku> sku, CriteriaQuery<?> criteria) {
    if (StringUtils.isNotBlank(searchCriteria.getSortQuery())) {
        CriteriaBuilder builder = em.getCriteriaBuilder();

        List<Order> sorts = new ArrayList<Order>();

        String sortQueries = searchCriteria.getSortQuery();
        for (String sortQuery : sortQueries.split(",")) {
            String[] sort = sortQuery.split(" ");
            if (sort.length == 2) {
                String key = sort[0];
                boolean asc = sort[1].toLowerCase().contains("asc");

                // Determine whether we should use the product path or the sku path
                Path<?> pathToUse;
                if (key.contains("defaultSku.")) {
                    pathToUse = sku;// w  w w. j a v  a 2 s . c  o  m
                    key = key.substring("defaultSku.".length());
                } else if (key.contains("product.")) {
                    pathToUse = product;
                    key = key.substring("product.".length());
                } else {
                    // We don't know which path this facet is built on - resolves previous bug that attempted
                    // to attach search facet to any query parameter
                    continue;
                }

                if (asc) {
                    sorts.add(builder.asc(pathToUse.get(key)));
                } else {
                    sorts.add(builder.desc(pathToUse.get(key)));
                }
            }
        }

        criteria.orderBy(sorts.toArray(new Order[sorts.size()]));
    }
}

From source file:ru.codeinside.adm.AdminServiceImpl.java

@Override
public List<InfoSystem> queryInfoSystems(boolean source, String[] sort, boolean[] asc, int start, int count) {
    final CriteriaBuilder c = em.getCriteriaBuilder();
    final CriteriaQuery<InfoSystem> query = c.createQuery(InfoSystem.class);
    final Root<InfoSystem> system = query.from(InfoSystem.class);
    if (source) {
        query.where(c.equal(system.get(InfoSystem_.source), true));
    }/*from w w w.ja v  a 2 s.c o  m*/
    query.select(system);
    if (sort != null) {
        final Order[] orders = new Order[sort.length];
        for (int i = 0; i < sort.length; i++) {
            final Path<String> path = system.get(sort[i]);
            orders[i] = asc[i] ? c.asc(path) : c.desc(path);
        }
        query.orderBy(orders);
    }
    return chunk(start, count, query);
}

From source file:sf.net.experimaestro.scheduler.Scheduler.java

/**
 * Initialise the task manager//from  w w w .  ja  v a 2s.c o m
 *
 * @param baseDirectory The directory where the XPM database will be stored
 */
public Scheduler(File baseDirectory) throws IOException {
    if (INSTANCE != null) {
        throw new XPMRuntimeException("Only one scheduler instance should be created");
    }

    INSTANCE = this;

    // Initialise the database
    LOGGER.info("Initialising database in directory %s", baseDirectory);
    HashMap<String, Object> properties = new HashMap<>();
    properties.put("hibernate.connection.url",
            format("jdbc:hsqldb:file:%s/xpm;shutdown=true;hsqldb.tx=mvcc", baseDirectory));
    properties.put("hibernate.connection.username", "");
    properties.put("hibernate.connection.password", "");

    /* From HSQLDB http://hsqldb.org/doc/guide/sessions-chapt.html#snc_tx_mvcc
            
    In MVCC mode
    - locks are at the row level
    - no shared (i.e. read) locks
    - in TRANSACTION_READ_COMMITTED mode: if a session wants to read/write a row that was written by another one => wait
    - in TRANSACTION_REPEATABLE_READ: if a session wants to write the same row than another one => exception
    */
    properties.put("hibernate.connection.isolation", String.valueOf(Connection.TRANSACTION_READ_COMMITTED));

    ArrayList<Class<?>> loadedClasses = new ArrayList<>();
    ServiceLoader<PersistentClassesAdder> services = ServiceLoader.load(PersistentClassesAdder.class);
    for (PersistentClassesAdder service : services) {
        service.add(loadedClasses);
    }

    properties.put(org.hibernate.jpa.AvailableSettings.LOADED_CLASSES, loadedClasses);

    entityManagerFactory = Persistence.createEntityManagerFactory("net.bpiwowar.experimaestro", properties);

    // Add a shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread(Scheduler.this::close));

    // Create reused criteria queries
    CriteriaBuilder builder = entityManagerFactory.getCriteriaBuilder();
    readyJobsQuery = builder.createQuery(Long.TYPE);
    Root<Job> root = readyJobsQuery.from(Job.class);
    readyJobsQuery.orderBy(builder.desc(root.get("priority")));
    readyJobsQuery.where(root.get("state").in(ResourceState.READY));
    readyJobsQuery.select(root.get(Resource_.resourceID));

    // Initialise the running resources so that they can retrieve their state
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    TypedQuery<Resource> query = entityManager.createQuery("from resources r where r.state = :state",
            Resource.class);
    query.setParameter("state", ResourceState.RUNNING);
    for (Resource resource : query.getResultList()) {
        LOGGER.info("Job %s is running: starting a watcher", resource);
        Job job = (Job) resource;
        if (job.process != null) {
            job.process.init(job);
        } else {
            Transaction.run(em -> {
                // Set the job state to ERROR (and update the state in case it was finished)
                // The job should take care of setting a new process if the job is still running
                Job _job = em.find(Job.class, job.getId());
                _job.setState(ResourceState.ERROR);
                _job.updateStatus();
                LOGGER.error("No process attached to a running job. New status is: %s", _job.getState());
            });
        }
        resource.updateStatus();
    }

    // Start the thread that notify dependencies
    LOGGER.info("Starting the notifier thread");
    notifier = new Notifier();
    notifier.start();
    runningThreadsCounter.add();

    // Start the thread that notify dependencies
    LOGGER.info("Starting the messager thread");
    messengerThread = new MessengerThread();
    messengerThread.start();
    runningThreadsCounter.add();

    // Start the thread that start the jobs
    LOGGER.info("Starting the job runner thread");
    readyJobSemaphore.setValue(true);
    runner = new JobRunner("JobRunner");
    runner.start();
    runningThreadsCounter.add();

    executorService = Executors.newFixedThreadPool(1);

    LOGGER.info("Done - ready status work now");
}