com.formkiq.core.dao.QueueDaoImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.formkiq.core.dao.QueueDaoImpl.java

Source

/*
 * Copyright (C) 2016 FormKiQ Inc.
 *
 * 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 com.formkiq.core.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.time.DateUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.AliasToBeanResultTransformer;
import org.hibernate.type.PostgresUUIDType;
import org.hibernate.type.StringType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.formkiq.core.domain.QueueMessage;
import com.formkiq.core.domain.type.QueueDTO;
import com.formkiq.core.domain.type.QueueListDTO;
import com.formkiq.core.domain.type.QueueMessageStatus;
import com.formkiq.core.util.DateService;
import com.formkiq.core.util.Strings;

/**
 * QueueDao hibernate implemenation.
 *
 */
@Repository
public class QueueDaoImpl extends AbstractDaoImpl implements QueueDao {

    /** DateService. */
    @Autowired
    private DateService dateservice;

    @SuppressWarnings("resource")
    @Override
    public int delete(final Map<String, String> messageValues) {

        StringBuilder sb = new StringBuilder("delete from queue_messages where ");

        List<String> keys = new ArrayList<>(messageValues.keySet());

        for (int i = 0; i < keys.size(); i++) {

            if (i > 0) {
                sb.append(" and ");
            }

            String key = keys.get(i);
            sb.append(" message #>> '{" + key + "}'=:value" + i);
        }

        Session session = getEntityManager().unwrap(Session.class);

        SQLQuery q = session.createSQLQuery(sb.toString());

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = messageValues.get(key);
            q.setParameter("value" + i, value);
        }

        return q.executeUpdate();
    }

    @SuppressWarnings("resource")
    @Override
    public int delete(final String messageid) {

        String sql = "delete from queue_messages where " + " queue_message_id=:id";

        Session session = getEntityManager().unwrap(Session.class);

        int result = session.createSQLQuery(sql).setParameter("id", UUID.fromString(messageid)).executeUpdate();

        return result;
    }

    @SuppressWarnings("resource")
    @Override
    public int deleteExpiredMessages() {

        Date dayBefore = DateUtils.addDays(this.dateservice.now(), -1);

        String sql = "delete from queue_messages where " + " inserted_date < :date and status=:status";

        Session session = getEntityManager().unwrap(Session.class);

        int result = session.createSQLQuery(sql).setParameter("date", dayBefore)
                .setParameter("status", QueueMessageStatus.TO_BE_DELETED.name()).executeUpdate();

        return result;
    }

    @Override
    public QueueMessage findMessage(final String messageid) {
        return getEntityManager().find(QueueMessage.class, UUID.fromString(messageid));
    }

    @SuppressWarnings({ "unchecked", "resource" })
    @Override
    public QueueListDTO findMessages(final String queue, final String token) {

        int offset = Strings.getOffset(token);
        int max = Strings.getMaxResults(token, DEFAULT_MAX_RESULTS);

        StringBuilder sql = new StringBuilder(
                "select u.queue_message_id as uuid " + ", u.message as message, u.status as status "
                        + " from queue_messages u " + " where queue_id=:queue ");

        sql.append(" OFFSET " + offset + " FETCH FIRST " + (max + 1) + " ROWS ONLY");

        Session session = getEntityManager().unwrap(Session.class);

        List<QueueDTO> list = session.createSQLQuery(sql.toString()).addScalar("uuid", StringType.INSTANCE)
                .addScalar("message", StringType.INSTANCE).addScalar("status", StringType.INSTANCE)
                .setParameter("queue", UUID.fromString(queue), PostgresUUIDType.INSTANCE)
                .setResultTransformer(new AliasToBeanResultTransformer(QueueDTO.class)).list();

        QueueListDTO dto = new QueueListDTO();

        List<QueueDTO> truncate = updatePagination(dto, offset, max, list);
        dto.setMessages(truncate);

        return dto;
    }

    @Override
    public void save(final QueueMessage message) {

        Date now = this.dateservice.now();

        if (message.getInsertedDate() == null) {
            message.setInsertedDate(now);
        }

        if (StringUtils.isEmpty(message.getQueuemessageid())) {
            message.setQueuemessageid(UUID.randomUUID());
            getEntityManager().persist(message);

        } else {

            getEntityManager().merge(message);
        }
    }

}