Example usage for org.springframework.beans BeanUtils copyProperties

List of usage examples for org.springframework.beans BeanUtils copyProperties

Introduction

In this page you can find the example usage for org.springframework.beans BeanUtils copyProperties.

Prototype

public static void copyProperties(Object source, Object target) throws BeansException 

Source Link

Document

Copy the property values of the given source bean into the target bean.

Usage

From source file:org.talend.dataprep.conversions.BeanConversionService.java

/**
 * Similar {@link #convert(Object, Class)} but allow user to specify a constant conversion that overrides previously defined
 * conversions./*from   w  w  w . j  a v a  2  s.c o  m*/
 *
 * @param source The bean to convert.
 * @param aClass The target class for conversion.
 * @param onTheFlyConvert The function to apply on the transformed bean.
 * @param <U> The source type.
 * @param <T> The target type.
 * @return The converted bean (typed as <code>T</code>).
 */
public <U, T> T convert(U source, Class<T> aClass, BiFunction<U, T, T> onTheFlyConvert) {
    try {
        T converted = aClass.newInstance();
        BeanUtils.copyProperties(source, converted);
        return onTheFlyConvert.apply(source, converted);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.waterforpeople.mapping.app.web.rest.CascadeNodeRestService.java

@RequestMapping(method = RequestMethod.GET, value = "")
@ResponseBody/*from  ww w .j a v a 2  s.c om*/
public Map<String, List<CascadeNodeDto>> listCascadeNodes(
        @RequestParam(value = "cascadeResourceId", defaultValue = "") Long cascadeResourceId,
        @RequestParam(value = "parentNodeId", defaultValue = "") Long parentNodeId) {
    final Map<String, List<CascadeNodeDto>> response = new HashMap<String, List<CascadeNodeDto>>();
    List<CascadeNodeDto> results = new ArrayList<CascadeNodeDto>();
    List<CascadeNode> cnList = cascadeNodeDao.listCascadeNodesByResourceAndParentId(cascadeResourceId,
            parentNodeId);
    if (cnList != null) {
        for (CascadeNode cn : cnList) {
            CascadeNodeDto dto = new CascadeNodeDto();
            BeanUtils.copyProperties(cn, dto);
            if (cn.getKey() != null) {
                dto.setKeyId(cn.getKey().getId());
            }
            results.add(dto);
        }
    }
    response.put("cascade_nodes", results);
    return response;
}

From source file:org.waterforpeople.mapping.app.web.rest.CascadeNodeRestService.java

private CascadeNodeDto createCascadeNode(CascadeNodeDto cascadeNodeDto) {
    CascadeNode cn = new CascadeNode();
    BeanUtils.copyProperties(cascadeNodeDto, cn);
    if (StringUtils.isEmpty(cascadeNodeDto.getCode())) {
        cn.setCode(cn.getName());/*from  w w  w .ja v  a 2s. co m*/
    }
    cn = cascadeNodeDao.save(cn);
    CascadeNodeDto cnDto = new CascadeNodeDto();
    DtoMarshaller.copyToDto(cn, cnDto);
    return cnDto;
}

From source file:org.waterforpeople.mapping.app.web.rest.UserRolesRestService.java

/**
 * Update an existing user role//from   w w  w . ja  v a 2s .  c  om
 *
 * @param payload
 * @return
 */
@RequestMapping(method = RequestMethod.PUT, value = "/{roleId}")
@ResponseBody
public Map<String, Object> updateUserRole(@PathVariable Long roleId, @RequestBody UserRolePayload payload) {
    final RestStatusDto statusDto = new RestStatusDto();
    statusDto.setStatus("failed");

    final Map<String, Object> response = new HashMap<String, Object>();
    response.put("meta", statusDto);

    if (StringUtils.isBlank(payload.getName())) {
        statusDto.setMessage("_missing_role_name");
        return response;
    }

    UserRole existingRole = userRoleDao.getByKey(roleId);
    if (existingRole == null) {
        statusDto.setMessage("_role_not_found");
        return response;
    }

    if (!existingRole.getName().equals(payload.getName())) {
        UserRole duplicateRoleName = userRoleDao.findUserRoleByName(payload.getName());
        if (duplicateRoleName != null) {
            statusDto.setMessage("_duplicate_role_name");
            return response;
        }
    }

    BeanUtils.copyProperties(payload, existingRole);

    UserRolePayload updatedRole = new UserRolePayload(userRoleDao.save(existingRole));
    response.put("user_roles", updatedRole);
    statusDto.setStatus("ok");

    return response;
}

From source file:org.yes.cart.payment.impl.PaymentProcessorSurrogate.java

/**
 * AuthCapture or immediate sale operation wil be use if payment gateway not supports normal flow authorize - delivery - capture.
 *
 * @param order  to authorize payments.//from  www  .  j av  a  2  s. c  o  m
 * @param params for payment gateway to create template from. Also if this map contains key
 *               forceSinglePayment, only one payment will be created (hack to support pay pal express).
 * @return status of operation.
 */
String authorizeCapture(final CustomerOrder order, final Map params) {

    final List<Payment> paymentsToAuthorize = createPaymentsToAuthorize(order,
            params.containsKey("forceSinglePayment"), params, PaymentGateway.AUTH_CAPTURE);

    String paymentResult = null;

    for (Payment payment : paymentsToAuthorize) {
        try {
            payment = getPaymentGateway().authorizeCapture(payment);
            paymentResult = payment.getPaymentProcessorResult();
        } catch (Throwable th) {
            paymentResult = Payment.PAYMENT_STATUS_FAILED;
            payment.setPaymentProcessorResult(Payment.PAYMENT_STATUS_FAILED);
            payment.setTransactionOperationResultMessage(th.getMessage());

        } finally {
            final CustomerOrderPayment authCaptureOrderPayment = new CustomerOrderPaymentEntity();
            //customerOrderPaymentService.getGenericDao().getEntityFactory().getByIface(CustomerOrderPayment.class);
            BeanUtils.copyProperties(payment, authCaptureOrderPayment); //from PG object to persisted
            authCaptureOrderPayment.setPaymentProcessorResult(paymentResult);
            authCaptureOrderPayment.setShopCode(order.getShop().getCode());
            // FIXME: YC-390 we assume that funds are settled, but this is not guaranteed
            authCaptureOrderPayment
                    .setPaymentProcessorBatchSettlement(Payment.PAYMENT_STATUS_OK.equals(paymentResult));
            customerOrderPaymentService.create(authCaptureOrderPayment);
        }

    }

    return paymentResult;

}

From source file:org.yes.cart.payment.impl.PaymentProcessorSurrogate.java

/**
 * {@inheritDoc}//from   w w  w. ja va2  s .c o m
 */
public String authorize(final CustomerOrder order, final Map params) {

    if (getPaymentGateway().getPaymentGatewayFeatures().isSupportAuthorize()) {

        final List<Payment> paymentsToAuthorize = createPaymentsToAuthorize(order,
                params.containsKey("forceSinglePayment"), params, PaymentGateway.AUTH);

        for (Payment payment : paymentsToAuthorize) {
            String paymentResult = null;
            try {
                payment = getPaymentGateway().authorize(payment);
                paymentResult = payment.getPaymentProcessorResult();
            } catch (Throwable th) {
                paymentResult = Payment.PAYMENT_STATUS_FAILED;
                payment.setPaymentProcessorResult(Payment.PAYMENT_STATUS_FAILED);
                payment.setTransactionOperationResultMessage(th.getMessage());
            } finally {
                final CustomerOrderPayment authOrderPayment = new CustomerOrderPaymentEntity();
                //customerOrderPaymentService.getGenericDao().getEntityFactory().getByIface(CustomerOrderPayment.class);
                BeanUtils.copyProperties(payment, authOrderPayment); //from PG object to persisted
                authOrderPayment.setPaymentProcessorResult(paymentResult);
                authOrderPayment.setShopCode(order.getShop().getCode());
                customerOrderPaymentService.create(authOrderPayment);
                if (Payment.PAYMENT_STATUS_FAILED.equals(paymentResult)) {
                    reverseAuthorizations(order.getOrdernum());
                    return Payment.PAYMENT_STATUS_FAILED;
                }
            }
        }
        return Payment.PAYMENT_STATUS_OK;
    } else if (getPaymentGateway().getPaymentGatewayFeatures().isSupportAuthorizeCapture()) {
        return authorizeCapture(order, params);
    }
    throw new RuntimeException(MessageFormat.format(
            "Payment gateway {0}  must supports authorize and/ authorize capture operations",
            getPaymentGateway().getLabel()));
}

From source file:org.yes.cart.payment.impl.PaymentProcessorSurrogate.java

/**
 * Reverse authorized payments. This can be when one of the payments from whole set is failed.
 * Reverse authorization will applied to authorized payments only
 *
 * @param orderNum order with some authorized payments
 */// www. j  av  a 2s  .co m
public void reverseAuthorizations(final String orderNum) {
    if (getPaymentGateway().getPaymentGatewayFeatures().isSupportReverseAuthorization()) {
        final List<CustomerOrderPayment> paymentsToRevAuth = customerOrderPaymentService.findBy(orderNum, null,
                Payment.PAYMENT_STATUS_OK, PaymentGateway.AUTH);

        final List<CustomerOrderPayment> checkRevAuth = customerOrderPaymentService.findBy(orderNum, null,
                Payment.PAYMENT_STATUS_OK, null);

        for (CustomerOrderPayment customerOrderPayment : paymentsToRevAuth) {
            if (canPerformReverseAuth(customerOrderPayment, checkRevAuth)) {
                Payment payment = new PaymentImpl();
                BeanUtils.copyProperties(customerOrderPayment, payment); //from persisted to PG object

                String paymentResult = null;
                try {
                    payment = getPaymentGateway().reverseAuthorization(payment); //pass "original" to perform reverse authorization.
                    paymentResult = payment.getPaymentProcessorResult();
                } catch (Throwable th) {
                    paymentResult = Payment.PAYMENT_STATUS_FAILED;
                    payment.setPaymentProcessorResult(Payment.PAYMENT_STATUS_FAILED);
                    payment.setTransactionOperationResultMessage(th.getMessage());

                } finally {
                    final CustomerOrderPayment authReversedOrderPayment = new CustomerOrderPaymentEntity();
                    //customerOrderPaymentService.getGenericDao().getEntityFactory().getByIface(CustomerOrderPayment.class);
                    BeanUtils.copyProperties(payment, authReversedOrderPayment); //from PG object to persisted
                    authReversedOrderPayment.setPaymentProcessorResult(paymentResult);
                    authReversedOrderPayment.setShopCode(customerOrderPayment.getShopCode());
                    customerOrderPaymentService.create(authReversedOrderPayment);
                }

            }
        }
    }
}

From source file:org.yes.cart.payment.impl.PaymentProcessorSurrogate.java

/**
 * Particular shipment is complete. Funds can be captured.
 * In case of multiple delivery and single payment, capture on last delivery.
 *
 * @param order               order/*from www.j a  v  a 2  s.c  o  m*/
 * @param orderShipmentNumber internal shipment number.
 *                            Each order has at least one delivery.
 * @param addToPayment        amount to add for each payment if it not null
 * @return status of operation.
 */
public String shipmentComplete(final CustomerOrder order, final String orderShipmentNumber,
        final BigDecimal addToPayment) {

    final boolean isMultiplePaymentsSupports = getPaymentGateway().getPaymentGatewayFeatures()
            .isSupportAuthorizePerShipment();
    final List<CustomerOrderPayment> paymentsToCapture = customerOrderPaymentService.findBy(order.getOrdernum(),
            isMultiplePaymentsSupports ? orderShipmentNumber : order.getOrdernum(), Payment.PAYMENT_STATUS_OK,
            PaymentGateway.AUTH);
    if (paymentsToCapture.size() > 1 || (paymentsToCapture.isEmpty()
            && !getPaymentGateway().getPaymentGatewayFeatures().isSupportAuthorize())) {
        ShopCodeContext.getLog(this).warn( //must be only one record
                MessageFormat.format(
                        "Payment gateway {0} with features {1}. Found {2} records to capture, but expected 1 only. Order num {3} Shipment num {4}",
                        getPaymentGateway().getLabel(), getPaymentGateway().getPaymentGatewayFeatures(),
                        paymentsToCapture.size(), order.getOrdernum(), orderShipmentNumber));
    }

    boolean wasError = false;
    String paymentResult = null;

    if (isMultiplePaymentsSupports || isLastShipmentComplete(order)) { //each completed delivery or last in case of single pay for several delivery
        for (CustomerOrderPayment paymentToCapture : paymentsToCapture) {
            Payment payment = new PaymentImpl();
            BeanUtils.copyProperties(paymentToCapture, payment); //from persisted to PG object
            payment.setTransactionOperation(PaymentGateway.CAPTURE);

            try {
                if (addToPayment != null) {
                    payment.setPaymentAmount(
                            payment.getPaymentAmount().add(addToPayment).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                payment = getPaymentGateway().capture(payment); //pass "original" to perform fund capture.
                paymentResult = payment.getPaymentProcessorResult();
            } catch (Throwable th) {
                paymentResult = Payment.PAYMENT_STATUS_FAILED;
                payment.setPaymentProcessorResult(Payment.PAYMENT_STATUS_FAILED);
                payment.setTransactionOperationResultMessage(th.getMessage());
                ShopCodeContext.getLog(this).error("Cannot capture " + payment, th);

            } finally {
                final CustomerOrderPayment captureOrderPayment = new CustomerOrderPaymentEntity();
                //customerOrderPaymentService.getGenericDao().getEntityFactory().getByIface(CustomerOrderPayment.class);
                BeanUtils.copyProperties(payment, captureOrderPayment); //from PG object to persisted
                captureOrderPayment.setPaymentProcessorResult(paymentResult);
                captureOrderPayment.setShopCode(paymentToCapture.getShopCode());
                // FIXME: YC-390 we assume that funds are settled, but this is not guaranteed
                captureOrderPayment
                        .setPaymentProcessorBatchSettlement(Payment.PAYMENT_STATUS_OK.equals(paymentResult));
                customerOrderPaymentService.create(captureOrderPayment);
            }
            if (!Payment.PAYMENT_STATUS_OK.equals(paymentResult)) {
                wasError = true;
            }
        }
    }

    return wasError ? Payment.PAYMENT_STATUS_FAILED : Payment.PAYMENT_STATUS_OK;
}

From source file:org.yes.cart.payment.impl.PaymentProcessorSurrogate.java

/**
 * {@inheritDoc}/*from ww  w. jav a2  s  . c  o  m*/
 */
public String cancelOrder(final CustomerOrder order, boolean useRefund) {

    if (!CustomerOrder.ORDER_STATUS_CANCELLED.equals(order.getOrderStatus())
            && !CustomerOrder.ORDER_STATUS_RETURNED.equals(order.getOrderStatus())) {

        boolean wasError = false;

        final List<CustomerOrderPayment> paymentsToRollBack = new ArrayList<CustomerOrderPayment>();

        paymentsToRollBack.addAll(customerOrderPaymentService.findBy(order.getOrdernum(), null,
                Payment.PAYMENT_STATUS_OK, PaymentGateway.AUTH_CAPTURE));
        paymentsToRollBack.addAll(customerOrderPaymentService.findBy(order.getOrdernum(), null,
                Payment.PAYMENT_STATUS_OK, PaymentGateway.CAPTURE));

        reverseAuthorizations(order.getOrdernum());

        for (CustomerOrderPayment customerOrderPayment : paymentsToRollBack) {
            Payment payment = null;
            String paymentResult = null;
            try {
                payment = new PaymentImpl();
                BeanUtils.copyProperties(customerOrderPayment, payment); //from persisted to PG object
                if (useRefund /* customerOrderPayment.isPaymentProcessorBatchSettlement()*/) {
                    // refund
                    payment.setTransactionOperation(PaymentGateway.REFUND);
                    payment = getPaymentGateway().refund(payment);
                    paymentResult = payment.getPaymentProcessorResult();
                } else {
                    //void
                    payment.setTransactionOperation(PaymentGateway.VOID_CAPTURE);
                    payment = getPaymentGateway().voidCapture(payment);
                    paymentResult = payment.getPaymentProcessorResult();
                }
            } catch (Throwable th) {
                ShopCodeContext.getLog(this)
                        .error(MessageFormat.format(
                                "Can not perform roll back operation on payment record {0} payment {1}",
                                customerOrderPayment.getCustomerOrderPaymentId(), payment), th);
                wasError = true;
            } finally {
                final CustomerOrderPayment captureReversedOrderPayment = new CustomerOrderPaymentEntity();
                //customerOrderPaymentService.getGenericDao().getEntityFactory().getByIface(CustomerOrderPayment.class);
                BeanUtils.copyProperties(payment, captureReversedOrderPayment); //from PG object to persisted
                captureReversedOrderPayment.setPaymentProcessorResult(paymentResult);
                captureReversedOrderPayment.setShopCode(customerOrderPayment.getShopCode());
                customerOrderPaymentService.create(captureReversedOrderPayment);
            }
            if (!Payment.PAYMENT_STATUS_OK.equals(paymentResult)
                    && !Payment.PAYMENT_STATUS_MANUAL_PROCESSING_REQUIRED.equals(paymentResult)) {
                wasError = true;
            }

        }

        return wasError ? Payment.PAYMENT_STATUS_FAILED : Payment.PAYMENT_STATUS_OK;
    }
    ShopCodeContext.getLog(this).warn("Can refund canceled order  {}", order.getOrdernum());
    return Payment.PAYMENT_STATUS_FAILED;
}

From source file:org.yes.cart.payment.impl.PaymentProcessorSurrogate.java

/**
 * Add information to template payment object.
 *
 * @param templatePayment         template payment.
 * @param order                   order//from   w  w w .ja  v a  2  s  .c o  m
 * @param transactionOperation    operation in term of payment processor
 * @param transactionGatewayLabel label of payment gateway
 * @return payment prototype;
 */
private Payment fillPaymentPrototype(final CustomerOrder order, final Payment templatePayment,
        final String transactionOperation, final String transactionGatewayLabel) {

    final Customer customer = order.getCustomer();

    if (customer != null) {

        Address shippingAddr = customer.getDefaultAddress(Address.ADDR_TYPE_SHIPING);
        Address billingAddr = customer.getDefaultAddress(Address.ADDR_TYPE_BILLING);

        if (billingAddr == null) {
            billingAddr = shippingAddr;
        }

        if (billingAddr != null) {
            PaymentAddress addr = new PaymentAddressImpl();
            BeanUtils.copyProperties(billingAddr, addr);
            templatePayment.setBillingAddress(addr);
        }

        if (shippingAddr != null) {
            PaymentAddress addr = new PaymentAddressImpl();
            BeanUtils.copyProperties(shippingAddr, addr);
            templatePayment.setShippingAddress(addr);
        }

        templatePayment.setBillingAddressString(order.getBillingAddress());
        templatePayment.setShippingAddressString(order.getShippingAddress());

        templatePayment.setBillingEmail(customer.getEmail());

    }

    templatePayment.setOrderDate(order.getOrderTimestamp());
    templatePayment.setOrderCurrency(order.getCurrency());
    templatePayment.setOrderLocale(order.getLocale());
    templatePayment.setOrderNumber(order.getOrdernum());

    templatePayment.setTransactionOperation(transactionOperation);
    templatePayment.setTransactionGatewayLabel(transactionGatewayLabel);

    return templatePayment;
}