Search in sources :

Example 96 with EntityManager

use of com.haulmont.cuba.core.EntityManager in project cuba by cuba-platform.

the class Emailer method markAsNonSent.

protected void markAsNonSent(SendingMessage sendingMessage) {
    try (Transaction tx = persistence.createTransaction()) {
        EntityManager em = persistence.getEntityManager();
        SendingMessage msg = em.merge(sendingMessage);
        msg.setStatus(SendingStatus.NOTSENT);
        msg.setAttemptsMade(msg.getAttemptsMade() + 1);
        tx.commit();
    } catch (Exception e) {
        log.error("Error marking message to '{}' as not sent", sendingMessage.getAddress(), e);
    }
}
Also used : EntityManager(com.haulmont.cuba.core.EntityManager) Transaction(com.haulmont.cuba.core.Transaction) SendingMessage(com.haulmont.cuba.core.entity.SendingMessage) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) SMTPAddressFailedException(com.sun.mail.smtp.SMTPAddressFailedException) AddressException(javax.mail.internet.AddressException) MailSendException(org.springframework.mail.MailSendException)

Example 97 with EntityManager

use of com.haulmont.cuba.core.EntityManager in project cuba by cuba-platform.

the class Emailer method loadEmailsToSend.

protected List<SendingMessage> loadEmailsToSend() {
    Date sendTimeoutTime = DateUtils.addSeconds(timeSource.currentTimestamp(), -config.getSendingTimeoutSec());
    List<SendingMessage> emailsToSend = new ArrayList<>();
    try (Transaction tx = persistence.createTransaction()) {
        EntityManager em = persistence.getEntityManager();
        TypedQuery<SendingMessage> query = em.createQuery("select sm from sys$SendingMessage sm" + " where sm.status = :statusQueue or (sm.status = :statusSending and sm.updateTs < :time)" + " order by sm.createTs", SendingMessage.class);
        query.setParameter("statusQueue", SendingStatus.QUEUE.getId());
        query.setParameter("time", sendTimeoutTime);
        query.setParameter("statusSending", SendingStatus.SENDING.getId());
        View view = metadata.getViewRepository().getView(SendingMessage.class, "sendingMessage.loadFromQueue");
        // because SendingAttachment.content has FetchType.LAZY
        view.setLoadPartialEntities(true);
        query.setView(view);
        query.setMaxResults(config.getMessageQueueCapacity());
        List<SendingMessage> resList = query.getResultList();
        for (SendingMessage msg : resList) {
            if (shouldMarkNotSent(msg)) {
                msg.setStatus(SendingStatus.NOTSENT);
            } else {
                msg.setStatus(SendingStatus.SENDING);
                emailsToSend.add(msg);
            }
        }
        tx.commit();
    }
    for (SendingMessage message : emailsToSend) {
        loadBodyAndAttachments(message);
    }
    return emailsToSend;
}
Also used : EntityManager(com.haulmont.cuba.core.EntityManager) Transaction(com.haulmont.cuba.core.Transaction) SendingMessage(com.haulmont.cuba.core.entity.SendingMessage)

Example 98 with EntityManager

use of com.haulmont.cuba.core.EntityManager in project cuba by cuba-platform.

the class FoldersServiceBean method importFolder.

@Override
public Folder importFolder(Folder parentFolder, byte[] bytes) throws IOException {
    if (!security.isEntityOpPermitted(Folder.class, EntityOp.CREATE)) {
        throw new AccessDeniedException(PermissionType.ENTITY_OP, Folder.class.getSimpleName());
    }
    Folder folder = null;
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    ZipArchiveInputStream archiveReader;
    archiveReader = new ZipArchiveInputStream(byteArrayInputStream);
    ZipArchiveEntry archiveEntry;
    while (((archiveEntry = archiveReader.getNextZipEntry()) != null) && (folder == null)) {
        if (archiveEntry.getName().equals("folder.xml")) {
            String xml = new String(IOUtils.toByteArray(archiveReader), StandardCharsets.UTF_8);
            folder = (Folder) createXStream().fromXML(xml);
        }
    }
    byteArrayInputStream.close();
    if (folder != null) {
        checkImportPermissions(folder);
        folder.setParent(parentFolder);
        Transaction tx = persistence.createTransaction();
        try {
            EntityManager em = persistence.getEntityManager();
            em.setSoftDeletion(false);
            Folder existingFolder = em.find(Folder.class, folder.getId());
            if (existingFolder != null) {
                checkImportPermissions(existingFolder);
                folder.setVersion(existingFolder.getVersion());
                folder.setCreateTs(existingFolder.getCreateTs());
                folder.setCreatedBy(existingFolder.getCreatedBy());
            } else {
                User user = userSessionSource.getUserSession().getUser();
                folder.setCreatedBy(user.getLoginLowerCase());
                folder.setCreateTs(timeSource.currentTimestamp());
                folder.setUpdatedBy(null);
                folder.setUpdateTs(null);
                folder.setVersion(0);
            }
            em.merge(folder);
            tx.commit();
        } finally {
            tx.end();
        }
    }
    return folder;
}
Also used : EntityManager(com.haulmont.cuba.core.EntityManager) User(com.haulmont.cuba.security.entity.User) Transaction(com.haulmont.cuba.core.Transaction) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) AppFolder(com.haulmont.cuba.core.entity.AppFolder) SearchFolder(com.haulmont.cuba.security.entity.SearchFolder) Folder(com.haulmont.cuba.core.entity.Folder)

Example 99 with EntityManager

use of com.haulmont.cuba.core.EntityManager in project cuba by cuba-platform.

the class NumberIdWorker method executeScript.

protected Object executeScript(String entityName, String sqlScript) {
    EntityManager em = persistence.getEntityManager(getDataStore(entityName));
    StrTokenizer tokenizer = new StrTokenizer(sqlScript, SequenceSupport.SQL_DELIMITER);
    Object value = null;
    Connection connection = em.getConnection();
    while (tokenizer.hasNext()) {
        String sql = tokenizer.nextToken();
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            try {
                if (statement.execute()) {
                    ResultSet rs = statement.getResultSet();
                    if (rs.next())
                        value = rs.getLong(1);
                }
            } finally {
                DbUtils.closeQuietly(statement);
            }
        } catch (SQLException e) {
            throw new IllegalStateException("Error executing SQL for getting next number", e);
        }
    }
    return value;
}
Also used : EntityManager(com.haulmont.cuba.core.EntityManager) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) StrTokenizer(org.apache.commons.lang.text.StrTokenizer)

Example 100 with EntityManager

use of com.haulmont.cuba.core.EntityManager in project cuba by cuba-platform.

the class DbBasedCoordinator method isLastExecutionFinished.

@Override
public boolean isLastExecutionFinished(ScheduledTask task, long now) {
    EntityManager em = persistence.getEntityManager();
    Query query = em.createQuery("select e.finishTime from sys$ScheduledExecution e where e.task.id = ?1 and e.startTime = ?2");
    query.setParameter(1, task.getId());
    query.setParameter(2, task.getLastStartTime());
    List list = query.getResultList();
    if (list.isEmpty() || list.get(0) == null) {
        // Execution finish was not registered for some reason, so using timeout value or just return false
        boolean result = task.getTimeout() != null && (task.getLastStart() + task.getTimeout() * 1000) <= now;
        if (result)
            log.trace(task + ": considered finished because of timeout");
        else
            log.trace(task + ": not finished and not timed out");
        return result;
    }
    Date date = (Date) list.get(0);
    log.trace("{} : finished at {}", task, date.getTime());
    return true;
}
Also used : EntityManager(com.haulmont.cuba.core.EntityManager) Query(com.haulmont.cuba.core.Query) List(java.util.List) Date(java.util.Date)

Aggregations

EntityManager (com.haulmont.cuba.core.EntityManager)167 Transaction (com.haulmont.cuba.core.Transaction)140 Query (com.haulmont.cuba.core.Query)27 User (com.haulmont.cuba.security.entity.User)27 Test (org.junit.Test)25 View (com.haulmont.cuba.core.global.View)22 MetaClass (com.haulmont.chile.core.model.MetaClass)14 Group (com.haulmont.cuba.security.entity.Group)12 Before (org.junit.Before)11 Entity (com.haulmont.cuba.core.entity.Entity)10 SendingMessage (com.haulmont.cuba.core.entity.SendingMessage)8 UUID (java.util.UUID)7 Nullable (javax.annotation.Nullable)7 TypedQuery (com.haulmont.cuba.core.TypedQuery)6 List (java.util.List)6 MetaProperty (com.haulmont.chile.core.model.MetaProperty)5 Role (com.haulmont.cuba.security.entity.Role)5 UserRole (com.haulmont.cuba.security.entity.UserRole)5 SoftDeleteOneToOneA (com.haulmont.cuba.testmodel.softdelete_one_to_one.SoftDeleteOneToOneA)5 FileDescriptor (com.haulmont.cuba.core.entity.FileDescriptor)4