Example usage for javax.persistence EntityManager createNamedQuery

List of usage examples for javax.persistence EntityManager createNamedQuery

Introduction

In this page you can find the example usage for javax.persistence EntityManager createNamedQuery.

Prototype

public Query createNamedQuery(String name);

Source Link

Document

Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).

Usage

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Find all running jobs on this service and set them to RESET or CANCELED.
 * //  w  w w .ja  va  2 s. com
 * @param serviceType
 *          the service type
 * @param baseUrl
 *          the base url
 * @throws ServiceRegistryException
 *           if there is a problem communicating with the jobs database
 */
private void cleanRunningJobs(String serviceType, String baseUrl) throws ServiceRegistryException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        Query query = em.createNamedQuery("Job.processinghost.status");
        query.setParameter("status", Status.RUNNING);
        query.setParameter("host", baseUrl);
        query.setParameter("serviceType", serviceType);
        @SuppressWarnings("unchecked")
        List<JobJpaImpl> unregisteredJobs = query.getResultList();
        for (JobJpaImpl job : unregisteredJobs) {
            if (job.isDispatchable()) {
                em.refresh(job);
                // If this job has already been treated
                if (Status.CANCELED.equals(job.getStatus()) || Status.RESTART.equals(job.getStatus()))
                    continue;
                if (job.getRootJob() != null && Status.PAUSED.equals(job.getRootJob().getStatus())) {
                    JobJpaImpl rootJob = job.getRootJob();
                    cancelAllChildren(rootJob, em);
                    rootJob.setStatus(Status.RESTART);
                    rootJob.setOperation(START_OPERATION);
                    em.merge(rootJob);
                    continue;
                }

                logger.info("Marking child jobs from job {} as canceled", job);
                cancelAllChildren(job, em);
                logger.info("Rescheduling lost job {}", job);
                job.setStatus(Status.RESTART);
                job.setProcessorServiceRegistration(null);
            } else {
                logger.info("Marking lost job {} as failed", job);
                job.setStatus(Status.FAILED);
            }
            em.merge(job);
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Gets the services in WARNING state triggered by this job
 * /*from   w w w  . j a v a  2s .c om*/
 * @param job
 *          the given job to get the related services
 * @return a list of services triggered by the job
 * @throws IllegalArgumentException
 *           if the given job was null
 * @throws ServiceRegistryException
 *           if the there was a problem with the query
 */
private List<ServiceRegistrationJpaImpl> getRelatedWarningServices(JobJpaImpl job)
        throws IllegalArgumentException, ServiceRegistryException {
    if (job == null)
        throw new IllegalArgumentException("job must not be null!");

    Query query = null;
    EntityManager em = null;
    logger.debug("Try to get the services in WARNING state triggered by this job {} failed",
            job.getSignature());
    try {
        em = emf.createEntityManager();
        // TODO: modify the query to avoid to go through the list here
        query = em.createNamedQuery("ServiceRegistration.relatedservices.warning");
        query.setParameter("serviceType", job.getJobType());

        List<ServiceRegistrationJpaImpl> jpaServices = new ArrayList<ServiceRegistrationJpaImpl>();

        @SuppressWarnings("unchecked")
        List<ServiceRegistrationJpaImpl> jobResults = query.getResultList();
        for (ServiceRegistrationJpaImpl relatedService : jobResults) {
            if (relatedService.getWarningStateTrigger() == job.getSignature()) {
                jpaServices.add(relatedService);
            }
        }
        return jpaServices;
    } catch (NoResultException e) {
        return null;
    } catch (Exception e) {
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Gets the services in WARNING or ERROR state triggered by this job
 * /*w w  w .  j  a  va  2 s.com*/
 * @param job
 *          the given job to get the related services
 * @return a list of services triggered by the job
 * @throws IllegalArgumentException
 *           if the given job was null
 * @throws ServiceRegistryException
 *           if the there was a problem with the query
 */
private List<ServiceRegistrationJpaImpl> getRelatedWarningErrorServices(JobJpaImpl job)
        throws ServiceRegistryException {
    if (job == null)
        throw new IllegalArgumentException("job must not be null!");

    Query query = null;
    EntityManager em = null;
    logger.debug("Try to get the services in WARNING or ERROR state triggered by this job {} failed",
            job.getSignature());
    try {
        em = emf.createEntityManager();

        // TODO: modify the query to avoid to go through the list here
        query = em.createNamedQuery("ServiceRegistration.relatedservices.warning_error");
        query.setParameter("serviceType", job.getJobType());

        List<ServiceRegistrationJpaImpl> jpaServices = new ArrayList<ServiceRegistrationJpaImpl>();

        @SuppressWarnings("unchecked")
        List<ServiceRegistrationJpaImpl> serviceResults = query.getResultList();
        for (ServiceRegistrationJpaImpl relatedService : serviceResults) {
            if (relatedService.getServiceState() == WARNING
                    && relatedService.getWarningStateTrigger() == job.getSignature()) {
                jpaServices.add(relatedService);
            }

            if (relatedService.getServiceState() == ERROR
                    && relatedService.getErrorStateTrigger() == job.getSignature()) {
                jpaServices.add(relatedService);
            }
        }
        return jpaServices;
    } catch (NoResultException e) {
        return null;
    } catch (Exception e) {
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.meveo.service.billing.impl.InvoiceService.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void createAgregatesAndInvoice(BillingAccount billingAccount, Long billingRunId, User currentUser)
        throws BusinessException, Exception {
    log.debug("createAgregatesAndInvoice tx status={}", txReg.getTransactionStatus());
    EntityManager em = getEntityManager();
    BillingRun billingRun = em.find(BillingRun.class, billingRunId);
    em.refresh(billingRun);/*from   ww  w. j  a v a 2 s . com*/
    try {
        billingAccount = em.find(billingAccount.getClass(), billingAccount.getId());
        em.refresh(billingAccount);
        currentUser = em.find(currentUser.getClass(), currentUser.getId());
        em.refresh(currentUser);

        Long startDate = System.currentTimeMillis();
        BillingCycle billingCycle = billingRun.getBillingCycle();
        if (billingCycle == null) {
            billingCycle = billingAccount.getBillingCycle();
        }
        if (billingCycle == null) {
            throw new BusinessException("Cant find the billing cycle");
        }
        InvoiceType invoiceType = billingCycle.getInvoiceType();
        if (invoiceType == null) {
            invoiceType = invoiceTypeService.getDefaultCommertial(currentUser);
        }
        Invoice invoice = new Invoice();
        invoice.setInvoiceType(invoiceType);
        invoice.setBillingAccount(billingAccount);
        invoice.setBillingRun(billingRun);
        invoice.setAuditable(billingRun.getAuditable());
        invoice.setProvider(billingRun.getProvider());
        // ticket 680
        Date invoiceDate = billingRun.getInvoiceDate();
        invoice.setInvoiceDate(invoiceDate);

        Integer delay = billingCycle.getDueDateDelay();
        Date dueDate = invoiceDate;
        if (delay != null) {
            dueDate = DateUtils.addDaysToDate(invoiceDate, delay);
        }
        invoice.setDueDate(dueDate);

        PaymentMethodEnum paymentMethod = billingAccount.getPaymentMethod();
        if (paymentMethod == null) {
            paymentMethod = billingAccount.getCustomerAccount().getPaymentMethod();
        }
        invoice.setPaymentMethod(paymentMethod);
        invoice.setProvider(billingRun.getProvider());

        em.persist(invoice);

        // create(invoice, currentUser, currentUser.getProvider());
        log.debug("created invoice entity with id={},  tx status={}, em open={}", invoice.getId(),
                txReg.getTransactionStatus(), em.isOpen());
        ratedTransactionService.createInvoiceAndAgregates(billingAccount, invoice,
                billingRun.getLastTransactionDate(), currentUser);
        log.debug("created aggregates tx status={}, em open={}", txReg.getTransactionStatus(), em.isOpen());
        em.joinTransaction();

        if (billingRun.getProvider().isDisplayFreeTransacInInvoice()) {
            em.createNamedQuery("RatedTransaction.updateInvoicedDisplayFree")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();
        } else {
            em.createNamedQuery("RatedTransaction.updateInvoiced")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();

        }

        StringBuffer num1 = new StringBuffer("000000000");
        num1.append(invoice.getId() + "");
        String invoiceNumber = num1.substring(num1.length() - 9);
        int key = 0;

        for (int i = 0; i < invoiceNumber.length(); i++) {
            key = key + Integer.parseInt(invoiceNumber.substring(i, i + 1));
        }

        invoice.setTemporaryInvoiceNumber(invoiceNumber + "-" + key % 10);
        // getEntityManager().merge(invoice);
        Long endDate = System.currentTimeMillis();

        log.info("createAgregatesAndInvoice BR_ID=" + billingRun.getId() + ", BA_ID=" + billingAccount.getId()
                + ", Time en ms=" + (endDate - startDate));
    } catch (Exception e) {
        log.error("Error for BA=" + billingAccount.getCode() + " : ", e);

        RejectedBillingAccount rejectedBA = new RejectedBillingAccount(billingAccount, billingRun,
                e.getMessage());
        rejectedBillingAccountService.create(rejectedBA, currentUser);
    }
}

From source file:org.apache.oozie.executor.jpa.WorkflowsJobGetJPAExecutor.java

@SuppressWarnings("unchecked")
@Override/*from w w w  .  j  ava  2 s. c o  m*/
public WorkflowsInfo execute(EntityManager em) throws JPAExecutorException {
    List<String> orArray = new ArrayList<String>();
    List<String> colArray = new ArrayList<String>();
    List<Object> valArray = new ArrayList<Object>();
    StringBuilder sb = new StringBuilder("");
    String orderBy = DEFAULT_ORDER_BY;
    boolean isStatus = false;
    boolean isAppName = false;
    boolean isUser = false;
    boolean isEnabled = false;
    boolean isId = false;
    int index = 0;
    for (Map.Entry<String, List<String>> entry : filter.entrySet()) {
        String colName = null;
        String colVar = null;
        if (entry.getKey().equals(OozieClient.FILTER_GROUP)) {
            XLog.getLog(getClass()).warn("Filter by 'group' is not supported anymore");
        } else {
            if (entry.getKey().equals(OozieClient.FILTER_STATUS)) {
                List<String> values = filter.get(OozieClient.FILTER_STATUS);
                colName = "status";
                for (int i = 0; i < values.size(); i++) {
                    colVar = "status";
                    colVar = colVar + index;
                    if (!isEnabled && !isStatus) {
                        sb.append(seletStr).append(" where w.statusStr IN (:status" + index);
                        isStatus = true;
                        isEnabled = true;
                    } else {
                        if (isEnabled && !isStatus) {
                            sb.append(" and w.statusStr IN (:status" + index);
                            isStatus = true;
                        } else {
                            if (isStatus) {
                                sb.append(", :status" + index);
                            }
                        }
                    }
                    if (i == values.size() - 1) {
                        sb.append(")");
                    }
                    index++;
                    valArray.add(values.get(i));
                    orArray.add(colName);
                    colArray.add(colVar);
                }
            } else {
                if (entry.getKey().equals(OozieClient.FILTER_NAME)) {
                    List<String> values = filter.get(OozieClient.FILTER_NAME);
                    colName = "appName";
                    for (int i = 0; i < values.size(); i++) {
                        colVar = "appName";
                        colVar = colVar + index;
                        if (!isEnabled && !isAppName) {
                            sb.append(seletStr).append(" where w.appName IN (:appName" + index);
                            isAppName = true;
                            isEnabled = true;
                        } else {
                            if (isEnabled && !isAppName) {
                                sb.append(" and w.appName IN (:appName" + index);
                                isAppName = true;
                            } else {
                                if (isAppName) {
                                    sb.append(", :appName" + index);
                                }
                            }
                        }
                        if (i == values.size() - 1) {
                            sb.append(")");
                        }
                        index++;
                        valArray.add(values.get(i));
                        orArray.add(colName);
                        colArray.add(colVar);
                    }
                } else {
                    if (entry.getKey().equals(OozieClient.FILTER_USER)) {
                        List<String> values = filter.get(OozieClient.FILTER_USER);
                        colName = "user";
                        for (int i = 0; i < values.size(); i++) {
                            colVar = "user";
                            colVar = colVar + index;
                            if (!isEnabled && !isUser) {
                                sb.append(seletStr).append(" where w.user IN (:user" + index);
                                isUser = true;
                                isEnabled = true;
                            } else {
                                if (isEnabled && !isUser) {
                                    sb.append(" and w.user IN (:user" + index);
                                    isUser = true;
                                } else {
                                    if (isUser) {
                                        sb.append(", :user" + index);
                                    }
                                }
                            }
                            if (i == values.size() - 1) {
                                sb.append(")");
                            }
                            index++;
                            valArray.add(values.get(i));
                            orArray.add(colName);
                            colArray.add(colVar);
                        }
                    }
                }
                if (entry.getKey().equals(OozieClient.FILTER_ID)) {
                    List<String> values = filter.get(OozieClient.FILTER_ID);
                    colName = "id";
                    for (int i = 0; i < values.size(); i++) {
                        colVar = "id";
                        colVar = colVar + index;
                        if (!isEnabled && !isId) {
                            sb.append(seletStr).append(" where w.id IN (:id" + index);
                            isId = true;
                            isEnabled = true;
                        } else {
                            if (isEnabled && !isId) {
                                sb.append(" and w.id IN (:id" + index);
                                isId = true;
                            } else {
                                if (isId) {
                                    sb.append(", :id" + index);
                                }
                            }
                        }
                        if (i == values.size() - 1) {
                            sb.append(")");
                        }
                        index++;
                        valArray.add(values.get(i));
                        orArray.add(colName);
                        colArray.add(colVar);
                    }
                } else if (entry.getKey().equalsIgnoreCase(OozieClient.FILTER_CREATED_TIME_START)) {
                    List<String> values = filter.get(OozieClient.FILTER_CREATED_TIME_START);
                    colName = "createdTimestampStart";
                    if (values.size() > 1) {
                        throw new JPAExecutorException(ErrorCode.E0302,
                                "cannot specify multiple startcreatedtime");
                    }
                    colVar = colName;
                    colVar = colVar + index;
                    if (!isEnabled) {
                        sb.append(seletStr).append(" where w.createdTimestamp >= :" + colVar);
                        isEnabled = true;
                    } else {
                        sb.append(" and w.createdTimestamp >= :" + colVar);
                    }
                    index++;
                    Date createdTime = null;
                    try {
                        createdTime = parseCreatedTimeString(values.get(0));
                    } catch (Exception e) {
                        throw new JPAExecutorException(ErrorCode.E0302, e.getMessage());
                    }
                    Timestamp createdTimeStamp = new Timestamp(createdTime.getTime());
                    valArray.add(createdTimeStamp);
                    orArray.add(colName);
                    colArray.add(colVar);

                } else if (entry.getKey().equalsIgnoreCase(OozieClient.FILTER_CREATED_TIME_END)) {
                    List<String> values = filter.get(OozieClient.FILTER_CREATED_TIME_END);
                    colName = "createdTimestampEnd";
                    if (values.size() > 1) {
                        throw new JPAExecutorException(ErrorCode.E0302,
                                "cannot specify multiple endcreatedtime");
                    }
                    colVar = colName;
                    colVar = colVar + index;
                    if (!isEnabled) {
                        sb.append(seletStr).append(" where w.createdTimestamp <= :" + colVar);
                        isEnabled = true;
                    } else {
                        sb.append(" and w.createdTimestamp <= :" + colVar);
                    }
                    index++;
                    Date createdTime = null;
                    try {
                        createdTime = parseCreatedTimeString(values.get(0));
                    } catch (Exception e) {
                        throw new JPAExecutorException(ErrorCode.E0302, e.getMessage());
                    }
                    Timestamp createdTimeStamp = new Timestamp(createdTime.getTime());
                    valArray.add(createdTimeStamp);
                    orArray.add(colName);
                    colArray.add(colVar);
                }
                // w.id = text || w.appName.contains(text) || w.user.contains(text)
                else if (entry.getKey().equalsIgnoreCase(OozieClient.FILTER_TEXT)) {
                    StoreStatusFilter.filterJobsUsingText(filter, sb, isEnabled, seletStr, valArray, orArray,
                            colArray);
                    isEnabled = true;
                }
            }
        }
    }

    orderBy = StoreStatusFilter.getSortBy(filter, orderBy);
    int realLen = 0;

    Query q = null;
    Query qTotal = null;
    if (orArray.size() == 0 && orderBy.equals(DEFAULT_ORDER_BY)) {
        q = em.createNamedQuery("GET_WORKFLOWS_COLUMNS");
        q.setFirstResult(start - 1);
        q.setMaxResults(len);
        qTotal = em.createNamedQuery("GET_WORKFLOWS_COUNT");
    } else {
        sb = sb.toString().trim().length() == 0 ? sb.append(seletStr) : sb;
        String sbTotal = sb.toString();
        sb.append(orderBy);
        q = em.createQuery(sb.toString());
        q.setFirstResult(start - 1);
        q.setMaxResults(len);
        qTotal = em.createQuery(sbTotal.replace(seletStr, countStr));

        for (int i = 0; i < orArray.size(); i++) {
            q.setParameter(colArray.get(i), valArray.get(i));
            qTotal.setParameter(colArray.get(i), valArray.get(i));
        }
    }

    OpenJPAQuery kq = OpenJPAPersistence.cast(q);
    JDBCFetchPlan fetch = (JDBCFetchPlan) kq.getFetchPlan();
    fetch.setFetchBatchSize(20);
    fetch.setResultSetType(ResultSetType.SCROLL_INSENSITIVE);
    fetch.setFetchDirection(FetchDirection.FORWARD);
    fetch.setLRSSizeAlgorithm(LRSSizeAlgorithm.LAST);
    List<?> resultList = q.getResultList();
    List<Object[]> objectArrList = (List<Object[]>) resultList;
    List<WorkflowJobBean> wfBeansList = new ArrayList<WorkflowJobBean>();

    for (Object[] arr : objectArrList) {
        WorkflowJobBean ww = getBeanForWorkflowFromArray(arr);
        wfBeansList.add(ww);
    }

    realLen = ((Long) qTotal.getSingleResult()).intValue();

    return new WorkflowsInfo(wfBeansList, start, len, realLen);
}