Spring-boot Нет запроса на привязку к потоку, когда выдается исключение в прослушивателе очереди JMS - PullRequest
0 голосов
/ 29 июня 2018

Я пытаюсь использовать очередь AWS, используя Spring boot с JMS, и у меня возникла проблема с генерированием исключений в моем потребительском методе. Каждый раз, когда я пытаюсь создать пользовательское исключение в своем потребительском методе для входа в Aspect, возвращается следующее сообщение:

errorCause = java.lang.IllegalStateException: Нет привязанного к потоку запроса найдено: Вы ссылаетесь на атрибуты запроса вне фактического веб-запрос или обработка запроса за пределами первоначально получая нить? Если вы действительно работаете в веб-запросе и по-прежнему получать это сообщение, ваш код, вероятно, работает за пределами DispatcherServlet / DispatcherPortlet: в этом случае используйте RequestContextListener или RequestContextFilter, чтобы выставить текущий request., errorMessage = Ошибка очереди прослушивания, дата = 2018-06-29T17: 45: 26,290, тип = InvoiceRefuseConsumer]

Я уже создал bean-компонент RequestContextListener, но мне это не удалось.

Может кто-нибудь сказать мне, что может быть причиной этой ошибки?

Вот мой код:

Модуль 1 - Потребитель очереди

@Service
public class InvoiceRefuseConsumer extends AbstractQueue implements IQueueConsumer{

    @Autowired
    private InvoiceRefuseService invoiceRefuseService;

    @JmsListener(destination = "${amazon.sqs.queue-to-be-consumed}")
    @Override
    public void listener(@Payload String message) throws ApplicationException {

        try {

            //Convert the payload received by the queue to the InvoiceFuseParam object
            InvoiceRefuseParam param = convertToPojo(message, InvoiceRefuseParam.class);

            // Set the type and reason of the refused invoice
            param.setType(InvoiceRefuseType.INVOICE_TREATMENT.getId());

            if(param.getReasonCode().equals(InvoiceRefuseTypeOperationType.TYPE_OPERATION_INSERT.getDesc())) {

                // Persist data information
                invoiceRefuseService.save(param);
            } else if(param.getReasonCode().equals(InvoiceRefuseTypeOperationType.TYPE_OPERATION_DELETE.getDesc())) {

                // Remove refused invoice
                invoiceRefuseService.delete(param.getKeyAccess(), param.getType());
            }

        } catch(Exception e) {
            throw new ApplicationException("Error listener queue", e);
        }
    }
}

Модуль 2 - Сервисные операции

@Service
public class InvoiceRefuseService {

    /**
     * automatically initiates the InvoiceRefuseCrud
     */
    @Autowired
    private InvoiceRefuseCrud invoiceRefuseCrud;

    /**
     * automatically initiates the SupplierCrud
     */
    @Autowired
    private SupplierCrud supplierCrud;

    /**
     * automatically initiates the SequenceDao
     */
    @Autowired
    private SequenceDao sequenceDao;

    /**
     * automatically initiates the InvoiceRefuseDao
     */
    @Autowired
    private InvoiceRefuseDao invoiceRefuseDao;

    /**
     * automatically initiates the OrderConsumerService
     */
    @Autowired
    private OrderConsumerService orderConsumerService;

    /**
     * automatically initiates the InvoiceOrderService
     */
    @Autowired
    private InvoiceOrderService invoiceOrderService;

    /**
     * automatically initiates the BranchWarehouseTypeDao
     */
    @Autowired
    private BranchWarehouseTypeDao branchWarehouseTypeDao;

    /**
     * Method created to delete a invoice refuse
     * @param key
     * @param type
     * @throws ApplicationException
     */
    @Transactional
    public void delete(String key, int type) throws ApplicationException {

        try {

            // Search for the refused invoices
            List<InvoiceRefuseModel> lsInvoiceRefuseModel = invoiceRefuseCrud.findBykeyAccessAndType(key, type);

            if(ApplicationUtils.isEmpty(lsInvoiceRefuseModel)){
                throw new FieldValidationException(getKey("key.notfound"));
            }

            // Remove refused invoice and cascate with the the scheduling order
            invoiceRefuseCrud.deleteAll(lsInvoiceRefuseModel);

        } catch (Exception e) {
            throw new ApplicationException(getKey("api.delete.error"), e);
        }
    }

    /**
     * Method created to save a new invoice refuse
     * @param param
     * @throws ApplicationException
     */
    @OneTransaction
    public void save(InvoiceRefuseParam param) throws ApplicationException {

        try {

            for (String orderNumber : param.getOrderNumbers()) {

                // Verify if the invoice refused key already exists
                Optional.ofNullable(invoiceRefuseCrud.findBykeyAccessAndType(param.getKeyAccess(), param.getType()))
                        .filter(invoiceRefuses -> invoiceRefuses.isEmpty())
                        .orElseThrow(() -> new ApplicationException(getKey("invoice.alread.exists")));

                // Convert to model
                InvoiceRefuseModel model = convertToSaveModel(param, orderNumber);

                // Save data on database
                InvoiceRefuseModel result = invoiceRefuseCrud.save(model);

                // Associate new refused invoice with the scheduled order
                associateInvoiceRefusedToSchedulingOrder(result);
            }

        } catch (Exception e) {
            throw new ApplicationException(getKey("api.save.error"), e);
        }
    }

    /**
     * Method creates to associate a refused invoice to the scheduling order
     * @param invoiceRefuseModel
     * @throws ApplicationException
     */
    public void associateInvoiceRefusedToSchedulingOrder(InvoiceRefuseModel invoiceRefuseModel) throws ApplicationException{

        // Search for the scheduled order
        List<InvoiceOrderModel> lsInvoiceOrderModel = invoiceOrderService.findByNuOrder(invoiceRefuseModel.getNuOrder());

        for (InvoiceOrderModel orderModel : lsInvoiceOrderModel) {

            // Verify if its a SAP order
            boolean isOrderSap = Optional
                    .ofNullable(branchWarehouseTypeDao.findByIdBranch(orderModel.getNuReceiverPlant()))
                    .filter(branch -> branch.getNaLoadPoint() != null)
                    .isPresent();

            if (isOrderSap) {

                // Update the order status
                invoiceOrderService.updateStatus(orderModel);
            }
        }
    }

    /**
     * Method created to convert from param to model
     * @param param
     * @param orderNumber
     * @return InvoiceRefuseModel
     * @throws ApplicationException
     */
    private InvoiceRefuseModel convertToSaveModel(InvoiceRefuseParam param, String orderNumber) throws ApplicationException{

        OrderParam orderParam  = new OrderParam();
        orderParam.getLsOrdeNumber().add(orderNumber);

        // Search for SAP orders
        OrderDataPojo orderSap = Optional.ofNullable(orderConsumerService.findAll(orderParam))
                .filter(ordersSap -> ordersSap.getOrders().size() > 0)
                .orElseThrow(() -> new ApplicationException(getKey("ordersap.notfound")));

        // Convert to model
        InvoiceRefuseModel model = new InvoiceRefuseModel();
        model.setNuOrder(orderNumber);

        model.setCdCompany(BranchMatrixType.MATRIX.getCdCompany());
        model.setDsMessage(param.getReasonDescription());

        model.setDtIssue(param.getIssueDate());
        model.setKeyAccess(param.getKeyAccess());
        model.setNuGuid(param.getGuid());
        model.setNuInvoice(param.getInvoiceNumber() + param.getInvoiceSerialNumber());
        model.setTsCreation(new Date());

        model.setNuInvoiceSerial(param.getInvoiceSerialNumber());
        model.setNuIssuerPlant(orderSap.getOrders().stream().map(o -> o.getHeader().getIssuerPlant()).findFirst().get());
        model.setNuReceiverPlant(orderSap.getOrders().stream().map(o -> o.getHeader().getReceiverPlant()).findFirst().get());
        model.setType(param.getType());
        model.setCdInvoiceRefuseMessage(param.getReasonCode());

        // Passing these fields is required for refused invoices, but they are not received for notes in treatment
        if(param.getType().equals(InvoiceRefuseType.INVOICE_REFUSED.getId())) {

            model.setIsEnableReturn(BooleanType.getByBool(param.getIsEnableReturn()).getId());
            model.setDtRefuse(param.getRefuseDate());
        }

        // Search for the issuing supplier
        SupplierModel supplierModelIssuer = findSupplier(param.getDocumentIdIssuer());
        model.setCdSupplierIssuer(supplierModelIssuer.getCdSupplier());

        // Search for the receiver supplier
        SupplierModel supplierModelReceiver = findSupplier(param.getDocumentIdIssuer());
        model.setCdSupplierReceiver(supplierModelReceiver.getCdSupplier());

        // Set the primary key
        InvoiceRefuseModelId id = new InvoiceRefuseModelId();
        id.setCdInvoiceRefuse(sequenceDao.nextIntValue(SequenceName.SQ_INVOICE_REFUSE));
        model.setId(id);

        return model;
    }

    /**
     * Method created to search for a supplier
     * @param documentId
     * @return SupplierModel
     * @throws ApplicationException
     */
    private SupplierModel findSupplier(String documentId) throws ApplicationException{

        // Search for the supplier
        SupplierModel model = supplierCrud.findTop1ByNuDocumentIdAndCdCompany(documentId, BranchMatrixType.MATRIX.getCdCompany());

        if(model == null){
            throw new ApplicationException(getKey("supplier.notfound"));
        }

        return model;
    }

    /**
     * Method created to find a refused invoice and return the result by page
     * @param param
     * @param pageable
     * @return Page<InvoiceRefuseModel>
     * @throws ApplicationException
     */
    public Page<InvoiceRefuseModel> findRefuseInvoice(InvoiceRefuseFilterParam param, Pageable pageable) throws ApplicationException {
        return invoiceRefuseDao.findRefuseInvoice(param, pageable);
    }

    /**
     * Method created to find a refused invoice and return the result by list
     * @param param
     * @return List<InvoiceRefuseModel>
     * @throws ApplicationException
     */
    public List<InvoiceRefuseModel> findRefuseInvoice(InvoiceRefuseFilterParam param) throws ApplicationException {
        return invoiceRefuseDao.findRefuseInvoice(param);
    }

    /**
     * Method created to find a refused invoice by order number and return the result by list
     * @param nuOrder
     * @return List<InvoiceRefuseModel>
     */
    public List<InvoiceRefuseModel> findByNuOrder(String nuOrder){
        return invoiceRefuseDao.findByNuOrder(nuOrder);
    }
}
...