Example usage for java.sql Timestamp getTime

List of usage examples for java.sql Timestamp getTime

Introduction

In this page you can find the example usage for java.sql Timestamp getTime.

Prototype

public long getTime() 

Source Link

Document

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.

Usage

From source file:org.ofbiz.order.order.OrderServices.java

/** Service for creating a new order */
public static Map<String, Object> createOrder(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    Security security = ctx.getSecurity();
    List<GenericValue> toBeStored = new LinkedList<GenericValue>();
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> successResult = ServiceUtil.returnSuccess();

    GenericValue userLogin = (GenericValue) context.get("userLogin");
    // get the order type
    String orderTypeId = (String) context.get("orderTypeId");
    String partyId = (String) context.get("partyId");
    String billFromVendorPartyId = (String) context.get("billFromVendorPartyId");

    // check security permissions for order:
    //  SALES ORDERS - if userLogin has ORDERMGR_SALES_CREATE or ORDERMGR_CREATE permission, or if it is same party as the partyId, or
    //                 if it is an AGENT (sales rep) creating an order for his customer
    //  PURCHASE ORDERS - if there is a PURCHASE_ORDER permission
    Map<String, Object> resultSecurity = new HashMap<String, Object>();
    boolean hasPermission = OrderServices.hasPermission(orderTypeId, partyId, userLogin, "CREATE", security);
    // final check - will pass if userLogin's partyId = partyId for order or if userLogin has ORDERMGR_CREATE permission
    // jacopoc: what is the meaning of this code block? FIXME
    if (!hasPermission) {
        partyId = ServiceUtil.getPartyIdCheckSecurity(userLogin, security, context, resultSecurity, "ORDERMGR",
                "_CREATE");
        if (resultSecurity.size() > 0) {
            return resultSecurity;
        }//from  www .  j a  va 2  s.c om
    }

    // get the product store for the order, but it is required only for sales orders
    String productStoreId = (String) context.get("productStoreId");
    GenericValue productStore = null;
    if ((orderTypeId.equals("SALES_ORDER")) && (UtilValidate.isNotEmpty(productStoreId))) {
        try {
            productStore = delegator.findByPrimaryKeyCache("ProductStore",
                    UtilMisc.toMap("productStoreId", productStoreId));
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource_error, "OrderErrorCouldNotFindProductStoreWithID",
                            UtilMisc.toMap("productStoreId", productStoreId), locale) + e.toString());
        }
    }

    // figure out if the order is immediately fulfilled based on product store settings
    boolean isImmediatelyFulfilled = false;
    if (productStore != null) {
        isImmediatelyFulfilled = "Y".equals(productStore.getString("isImmediatelyFulfilled"));
    }

    successResult.put("orderTypeId", orderTypeId);

    // lookup the order type entity
    GenericValue orderType = null;
    try {
        orderType = delegator.findByPrimaryKeyCache("OrderType", UtilMisc.toMap("orderTypeId", orderTypeId));
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource_error, "OrderErrorOrderTypeLookupFailed", locale)
                        + e.toString());
    }

    // make sure we have a valid order type
    if (orderType == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                "OrderErrorInvalidOrderTypeWithID", UtilMisc.toMap("orderTypeId", orderTypeId), locale));
    }

    // check to make sure we have something to order
    List<GenericValue> orderItems = UtilGenerics.checkList(context.get("orderItems"));
    if (orderItems.size() < 1) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "items.none", locale));
    }

    // all this marketing pkg auto stuff is deprecated in favor of MARKETING_PKG_AUTO productTypeId and a BOM of MANUF_COMPONENT assocs
    // these need to be retrieved now because they might be needed for exploding MARKETING_PKG_AUTO
    List<GenericValue> orderAdjustments = UtilGenerics.checkList(context.get("orderAdjustments"));
    List<GenericValue> orderItemShipGroupInfo = UtilGenerics.checkList(context.get("orderItemShipGroupInfo"));
    List<GenericValue> orderItemPriceInfo = UtilGenerics.checkList(context.get("orderItemPriceInfos"));

    // check inventory and other things for each item
    List<String> errorMessages = FastList.newInstance();
    Map<String, BigDecimal> normalizedItemQuantities = FastMap.newInstance();
    Map<String, String> normalizedItemNames = FastMap.newInstance();
    Map<String, GenericValue> itemValuesBySeqId = FastMap.newInstance();
    Iterator<GenericValue> itemIter = orderItems.iterator();
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();

    //
    // need to run through the items combining any cases where multiple lines refer to the
    // same product so the inventory check will work correctly
    // also count quantities ordered while going through the loop
    while (itemIter.hasNext()) {
        GenericValue orderItem = itemIter.next();

        // start by putting it in the itemValuesById Map
        itemValuesBySeqId.put(orderItem.getString("orderItemSeqId"), orderItem);

        String currentProductId = orderItem.getString("productId");
        if (currentProductId != null) {
            // only normalize items with a product associated (ignore non-product items)
            if (normalizedItemQuantities.get(currentProductId) == null) {
                normalizedItemQuantities.put(currentProductId, orderItem.getBigDecimal("quantity"));
                normalizedItemNames.put(currentProductId, orderItem.getString("itemDescription"));
            } else {
                BigDecimal currentQuantity = normalizedItemQuantities.get(currentProductId);
                normalizedItemQuantities.put(currentProductId,
                        currentQuantity.add(orderItem.getBigDecimal("quantity")));
            }

            /* try {
            // count product ordered quantities
            // run this synchronously so it will run in the same transaction
            dispatcher.runSync("countProductQuantityOrdered", UtilMisc.<String, Object>toMap("productId", currentProductId, "quantity", orderItem.getBigDecimal("quantity"), "userLogin", userLogin));
             } catch (GenericServiceException e1) {
            Debug.logError(e1, "Error calling countProductQuantityOrdered service", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                    "OrderErrorCallingCountProductQuantityOrderedService",locale) + e1.toString());
             }*/
        }
    }

    if (!"PURCHASE_ORDER".equals(orderTypeId) && productStoreId == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                "OrderErrorTheProductStoreIdCanOnlyBeNullForPurchaseOrders", locale));
    }

    Timestamp orderDate = (Timestamp) context.get("orderDate");

    Iterator<String> normalizedIter = normalizedItemQuantities.keySet().iterator();
    while (normalizedIter.hasNext()) {
        // lookup the product entity for each normalized item; error on products not found
        String currentProductId = normalizedIter.next();
        BigDecimal currentQuantity = normalizedItemQuantities.get(currentProductId);
        String itemName = normalizedItemNames.get(currentProductId);
        GenericValue product = null;

        try {
            product = delegator.findByPrimaryKeyCache("Product", UtilMisc.toMap("productId", currentProductId));
        } catch (GenericEntityException e) {
            String errMsg = UtilProperties.getMessage(resource_error, "product.not_found",
                    new Object[] { currentProductId }, locale);
            Debug.logError(e, errMsg, module);
            errorMessages.add(errMsg);
            continue;
        }

        if (product == null) {
            String errMsg = UtilProperties.getMessage(resource_error, "product.not_found",
                    new Object[] { currentProductId }, locale);
            Debug.logError(errMsg, module);
            errorMessages.add(errMsg);
            continue;
        }

        if ("SALES_ORDER".equals(orderTypeId)) {
            // check to see if introductionDate hasn't passed yet
            if (product.get("introductionDate") != null
                    && nowTimestamp.before(product.getTimestamp("introductionDate"))) {
                String excMsg = UtilProperties.getMessage(resource_error, "product.not_yet_for_sale",
                        new Object[] { getProductName(product, itemName), product.getString("productId") },
                        locale);
                Debug.logWarning(excMsg, module);
                errorMessages.add(excMsg);
                continue;
            }
        }

        if ("SALES_ORDER".equals(orderTypeId)) {
            boolean salesDiscontinuationFlag = false;
            // When past orders are imported, they should be imported even if sales discontinuation date is in the past but if the order date was before it
            if (orderDate != null && product.get("salesDiscontinuationDate") != null) {
                salesDiscontinuationFlag = orderDate.after(product.getTimestamp("salesDiscontinuationDate"))
                        && nowTimestamp.after(product.getTimestamp("salesDiscontinuationDate"));
            } else if (product.get("salesDiscontinuationDate") != null) {
                salesDiscontinuationFlag = nowTimestamp.after(product.getTimestamp("salesDiscontinuationDate"));
            }
            // check to see if salesDiscontinuationDate has passed
            if (salesDiscontinuationFlag) {
                String excMsg = UtilProperties.getMessage(resource_error, "product.no_longer_for_sale",
                        new Object[] { getProductName(product, itemName), product.getString("productId") },
                        locale);
                Debug.logWarning(excMsg, module);
                errorMessages.add(excMsg);
                continue;
            }
        }

        if ("SALES_ORDER".equals(orderTypeId)) {
            // check to see if we have inventory available
            try {
                Map<String, Object> invReqResult = dispatcher.runSync("isStoreInventoryAvailableOrNotRequired",
                        UtilMisc.toMap("productStoreId", productStoreId, "productId", product.get("productId"),
                                "product", product, "quantity", currentQuantity));
                if (ServiceUtil.isError(invReqResult)) {
                    errorMessages.add((String) invReqResult.get(ModelService.ERROR_MESSAGE));
                    List<String> errMsgList = UtilGenerics
                            .checkList(invReqResult.get(ModelService.ERROR_MESSAGE_LIST));
                    errorMessages.addAll(errMsgList);
                } else if (!"Y".equals(invReqResult.get("availableOrNotRequired"))) {
                    String invErrMsg = UtilProperties.getMessage(resource_error, "product.out_of_stock",
                            new Object[] { getProductName(product, itemName), currentProductId }, locale);
                    Debug.logWarning(invErrMsg, module);
                    errorMessages.add(invErrMsg);
                    continue;
                }
            } catch (GenericServiceException e) {
                String errMsg = "Fatal error calling inventory checking services: " + e.toString();
                Debug.logError(e, errMsg, module);
                errorMessages.add(errMsg);
            }
        }
    }

    // add the fixedAsset id to the workefforts map by obtaining the fixed Asset number from the FixedAssetProduct table
    List<GenericValue> workEfforts = UtilGenerics.checkList(context.get("workEfforts")); // is an optional parameter from this service but mandatory for rental items
    Iterator<GenericValue> orderItemIter = orderItems.iterator();
    while (orderItemIter.hasNext()) {
        GenericValue orderItem = orderItemIter.next();
        if ("RENTAL_ORDER_ITEM".equals(orderItem.getString("orderItemTypeId"))) {
            // check to see if workefforts are available for this order type.
            if (UtilValidate.isEmpty(workEfforts)) {
                String errMsg = "Work Efforts missing for ordertype RENTAL_ORDER_ITEM " + "Product: "
                        + orderItem.getString("productId");
                Debug.logError(errMsg, module);
                errorMessages.add(errMsg);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource_error, "OrderRentalOrderItems", locale));
            }
            Iterator<GenericValue> we = workEfforts.iterator(); // find the related workEffortItem (workEffortId = orderSeqId)
            while (we.hasNext()) {
                // create the entity maps required.
                GenericValue workEffort = we.next();
                if (workEffort.getString("workEffortId").equals(orderItem.getString("orderItemSeqId"))) {
                    List<GenericValue> selFixedAssetProduct = null;
                    try {
                        List<GenericValue> allFixedAssetProduct = delegator.findByAnd("FixedAssetProduct",
                                UtilMisc.toMap("productId", orderItem.getString("productId"),
                                        "fixedAssetProductTypeId", "FAPT_USE"));
                        selFixedAssetProduct = EntityUtil.filterByDate(allFixedAssetProduct, nowTimestamp,
                                "fromDate", "thruDate", true);
                    } catch (GenericEntityException e) {
                        String excMsg = "Could not find related Fixed Asset for the product: "
                                + orderItem.getString("productId");
                        Debug.logError(excMsg, module);
                        errorMessages.add(excMsg);
                        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                                "OrderCouldNotFindRelatedFixedAssetForTheProduct",
                                UtilMisc.toMap("productId", orderItem.getString("productId")), locale));
                    }

                    if (UtilValidate.isNotEmpty(selFixedAssetProduct)) {
                        Iterator<GenericValue> firstOne = selFixedAssetProduct.iterator();
                        if (firstOne.hasNext()) {
                            GenericValue fixedAssetProduct = delegator.makeValue("FixedAssetProduct");
                            fixedAssetProduct = firstOne.next();
                            workEffort.set("fixedAssetId", fixedAssetProduct.get("fixedAssetId"));
                            workEffort.set("quantityToProduce", orderItem.get("quantity")); // have quantity easy available later...
                            workEffort.set("createdByUserLogin", userLogin.get("userLoginId"));
                        }
                    }
                    break; // item found, so go to next orderitem.
                }
            }
        }
    }

    if (errorMessages.size() > 0) {
        return ServiceUtil.returnError(errorMessages);
    }

    // the inital status for ALL order types
    String initialStatus = "ORDER_CREATED";
    successResult.put("statusId", initialStatus);

    // create the order object
    String orderId = (String) context.get("orderId");
    String orgPartyId = null;
    if (productStore != null) {
        orgPartyId = productStore.getString("payToPartyId");
    } else if (billFromVendorPartyId != null) {
        orgPartyId = billFromVendorPartyId;
    }

    if (UtilValidate.isNotEmpty(orgPartyId)) {
        Map<String, Object> getNextOrderIdContext = FastMap.newInstance();
        getNextOrderIdContext.putAll(context);
        getNextOrderIdContext.put("partyId", orgPartyId);
        getNextOrderIdContext.put("userLogin", userLogin);

        if ((orderTypeId.equals("SALES_ORDER")) || (productStoreId != null)) {
            getNextOrderIdContext.put("productStoreId", productStoreId);
        }
        if (UtilValidate.isEmpty(orderId)) {
            try {
                getNextOrderIdContext = ctx.makeValidContext("getNextOrderId", "IN", getNextOrderIdContext);
                Map<String, Object> getNextOrderIdResult = dispatcher.runSync("getNextOrderId",
                        getNextOrderIdContext);
                if (ServiceUtil.isError(getNextOrderIdResult)) {
                    String errMsg = UtilProperties.getMessage(resource_error,
                            "OrderErrorGettingNextOrderIdWhileCreatingOrder", locale);
                    return ServiceUtil.returnError(errMsg, null, null, getNextOrderIdResult);
                }
                orderId = (String) getNextOrderIdResult.get("orderId");
            } catch (GenericServiceException e) {
                String errMsg = UtilProperties.getMessage(resource_error,
                        "OrderCaughtGenericServiceExceptionWhileGettingOrderId", locale);
                Debug.logError(e, errMsg, module);
                return ServiceUtil.returnError(errMsg);
            }
        }
    }

    if (UtilValidate.isEmpty(orderId)) {
        // for purchase orders or when other orderId generation fails, a product store id should not be required to make an order
        orderId = delegator.getNextSeqId("OrderHeader");
    }

    String billingAccountId = (String) context.get("billingAccountId");
    if (orderDate == null) {
        orderDate = nowTimestamp;
    }

    Map<String, Object> orderHeaderMap = UtilMisc.<String, Object>toMap("orderId", orderId, "orderTypeId",
            orderTypeId, "orderDate", orderDate, "entryDate", nowTimestamp, "statusId", initialStatus,
            "billingAccountId", billingAccountId);
    orderHeaderMap.put("orderName", context.get("orderName"));
    orderHeaderMap.put("estimatedDeliveryDate", context.get("estimatedDeliveryDate"));
    orderHeaderMap.put("isEnableAcctg", context.get("isEnableAcctg"));
    if (isImmediatelyFulfilled) {
        // also flag this order as needing inventory issuance so that when it is set to complete it will be issued immediately (needsInventoryIssuance = Y)
        orderHeaderMap.put("needsInventoryIssuance", "Y");
    }
    GenericValue orderHeader = delegator.makeValue("OrderHeader", orderHeaderMap);

    // determine the sales channel
    String salesChannelEnumId = (String) context.get("salesChannelEnumId");
    if ((salesChannelEnumId == null) || salesChannelEnumId.equals("UNKNWN_SALES_CHANNEL")) {
        // try the default store sales channel
        if (orderTypeId.equals("SALES_ORDER") && (productStore != null)) {
            salesChannelEnumId = productStore.getString("defaultSalesChannelEnumId");
        }
        // if there's still no channel, set to unknown channel
        if (salesChannelEnumId == null) {
            salesChannelEnumId = "UNKNWN_SALES_CHANNEL";
        }
    }
    orderHeader.set("salesChannelEnumId", salesChannelEnumId);

    if (context.get("currencyUom") != null) {
        orderHeader.set("currencyUom", context.get("currencyUom"));
    }

    if (context.get("firstAttemptOrderId") != null) {
        orderHeader.set("firstAttemptOrderId", context.get("firstAttemptOrderId"));
    }

    if (context.get("grandTotal") != null) {
        orderHeader.set("grandTotal", context.get("grandTotal"));
    }

    if (UtilValidate.isNotEmpty(context.get("visitId"))) {
        orderHeader.set("visitId", context.get("visitId"));
    }

    if (UtilValidate.isNotEmpty(context.get("internalCode"))) {
        orderHeader.set("internalCode", context.get("internalCode"));
    }

    if (UtilValidate.isNotEmpty(context.get("externalId"))) {
        orderHeader.set("externalId", context.get("externalId"));
    }

    if (UtilValidate.isNotEmpty(context.get("originFacilityId"))) {
        orderHeader.set("originFacilityId", context.get("originFacilityId"));
    }
    if (UtilValidate.isNotEmpty(context.get("productSubscriptionTypeId"))) {
        orderHeader.set("productSubscriptionTypeId", context.get("productSubscriptionTypeId"));
    }
    if (UtilValidate.isNotEmpty(context.get("shipmentId"))) {
        orderHeader.set("shipmentId", context.get("shipmentId"));
    }
    if (UtilValidate.isNotEmpty(context.get("purposeTypeId"))) {
        orderHeader.set("purposeTypeId", context.get("purposeTypeId"));
    }
    if (UtilValidate.isNotEmpty(context.get("productStoreId"))) {
        orderHeader.set("productStoreId", context.get("productStoreId"));
    }

    if (UtilValidate.isNotEmpty(context.get("transactionId"))) {
        orderHeader.set("transactionId", context.get("transactionId"));
    }

    if (UtilValidate.isNotEmpty(context.get("terminalId"))) {
        orderHeader.set("terminalId", context.get("terminalId"));
    }

    if (UtilValidate.isNotEmpty(context.get("autoOrderShoppingListId"))) {
        orderHeader.set("autoOrderShoppingListId", context.get("autoOrderShoppingListId"));
    }

    if (UtilValidate.isNotEmpty(context.get("webSiteId"))) {
        orderHeader.set("webSiteId", context.get("webSiteId"));
    }

    if (userLogin != null && userLogin.get("userLoginId") != null) {
        orderHeader.set("createdBy", userLogin.getString("userLoginId"));
    }
    if (UtilValidate.isNotEmpty(context.get("orderName"))) {
        orderHeader.set("orderName", context.get("orderName"));
    }
    // first try to create the OrderHeader; if this does not fail, continue.
    try {
        delegator.create(orderHeader);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Cannot create OrderHeader entity; problems with insert", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                "OrderOrderCreationFailedPleaseNotifyCustomerService", locale));
    }

    // create the order status record
    String orderStatusSeqId = delegator.getNextSeqId("OrderStatus");
    GenericValue orderStatus = delegator.makeValue("OrderStatus",
            UtilMisc.toMap("orderStatusId", orderStatusSeqId));
    orderStatus.set("orderId", orderId);
    orderStatus.set("statusId", orderHeader.getString("statusId"));
    orderStatus.set("statusDatetime", nowTimestamp);
    orderStatus.set("statusUserLogin", userLogin.getString("userLoginId"));
    toBeStored.add(orderStatus);

    // before processing orderItems process orderItemGroups so that they'll be in place for the foreign keys and what not
    List<GenericValue> orderItemGroups = UtilGenerics.checkList(context.get("orderItemGroups"));
    if (UtilValidate.isNotEmpty(orderItemGroups)) {
        Iterator<GenericValue> orderItemGroupIter = orderItemGroups.iterator();
        while (orderItemGroupIter.hasNext()) {
            GenericValue orderItemGroup = orderItemGroupIter.next();
            orderItemGroup.set("orderId", orderId);
            toBeStored.add(orderItemGroup);
        }
    }

    // set the order items
    Iterator<GenericValue> oi = orderItems.iterator();
    while (oi.hasNext()) {
        GenericValue orderItem = oi.next();
        orderItem.set("orderId", orderId);
        toBeStored.add(orderItem);

        // create the item status record
        /* String itemStatusId = delegator.getNextSeqId("OrderStatus");
         GenericValue itemStatus = delegator.makeValue("OrderStatus", UtilMisc.toMap("orderStatusId", itemStatusId));
         itemStatus.put("statusId", orderItem.get("statusId"));
         itemStatus.put("orderId", orderId);
         itemStatus.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
         itemStatus.put("statusDatetime", nowTimestamp);
         itemStatus.set("statusUserLogin", userLogin.getString("userLoginId"));
         toBeStored.add(itemStatus);*/
    }

    // set the order attributes
    List<GenericValue> orderAttributes = UtilGenerics.checkList(context.get("orderAttributes"));
    if (UtilValidate.isNotEmpty(orderAttributes)) {
        Iterator<GenericValue> oattr = orderAttributes.iterator();
        while (oattr.hasNext()) {
            GenericValue oatt = oattr.next();
            oatt.set("orderId", orderId);
            toBeStored.add(oatt);
        }
    }

    // set the order item attributes
    List<GenericValue> orderItemAttributes = UtilGenerics.checkList(context.get("orderItemAttributes"));
    if (UtilValidate.isNotEmpty(orderItemAttributes)) {
        Iterator<GenericValue> oiattr = orderItemAttributes.iterator();
        while (oiattr.hasNext()) {
            GenericValue oiatt = oiattr.next();
            oiatt.set("orderId", orderId);
            toBeStored.add(oiatt);
        }
    }

    // create the order internal notes
    List<String> orderInternalNotes = UtilGenerics.checkList(context.get("orderInternalNotes"));
    if (UtilValidate.isNotEmpty(orderInternalNotes)) {
        Iterator<String> orderInternalNotesIt = orderInternalNotes.iterator();
        while (orderInternalNotesIt.hasNext()) {
            String orderInternalNote = orderInternalNotesIt.next();
            try {
                Map<String, Object> noteOutputMap = dispatcher.runSync("createOrderNote",
                        UtilMisc.<String, Object>toMap("orderId", orderId, "internalNote", "Y", "note",
                                orderInternalNote, "userLogin", userLogin));
                if (ServiceUtil.isError(noteOutputMap)) {
                    return ServiceUtil
                            .returnError(
                                    UtilProperties.getMessage(resource, "OrderOrderNoteCannotBeCreated",
                                            UtilMisc.toMap("errorString", ""), locale),
                                    null, null, noteOutputMap);
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Error creating internal notes while creating order: " + e.toString(),
                        module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                        "OrderOrderNoteCannotBeCreated", UtilMisc.toMap("errorString", e.toString()), locale));
            }
        }
    }

    // create the order public notes
    List<String> orderNotes = UtilGenerics.checkList(context.get("orderNotes"));
    if (UtilValidate.isNotEmpty(orderNotes)) {
        Iterator<String> orderNotesIt = orderNotes.iterator();
        while (orderNotesIt.hasNext()) {
            String orderNote = orderNotesIt.next();
            try {
                Map<String, Object> noteOutputMap = dispatcher.runSync("createOrderNote",
                        UtilMisc.<String, Object>toMap("orderId", orderId, "internalNote", "N", "note",
                                orderNote, "userLogin", userLogin));
                if (ServiceUtil.isError(noteOutputMap)) {
                    return ServiceUtil
                            .returnError(
                                    UtilProperties.getMessage(resource, "OrderOrderNoteCannotBeCreated",
                                            UtilMisc.toMap("errorString", ""), locale),
                                    null, null, noteOutputMap);
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Error creating notes while creating order: " + e.toString(), module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                        "OrderOrderNoteCannotBeCreated", UtilMisc.toMap("errorString", e.toString()), locale));
            }
        }
    }

    // create the workeffort records
    // and connect them with the orderitem over the WorkOrderItemFulfillment
    // create also the techData calendars to keep track of availability of the fixed asset.
    if (UtilValidate.isNotEmpty(workEfforts)) {
        List<GenericValue> tempList = new LinkedList<GenericValue>();
        Iterator<GenericValue> we = workEfforts.iterator();
        while (we.hasNext()) {
            // create the entity maps required.
            GenericValue workEffort = we.next();
            GenericValue workOrderItemFulfillment = delegator.makeValue("WorkOrderItemFulfillment");
            // find fixed asset supplied on the workeffort map
            GenericValue fixedAsset = null;
            Debug.logInfo("find the fixedAsset", module);
            try {
                fixedAsset = delegator.findByPrimaryKey("FixedAsset",
                        UtilMisc.toMap("fixedAssetId", workEffort.get("fixedAssetId")));
            } catch (GenericEntityException e) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource_error, "OrderFixedAssetNotFoundFixedAssetId",
                                UtilMisc.toMap("fixedAssetId", workEffort.get("fixedAssetId")), locale));
            }
            if (fixedAsset == null) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource_error, "OrderFixedAssetNotFoundFixedAssetId",
                                UtilMisc.toMap("fixedAssetId", workEffort.get("fixedAssetId")), locale));
            }
            // see if this fixed asset has a calendar, when no create one and attach to fixed asset
            Debug.logInfo("find the techdatacalendar", module);
            GenericValue techDataCalendar = null;
            try {
                techDataCalendar = fixedAsset.getRelatedOne("TechDataCalendar");
            } catch (GenericEntityException e) {
                Debug.logInfo("TechData calendar does not exist yet so create for fixedAsset: "
                        + fixedAsset.get("fixedAssetId"), module);
            }
            if (techDataCalendar == null) {
                Iterator<GenericValue> fai = tempList.iterator();
                while (fai.hasNext()) {
                    GenericValue currentValue = fai.next();
                    if ("FixedAsset".equals(currentValue.getEntityName()) && currentValue
                            .getString("fixedAssetId").equals(workEffort.getString("fixedAssetId"))) {
                        fixedAsset = currentValue;
                        break;
                    }
                }
                Iterator<GenericValue> tdci = tempList.iterator();
                while (tdci.hasNext()) {
                    GenericValue currentValue = tdci.next();
                    if ("TechDataCalendar".equals(currentValue.getEntityName()) && currentValue
                            .getString("calendarId").equals(fixedAsset.getString("calendarId"))) {
                        techDataCalendar = currentValue;
                        break;
                    }
                }
            }
            if (techDataCalendar == null) {
                techDataCalendar = delegator.makeValue("TechDataCalendar");
                Debug.logInfo("create techdata calendar because it does not exist", module);
                String calendarId = delegator.getNextSeqId("TechDataCalendar");
                techDataCalendar.set("calendarId", calendarId);
                tempList.add(techDataCalendar);
                Debug.logInfo("update fixed Asset", module);
                fixedAsset.set("calendarId", calendarId);
                tempList.add(fixedAsset);
            }
            // then create the workEffort and the workOrderItemFulfillment to connect to the order and orderItem
            workOrderItemFulfillment.set("orderItemSeqId", workEffort.get("workEffortId").toString()); // orderItemSeqNo is stored here so save first
            // workeffort
            String workEffortId = delegator.getNextSeqId("WorkEffort"); // find next available workEffortId
            workEffort.set("workEffortId", workEffortId);
            workEffort.set("workEffortTypeId", "ASSET_USAGE");
            toBeStored.add(workEffort); // store workeffort before workOrderItemFulfillment because of workEffortId key constraint
            // workOrderItemFulfillment
            workOrderItemFulfillment.set("workEffortId", workEffortId);
            workOrderItemFulfillment.set("orderId", orderId);
            toBeStored.add(workOrderItemFulfillment);
            //                Debug.logInfo("Workeffort "+ workEffortId + " created for asset " + workEffort.get("fixedAssetId") + " and order "+ workOrderItemFulfillment.get("orderId") + "/" + workOrderItemFulfillment.get("orderItemSeqId") + " created", module);
            //
            // now create the TechDataExcDay, when they do not exist, create otherwise update the capacity values
            // please note that calendarId is the same for (TechData)Calendar, CalendarExcDay and CalendarExWeek
            Timestamp estimatedStartDate = workEffort.getTimestamp("estimatedStartDate");
            Timestamp estimatedCompletionDate = workEffort.getTimestamp("estimatedCompletionDate");
            long dayCount = (estimatedCompletionDate.getTime() - estimatedStartDate.getTime()) / 86400000;
            while (--dayCount >= 0) {
                GenericValue techDataCalendarExcDay = null;
                // find an existing Day exception record
                Timestamp exceptionDateStartTime = UtilDateTime
                        .getDayStart(new Timestamp(estimatedStartDate.getTime()), (int) dayCount);
                try {
                    techDataCalendarExcDay = delegator.findByPrimaryKey("TechDataCalendarExcDay",
                            UtilMisc.toMap("calendarId", fixedAsset.get("calendarId"), "exceptionDateStartTime",
                                    exceptionDateStartTime));
                } catch (GenericEntityException e) {
                    Debug.logInfo(" techData excday record not found so creating........", module);
                }
                if (techDataCalendarExcDay == null) {
                    Iterator<GenericValue> tdcedi = tempList.iterator();
                    while (tdcedi.hasNext()) {
                        GenericValue currentValue = tdcedi.next();
                        if ("TechDataCalendarExcDay".equals(currentValue.getEntityName())
                                && currentValue.getString("calendarId")
                                        .equals(fixedAsset.getString("calendarId"))
                                && currentValue.getTimestamp("exceptionDateStartTime")
                                        .equals(exceptionDateStartTime)) {
                            techDataCalendarExcDay = currentValue;
                            break;
                        }
                    }
                }
                if (techDataCalendarExcDay == null) {
                    techDataCalendarExcDay = delegator.makeValue("TechDataCalendarExcDay");
                    techDataCalendarExcDay.set("calendarId", fixedAsset.get("calendarId"));
                    techDataCalendarExcDay.set("exceptionDateStartTime", exceptionDateStartTime);
                    techDataCalendarExcDay.set("usedCapacity", BigDecimal.ZERO); // initialise to zero
                    techDataCalendarExcDay.set("exceptionCapacity",
                            fixedAsset.getBigDecimal("productionCapacity"));
                    //                       Debug.logInfo(" techData excday record not found creating for calendarId: " + techDataCalendarExcDay.getString("calendarId") +
                    //                               " and date: " + exceptionDateStartTime.toString(), module);
                }
                // add the quantity to the quantity on the date record
                BigDecimal newUsedCapacity = techDataCalendarExcDay.getBigDecimal("usedCapacity")
                        .add(workEffort.getBigDecimal("quantityToProduce"));
                // check to see if the requested quantity is available on the requested day but only when the maximum capacity is set on the fixed asset
                if (fixedAsset.get("productionCapacity") != null) {
                    //                       Debug.logInfo("see if maximum not reached, available:  " + techDataCalendarExcDay.getString("exceptionCapacity") +
                    //                               " already allocated: " + techDataCalendarExcDay.getString("usedCapacity") +
                    //                                " Requested: " + workEffort.getString("quantityToProduce"), module);
                    if (newUsedCapacity
                            .compareTo(techDataCalendarExcDay.getBigDecimal("exceptionCapacity")) > 0) {
                        String errMsg = "ERROR: fixed_Asset_sold_out AssetId: " + workEffort.get("fixedAssetId")
                                + " on date: " + techDataCalendarExcDay.getString("exceptionDateStartTime");
                        Debug.logError(errMsg, module);
                        errorMessages.add(errMsg);
                        continue;
                    }
                }
                techDataCalendarExcDay.set("usedCapacity", newUsedCapacity);
                tempList.add(techDataCalendarExcDay);
                //                  Debug.logInfo("Update success CalendarID: " + techDataCalendarExcDay.get("calendarId").toString() +
                //                            " and for date: " + techDataCalendarExcDay.get("exceptionDateStartTime").toString() +
                //                            " and for quantity: " + techDataCalendarExcDay.getDouble("usedCapacity").toString(), module);
            }
        }
        if (tempList.size() > 0) {
            toBeStored.addAll(tempList);
        }
    }
    if (errorMessages.size() > 0) {
        return ServiceUtil.returnError(errorMessages);
    }

    // set the orderId on all adjustments; this list will include order and
    // item adjustments...
    if (UtilValidate.isNotEmpty(orderAdjustments)) {
        Iterator<GenericValue> iter = orderAdjustments.iterator();

        while (iter.hasNext()) {
            GenericValue orderAdjustment = iter.next();
            try {
                orderAdjustment.set("orderAdjustmentId", delegator.getNextSeqId("OrderAdjustment"));
            } catch (IllegalArgumentException e) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                        "OrderErrorCouldNotGetNextSequenceIdForOrderAdjustmentCannotCreateOrder", locale));
            }

            orderAdjustment.set("orderId", orderId);
            orderAdjustment.set("createdDate", UtilDateTime.nowTimestamp());
            orderAdjustment.set("createdByUserLogin", userLogin.getString("userLoginId"));

            if (UtilValidate.isEmpty(orderAdjustment.get("orderItemSeqId"))) {
                orderAdjustment.set("orderItemSeqId", DataModelConstants.SEQ_ID_NA);
            }
            if (UtilValidate.isEmpty(orderAdjustment.get("shipGroupSeqId"))) {
                orderAdjustment.set("shipGroupSeqId", DataModelConstants.SEQ_ID_NA);
            }
            toBeStored.add(orderAdjustment);
        }
    }

    // set the order contact mechs
    List<GenericValue> orderContactMechs = UtilGenerics.checkList(context.get("orderContactMechs"));
    if (UtilValidate.isNotEmpty(orderContactMechs)) {
        Iterator<GenericValue> ocmi = orderContactMechs.iterator();

        while (ocmi.hasNext()) {
            GenericValue ocm = ocmi.next();
            ocm.set("orderId", orderId);
            toBeStored.add(ocm);
        }
    }

    // set the order item contact mechs
    List<GenericValue> orderItemContactMechs = UtilGenerics.checkList(context.get("orderItemContactMechs"));
    if (UtilValidate.isNotEmpty(orderItemContactMechs)) {
        Iterator<GenericValue> oicmi = orderItemContactMechs.iterator();

        while (oicmi.hasNext()) {
            GenericValue oicm = oicmi.next();
            oicm.set("orderId", orderId);
            toBeStored.add(oicm);
        }
    }

    // set the order item ship groups
    // commented when PurchaseOrder not created without shipment
    List<String> dropShipGroupIds = FastList.newInstance(); // this list will contain the ids of all the ship groups for drop shipments (no reservations)
    if (UtilValidate.isNotEmpty(orderItemShipGroupInfo)) {
        Iterator<GenericValue> osiInfos = orderItemShipGroupInfo.iterator();
        while (osiInfos.hasNext()) {
            GenericValue valueObj = osiInfos.next();
            valueObj.set("orderId", orderId);
            /* if ("OrderItemShipGroup".equals(valueObj.getEntityName())) {
            // ship group
            if (valueObj.get("carrierRoleTypeId") == null) {
                valueObj.set("carrierRoleTypeId", "CARRIER");
            }
            if (!UtilValidate.isEmpty(valueObj.getString("supplierPartyId"))) {
                dropShipGroupIds.add(valueObj.getString("shipGroupSeqId"));
            }
             toBeStored.add(valueObj); // from out side of if we bring here
             } else */
            if ("OrderAdjustment".equals(valueObj.getEntityName())) {
                // shipping / tax adjustment(s)
                if (UtilValidate.isEmpty(valueObj.get("orderItemSeqId"))) {
                    valueObj.set("orderItemSeqId", DataModelConstants.SEQ_ID_NA);
                }
                valueObj.set("orderAdjustmentId", delegator.getNextSeqId("OrderAdjustment"));
                valueObj.set("createdDate", UtilDateTime.nowTimestamp());
                valueObj.set("createdByUserLogin", userLogin.getString("userLoginId"));
                toBeStored.add(valueObj);
            }

        }
    }

    // set the additional party roles
    Map<String, List<String>> additionalPartyRole = UtilGenerics
            .checkMap(context.get("orderAdditionalPartyRoleMap"));
    if (additionalPartyRole != null) {
        for (Map.Entry<String, List<String>> entry : additionalPartyRole.entrySet()) {
            String additionalRoleTypeId = entry.getKey();
            List<String> parties = entry.getValue();
            if (parties != null) {
                Iterator<String> apIt = parties.iterator();
                while (apIt.hasNext()) {
                    String additionalPartyId = apIt.next();
                    toBeStored.add(delegator.makeValue("PartyRole",
                            UtilMisc.toMap("partyId", additionalPartyId, "roleTypeId", additionalRoleTypeId)));
                    toBeStored.add(delegator.makeValue("OrderRole", UtilMisc.toMap("orderId", orderId,
                            "partyId", additionalPartyId, "roleTypeId", additionalRoleTypeId)));
                }
            }
        }
    }

    // set the item survey responses
    List<GenericValue> surveyResponses = UtilGenerics.checkList(context.get("orderItemSurveyResponses"));
    if (UtilValidate.isNotEmpty(surveyResponses)) {
        Iterator<GenericValue> oisr = surveyResponses.iterator();
        while (oisr.hasNext()) {
            GenericValue surveyResponse = oisr.next();
            surveyResponse.set("orderId", orderId);
            toBeStored.add(surveyResponse);
        }
    }

    // set the item price info; NOTE: this must be after the orderItems are stored for referential integrity
    if (UtilValidate.isNotEmpty(orderItemPriceInfo)) {
        Iterator<GenericValue> oipii = orderItemPriceInfo.iterator();

        while (oipii.hasNext()) {
            GenericValue oipi = oipii.next();
            try {
                oipi.set("orderItemPriceInfoId", delegator.getNextSeqId("OrderItemPriceInfo"));
            } catch (IllegalArgumentException e) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                        "OrderErrorCouldNotGetNextSequenceIdForOrderItemPriceInfoCannotCreateOrder", locale));
            }

            oipi.set("orderId", orderId);
            toBeStored.add(oipi);
        }
    }

    // set the item associations
    List<GenericValue> orderItemAssociations = UtilGenerics.checkList(context.get("orderItemAssociations"));
    if (UtilValidate.isNotEmpty(orderItemAssociations)) {
        Iterator<GenericValue> oia = orderItemAssociations.iterator();
        while (oia.hasNext()) {
            GenericValue orderItemAssociation = oia.next();
            if (orderItemAssociation.get("toOrderId") == null) {
                orderItemAssociation.set("toOrderId", orderId);
            } else if (orderItemAssociation.get("orderId") == null) {
                orderItemAssociation.set("orderId", orderId);
            }
            toBeStored.add(orderItemAssociation);
        }
    }

    // store the orderProductPromoUseInfos
    List<GenericValue> orderProductPromoUses = UtilGenerics.checkList(context.get("orderProductPromoUses"));
    if (UtilValidate.isNotEmpty(orderProductPromoUses)) {
        Iterator<GenericValue> orderProductPromoUseIter = orderProductPromoUses.iterator();
        while (orderProductPromoUseIter.hasNext()) {
            GenericValue productPromoUse = orderProductPromoUseIter.next();
            productPromoUse.set("orderId", orderId);
            toBeStored.add(productPromoUse);
        }
    }

    // store the orderProductPromoCodes
    Set<String> orderProductPromoCodes = UtilGenerics.checkSet(context.get("orderProductPromoCodes"));
    if (UtilValidate.isNotEmpty(orderProductPromoCodes)) {
        GenericValue orderProductPromoCode = delegator.makeValue("OrderProductPromoCode");
        Iterator<String> orderProductPromoCodeIter = orderProductPromoCodes.iterator();
        while (orderProductPromoCodeIter.hasNext()) {
            orderProductPromoCode.clear();
            orderProductPromoCode.set("orderId", orderId);
            orderProductPromoCode.set("productPromoCodeId", orderProductPromoCodeIter.next());
            toBeStored.add(orderProductPromoCode);
        }
    }

    /* DEJ20050529 the OLD way, where a single party had all roles... no longer doing things this way...
    // define the roles for the order
    List userOrderRoleTypes = null;
    if ("SALES_ORDER".equals(orderTypeId)) {
    userOrderRoleTypes = UtilMisc.toList("END_USER_CUSTOMER", "SHIP_TO_CUSTOMER", "BILL_TO_CUSTOMER", "PLACING_CUSTOMER");
    } else if ("PURCHASE_ORDER".equals(orderTypeId)) {
    userOrderRoleTypes = UtilMisc.toList("SHIP_FROM_VENDOR", "BILL_FROM_VENDOR", "SUPPLIER_AGENT");
    } else {
    // TODO: some default behavior
    }
            
    // now add the roles
    if (userOrderRoleTypes != null) {
    Iterator i = userOrderRoleTypes.iterator();
    while (i.hasNext()) {
        String roleType = (String) i.next();
        String thisParty = partyId;
        if (thisParty == null) {
            thisParty = "_NA_";  // will always set these roles so we can query
        }
        // make sure the party is in the role before adding
        toBeStored.add(delegator.makeValue("PartyRole", UtilMisc.toMap("partyId", partyId, "roleTypeId", roleType)));
        toBeStored.add(delegator.makeValue("OrderRole", UtilMisc.toMap("orderId", orderId, "partyId", partyId, "roleTypeId", roleType)));
    }
    }
    */

    // see the attributeRoleMap definition near the top of this file for attribute-role mappings
    Map<String, String> attributeRoleMap = salesAttributeRoleMap;
    GenericValue orderHeaderType = null;
    try {
        orderHeaderType = delegator.findOne("OrderType", UtilMisc.toMap("orderTypeId", orderTypeId), false);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problems to get orderType", module);
    }
    if (("PURCHASE_ORDER".equals(orderTypeId)) || (UtilValidate.isNotEmpty(orderHeaderType)
            && ("PURCHASE_ORDER".equals(orderHeaderType.getString("parentTypeId"))))) {
        attributeRoleMap = purchaseAttributeRoleMap;
        //Debug.log("===orderTypeId==beforeRole="+orderTypeId);
    }
    for (Map.Entry<String, String> attributeRoleEntry : attributeRoleMap.entrySet()) {
        if (UtilValidate.isNotEmpty(context.get(attributeRoleEntry.getKey()))) {
            // make sure the party is in the role before adding
            toBeStored.add(delegator.makeValue("PartyRole", UtilMisc.toMap("partyId",
                    context.get(attributeRoleEntry.getKey()), "roleTypeId", attributeRoleEntry.getValue())));
            toBeStored.add(delegator.makeValue("OrderRole", UtilMisc.toMap("orderId", orderId, "partyId",
                    context.get(attributeRoleEntry.getKey()), "roleTypeId", attributeRoleEntry.getValue())));
        }
    }

    // set the affiliate -- This is going to be removed...
    String affiliateId = (String) context.get("affiliateId");
    if (UtilValidate.isNotEmpty(affiliateId)) {
        toBeStored.add(delegator.makeValue("OrderRole",
                UtilMisc.toMap("orderId", orderId, "partyId", affiliateId, "roleTypeId", "AFFILIATE")));
    }

    // set the distributor
    String distributorId = (String) context.get("distributorId");
    if (UtilValidate.isNotEmpty(distributorId)) {
        toBeStored.add(delegator.makeValue("OrderRole",
                UtilMisc.toMap("orderId", orderId, "partyId", distributorId, "roleTypeId", "DISTRIBUTOR")));
    }

    // find all parties in role VENDOR associated with WebSite OR ProductStore (where WebSite overrides, if specified), associated first valid with the Order
    if (UtilValidate.isNotEmpty(context.get("productStoreId"))) {
        try {
            List<GenericValue> productStoreRoles = delegator.findByAnd("ProductStoreRole",
                    UtilMisc.toMap("roleTypeId", "VENDOR", "productStoreId", context.get("productStoreId")),
                    UtilMisc.toList("-fromDate"));
            productStoreRoles = EntityUtil.filterByDate(productStoreRoles, true);
            GenericValue productStoreRole = EntityUtil.getFirst(productStoreRoles);
            if (productStoreRole != null) {
                toBeStored.add(delegator.makeValue("OrderRole", UtilMisc.toMap("orderId", orderId, "partyId",
                        productStoreRole.get("partyId"), "roleTypeId", "VENDOR")));
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error looking up Vendor for the current Product Store", module);
        }

    }
    if (UtilValidate.isNotEmpty(context.get("webSiteId"))) {
        try {
            List<GenericValue> webSiteRoles = delegator.findByAnd("WebSiteRole",
                    UtilMisc.toMap("roleTypeId", "VENDOR", "webSiteId", context.get("webSiteId")),
                    UtilMisc.toList("-fromDate"));
            webSiteRoles = EntityUtil.filterByDate(webSiteRoles, true);
            GenericValue webSiteRole = EntityUtil.getFirst(webSiteRoles);
            if (webSiteRole != null) {
                toBeStored.add(delegator.makeValue("OrderRole", UtilMisc.toMap("orderId", orderId, "partyId",
                        webSiteRole.get("partyId"), "roleTypeId", "VENDOR")));
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error looking up Vendor for the current Web Site", module);
        }

    }

    // set the order payment info
    List<GenericValue> orderPaymentInfos = UtilGenerics.checkList(context.get("orderPaymentInfo"));
    if (UtilValidate.isNotEmpty(orderPaymentInfos)) {
        Iterator<GenericValue> oppIter = orderPaymentInfos.iterator();
        while (oppIter.hasNext()) {
            GenericValue valueObj = oppIter.next();
            valueObj.set("orderId", orderId);
            if ("OrderPaymentPreference".equals(valueObj.getEntityName())) {
                if (valueObj.get("orderPaymentPreferenceId") == null) {
                    valueObj.set("orderPaymentPreferenceId", delegator.getNextSeqId("OrderPaymentPreference"));
                    valueObj.set("createdDate", UtilDateTime.nowTimestamp());
                    valueObj.set("createdByUserLogin", userLogin.getString("userLoginId"));
                }
                if (valueObj.get("statusId") == null) {
                    valueObj.set("statusId", "PAYMENT_NOT_RECEIVED");
                }
            }
            toBeStored.add(valueObj);
        }
    }

    // store the trackingCodeOrder entities
    List<GenericValue> trackingCodeOrders = UtilGenerics.checkList(context.get("trackingCodeOrders"));
    if (UtilValidate.isNotEmpty(trackingCodeOrders)) {
        Iterator<GenericValue> tkcdordIter = trackingCodeOrders.iterator();
        while (tkcdordIter.hasNext()) {
            GenericValue trackingCodeOrder = tkcdordIter.next();
            trackingCodeOrder.set("orderId", orderId);
            toBeStored.add(trackingCodeOrder);
        }
    }

    // store the OrderTerm entities

    List<GenericValue> orderTerms = UtilGenerics.checkList(context.get("orderTerms"));
    if (UtilValidate.isNotEmpty(orderTerms)) {
        Iterator<GenericValue> orderTermIter = orderTerms.iterator();
        while (orderTermIter.hasNext()) {
            GenericValue orderTerm = orderTermIter.next();
            orderTerm.set("orderId", orderId);
            if (orderTerm.get("orderItemSeqId") == null) {
                orderTerm.set("orderItemSeqId", "_NA_");
            }
            toBeStored.add(orderTerm);
        }
    }

    // if a workEffortId is passed, then prepare a OrderHeaderWorkEffort value
    String workEffortId = (String) context.get("workEffortId");
    if (UtilValidate.isNotEmpty(workEffortId)) {
        GenericValue orderHeaderWorkEffort = delegator.makeValue("OrderHeaderWorkEffort");
        orderHeaderWorkEffort.set("orderId", orderId);
        orderHeaderWorkEffort.set("workEffortId", workEffortId);
        toBeStored.add(orderHeaderWorkEffort);
    }

    try {
        // store line items, etc so that they will be there for the foreign key checks
        delegator.storeAll(toBeStored);

        // START inventory reservation
        // commented when PurchaseOrder not created without shipment
        /*List<String> resErrorMessages = new LinkedList<String>();
        try {
        reserveInventory(delegator, dispatcher, userLogin, locale, orderItemShipGroupInfo, dropShipGroupIds, itemValuesBySeqId,
                orderTypeId, productStoreId, resErrorMessages);
        } catch (GeneralException e) {
        return ServiceUtil.returnError(e.getMessage());
        }
                
        if (resErrorMessages.size() > 0) {
        return ServiceUtil.returnError(resErrorMessages);
        }*/
        // END inventory reservation

        successResult.put("orderId", orderId);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem with order storage or reservations", module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource_error, "OrderErrorCouldNotCreateOrderWriteError", locale)
                        + e.getMessage() + ").");
    }

    return successResult;
}

From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java

/**
 * Get the Alerts which are active for the target date provided.
 *
 * @param target_//from w  w  w.  j  a  va2  s . c  o  m
 *        The target date, typically the date an Auto Run process is
 *        started.
 * @return null if an error, otherwise the list of valid alert definitions.
 */
public AlertRec[] selectAlerts(Timestamp target_) {
    String select = "select al_idseq, name, created_by " + "from sbrext.sn_alert_view_ext "
            + "where al_status <> 'I' AND " + "(auto_freq_unit = 'D' OR "
            + "(auto_freq_unit = 'W' AND auto_freq_value = ?) OR "
            + "(auto_freq_unit = 'M' AND auto_freq_value = ?)) "
            + "order by upper(created_by) asc, upper(name) asc";

    // Get day and date from target to qualify the select.
    GregorianCalendar tdate = new GregorianCalendar();
    tdate.setTimeInMillis(target_.getTime());
    int dayWeek = tdate.get(Calendar.DAY_OF_WEEK);
    int dayMonth = tdate.get(Calendar.DAY_OF_MONTH);

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    AlertRec[] recs = null;
    try {
        // Set SQL arguments
        pstmt = _conn.prepareStatement(select);
        pstmt.setInt(1, dayWeek);
        pstmt.setInt(2, dayMonth);

        // Retrieve all applicable definition ids.
        rs = pstmt.executeQuery();
        Vector<String> list = new Vector<String>();
        while (rs.next()) {
            list.add(rs.getString(1));
        }
        rs.close();
        rs = null;
        pstmt.close();
        pstmt = null;

        // There may be nothing to do.
        if (list.size() == 0)
            recs = new AlertRec[0];
        else {
            // retrieve the full alert definition, we will need it.
            recs = new AlertRec[list.size()];
            int keep = 0;
            int ndx;
            for (ndx = 0; ndx < recs.length; ++ndx) {
                // Be sure we can read the Alert Definition.
                recs[keep] = selectAlert((String) list.get(ndx));
                if (recs[keep] == null)
                    return null;

                // Check the date. We do this here and not in the SQL because
                // 99.99% of the time this will return true and complicating the
                // SQL isn't necessary.
                if (recs[keep].isActive(target_))
                    ++keep;

                // In the RARE situation that the alert is inactive at this
                // point,
                // we reset the object pointer to release the memory.
                else
                    recs[keep] = null;
            }

            // Return the results. It is possible that sometimes the last entry
            // in the
            // list will be null. Consequently the use of the list should be in
            // a loop
            // with the following condition: "cnt < recs.length && recs[cnt] !=
            // null"
            if (keep != ndx) {
                // Only process the ones that are Active.
                AlertRec trecs[] = new AlertRec[keep];
                for (ndx = 0; ndx < keep; ++ndx)
                    trecs[ndx] = recs[ndx];
                recs = trecs;
            }
        }
    } catch (SQLException ex) {
        _errorCode = DBAlertUtil.getSQLErrorCode(ex);
        _errorMsg = _errorCode + ": " + select + "\n\n" + ex.toString();
        _logger.error(_errorMsg);
    } finally {
        closeCursors(pstmt, rs);
    }
    return recs;
}

From source file:com.funambol.foundation.items.dao.PIMContactDAO.java

/**
 * Adds a contact. If necessary, a new ID is generated and set in the
 * ContactWrapper.//from  w ww.ja va2  s  .  c  o m
 *
 * @param cw as a ContactWrapper object, usually without an ID set.
 * @throws DAOException
 *
 * @see ContactWrapper
 */
public void addItem(ContactWrapper cw) throws DAOException {
    if (log.isTraceEnabled()) {
        log.trace("Storing a contact item...");
    }

    Connection con = null;
    PreparedStatement ps = null;

    long id = 0;
    int type = 0;

    PersonalDetail personalDetail = null;
    BusinessDetail businessDetail = null;
    Address homeAddressBook = null;
    Address workAddressBook = null;
    Address otherAddressBook = null;

    Name name = null;
    Phone phone = null;
    Email email = null;
    WebPage webPage = null;

    List<WebPage> webPages = new ArrayList<WebPage>();
    List<Email> emails = new ArrayList<Email>();
    List<Phone> phones = new ArrayList<Phone>();
    List<String[]> labels = new ArrayList<String[]>();

    String webPageType = null;

    Short importance = null;
    Short sensitivity = null;
    String mileage = null;
    String subject = null;
    String folder = null;
    String anniversary = null;
    String firstName = null;
    String middleName = null;
    String lastName = null;
    String displayName = null;
    String birthday = null;
    String categories = null;
    String gender = null;
    String hobbies = null;
    String initials = null;
    String languages = null;
    String nickName = null;
    String spouse = null;
    String suffix = null;
    String assistant = null;
    String officeLocation = null;
    String company = null;
    String companies = null;
    String department = null;
    String manager = null;
    String role = null;
    String children = null;
    String salutation = null;
    String sId = null;

    Timestamp lastUpdate = cw.getLastUpdate();
    if (lastUpdate == null) {
        lastUpdate = new Timestamp(System.currentTimeMillis());
    }

    try {

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        sId = cw.getId();
        if (sId == null) { // ...as it should be
            sId = getNextID();
            cw.setId(sId);
        }
        id = Long.parseLong(sId);

        Contact c = cw.getContact();
        personalDetail = c.getPersonalDetail();
        businessDetail = c.getBusinessDetail();
        name = c.getName();

        if (personalDetail != null) {
            homeAddressBook = personalDetail.getAddress();
            otherAddressBook = personalDetail.getOtherAddress();
            webPages.addAll(personalDetail.getWebPages());
            emails.addAll(personalDetail.getEmails());
            phones.addAll(personalDetail.getPhones());
        }

        if (businessDetail != null) {
            workAddressBook = businessDetail.getAddress();
            webPages.addAll(businessDetail.getWebPages());
            emails.addAll(businessDetail.getEmails());
            phones.addAll(businessDetail.getPhones());
            companies = businessDetail.getCompanies();

        }

        importance = c.getImportance();
        sensitivity = c.getSensitivity();
        mileage = c.getMileage();
        subject = c.getSubject();
        languages = c.getLanguages();

        categories = Property.stringFrom(c.getCategories());
        folder = c.getFolder();

        if (personalDetail != null) {
            anniversary = personalDetail.getAnniversary();
            birthday = personalDetail.getBirthday();
            children = personalDetail.getChildren();
            spouse = personalDetail.getSpouse();
            hobbies = personalDetail.getHobbies();
            gender = personalDetail.getGender();
        }

        if (businessDetail != null) {
            assistant = businessDetail.getAssistant();
            manager = businessDetail.getManager();
            officeLocation = businessDetail.getOfficeLocation();
            company = Property.stringFrom(businessDetail.getCompany());
            department = Property.stringFrom(businessDetail.getDepartment());
            role = Property.stringFrom(businessDetail.getRole());
        }

        if (name != null) {
            firstName = Property.stringFrom(name.getFirstName());
            middleName = Property.stringFrom(name.getMiddleName());
            lastName = Property.stringFrom(name.getLastName());
            displayName = Property.stringFrom(name.getDisplayName());
            initials = Property.stringFrom(name.getInitials());
            nickName = Property.stringFrom(name.getNickname());
            suffix = Property.stringFrom(name.getSuffix());
            salutation = Property.stringFrom(name.getSalutation());
        }

        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT);

        //
        // GENERAL
        //

        if (log.isTraceEnabled()) {
            log.trace("Preparing statement with ID " + id);
        }
        ps.setLong(1, id);

        if (log.isTraceEnabled()) {
            log.trace("Preparing statement with user ID " + userId);
        }
        ps.setString(2, userId);

        ps.setLong(3, lastUpdate.getTime());
        ps.setString(4, String.valueOf(Def.PIM_STATE_NEW));

        boolean hasPhoto = false;
        Photo photo = personalDetail.getPhotoObject();
        if (photo != null && (photo.getImage() != null || photo.getUrl() != null)) {
            hasPhoto = true;
            ps.setShort(5, photo.getImage() != null ? ContactWrapper.PHOTO_IMAGE : ContactWrapper.PHOTO_URL);
        } else if (photo != null) {
            ps.setShort(5, ContactWrapper.EMPTY_PHOTO);
        } else {
            ps.setNull(5, Types.SMALLINT);
        }

        //
        // CONTACT DETAILS
        //

        if (importance != null) {
            ps.setShort(6, importance.shortValue());
        } else {
            ps.setNull(6, Types.SMALLINT);
        }

        if (sensitivity != null) {
            ps.setShort(7, sensitivity.shortValue());
        } else {
            ps.setNull(7, Types.SMALLINT);
        }

        ps.setString(8, StringUtils.left(subject, SQL_SUBJECT_DIM));
        ps.setString(9, StringUtils.left(folder, SQL_FOLDER_DIM));

        //
        // PERSONAL DETAILS
        //

        ps.setString(10, StringUtils.left(anniversary, SQL_ANNIVERSARY_DIM));
        ps.setString(11, StringUtils.left(firstName, SQL_FIRSTNAME_DIM));
        ps.setString(12, StringUtils.left(middleName, SQL_MIDDLENAME_DIM));
        ps.setString(13, StringUtils.left(lastName, SQL_LASTNAME_DIM));
        ps.setString(14, StringUtils.left(displayName, SQL_DISPLAYNAME_DIM));
        ps.setString(15, StringUtils.left(birthday, SQL_BIRTHDAY_DIM));

        if (c.getNotes() != null && c.getNotes().size() > 0) {
            String noteValue = ((Note) c.getNotes().get(0)).getPropertyValueAsString();
            ps.setString(16, StringUtils.left(noteValue, SQL_NOTE_DIM));
        } else {
            ps.setString(16, null);
        }

        ps.setString(17, StringUtils.left(categories, SQL_CATEGORIES_DIM));
        ps.setString(18, StringUtils.left(children, SQL_CHILDREN_DIM));
        ps.setString(19, StringUtils.left(hobbies, SQL_HOBBIES_DIM));
        ps.setString(20, StringUtils.left(initials, SQL_INITIALS_DIM));
        ps.setString(21, StringUtils.left(languages, SQL_LANGUAGES_DIM));
        ps.setString(22, StringUtils.left(nickName, SQL_NICKNAME_DIM));
        ps.setString(23, StringUtils.left(spouse, SQL_SPOUSE_DIM));
        ps.setString(24, StringUtils.left(suffix, SQL_SUFFIX_DIM));
        ps.setString(25, StringUtils.left(salutation, SQL_SALUTATION_DIM));

        //
        // BUSINESS DETAILS
        //
        ps.setString(26, StringUtils.left(assistant, SQL_ASSISTANT_DIM));
        ps.setString(27, StringUtils.left(company, SQL_COMPANY_DIM));
        ps.setString(28, StringUtils.left(department, SQL_DEPARTMENT_DIM));

        if (businessDetail.getTitles() != null && businessDetail.getTitles().size() > 0) {
            String titleValue = ((Title) businessDetail.getTitles().get(0)).getPropertyValueAsString();
            ps.setString(29, StringUtils.left(titleValue, SQL_TITLE_DIM));
        } else {
            ps.setString(29, null);
        }

        ps.setString(30, StringUtils.left(manager, SQL_MANAGER_DIM));
        if (mileage != null && mileage.length() > SQL_MILEAGE_DIM) {
            mileage = mileage.substring(0, SQL_MILEAGE_DIM);
        }
        ps.setString(31, StringUtils.left(mileage, SQL_MILEAGE_DIM));
        ps.setString(32, StringUtils.left(officeLocation, SQL_OFFICELOCATION_DIM));
        ps.setString(33, StringUtils.left(role, SQL_ROLE_DIM));
        ps.setString(34, StringUtils.left(companies, SQL_COMPANIES_DIM));
        ps.setString(35, StringUtils.left(gender, SQL_GENDER_DIM));

        ps.executeUpdate();

        DBTools.close(null, ps, null);

        //
        // emails
        //
        if (!emails.isEmpty()) {

            ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = emails.size(); i < l; i++) {

                email = emails.get(i);

                type = getContactEmailItemTypeFromEmailPropertyType(email.getEmailType());
                // Unknown property: saves nothing
                if (TYPE_UNDEFINED == type)
                    continue;

                String emailValue = email.getPropertyValueAsString();

                if (emailValue != null && emailValue.length() != 0) {
                    if (emailValue.length() > SQL_EMAIL_DIM) {
                        emailValue = emailValue.substring(0, SQL_EMAIL_DIM);
                    }
                    ps.setLong(1, id);
                    ps.setInt(2, type);
                    ps.setString(3, emailValue);

                    ps.executeUpdate();
                }

            }

            DBTools.close(null, ps, null);

        }

        //
        // phones
        //
        if (!phones.isEmpty()) {

            ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = phones.size(); i < l; i++) {

                phone = phones.get(i);

                type = getContactPhoneItemTypeFromPhonePropertyType(phone.getPhoneType());
                // Unknown property: saves nothing
                if (TYPE_UNDEFINED == type)
                    continue;

                String phoneValue = phone.getPropertyValueAsString();
                if (phoneValue != null && phoneValue.length() != 0) {
                    if (phoneValue.length() > SQL_PHONE_DIM) {
                        phoneValue = phoneValue.substring(0, SQL_PHONE_DIM);
                    }

                    ps.setLong(1, id);
                    ps.setInt(2, type);
                    ps.setString(3, phoneValue);

                    ps.executeUpdate();
                }

            }

            DBTools.close(null, ps, null);

        }

        //
        // webPages
        //
        if (!webPages.isEmpty()) {

            ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = webPages.size(); i < l; i++) {

                webPage = webPages.get(i);

                webPageType = webPage.getWebPageType();

                if ((FIELD_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_WEB_PAGE;
                } else if ((FIELD_HOME_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_HOME_WEB_PAGE;
                } else if ((FIELD_BUSINESS_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_BUSINESS_WEB_PAGE;
                } else {
                    //
                    // Unknown property: saves nothing
                    //
                    continue;
                }

                String webPageValue = webPage.getPropertyValueAsString();
                if (webPageValue != null && webPageValue.length() != 0) {
                    if (webPageValue.length() > SQL_WEBPAGE_DIM) {
                        webPageValue = webPageValue.substring(0, SQL_WEBPAGE_DIM);
                    }

                    ps.setLong(1, id);
                    ps.setInt(2, type);
                    ps.setString(3, webPageValue);

                    ps.executeUpdate();
                }

            }

            DBTools.close(null, ps, null);

        }

        if (homeAddressBook != null) {

            String homeStreet = Property.stringFrom(homeAddressBook.getStreet());
            String homeCity = Property.stringFrom(homeAddressBook.getCity());
            String homePostalCode = Property.stringFrom(homeAddressBook.getPostalCode());
            String homeState = Property.stringFrom(homeAddressBook.getState());
            String homeCountry = Property.stringFrom(homeAddressBook.getCountry());
            String homePostalOfficeAddress = Property.stringFrom(homeAddressBook.getPostOfficeAddress());
            String homeExtendedAddress = Property.stringFrom(homeAddressBook.getExtendedAddress());

            String homeLabel = Property.stringFrom(homeAddressBook.getLabel());
            if (homeLabel != null) {
                String[] label = { homeLabel, FIELD_HOME_LABEL };
                labels.add(label);
            }

            String[] homeAddressFields = { homeStreet, homeCity, homePostalCode, homeCountry, homeState,
                    homePostalOfficeAddress, homeExtendedAddress };

            if (!hasOnlyEmptyOrNullContent(homeAddressFields)) {

                ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                ps.setLong(1, id);
                ps.setInt(2, ADDRESS_TYPE_HOME);
                ps.setString(3, replaceNewLine(StringUtils.left(homeStreet, SQL_STREET_DIM)));
                ps.setString(4, StringUtils.left(homeCity, SQL_CITY_DIM));
                ps.setString(5, StringUtils.left(homeState, SQL_STATE_DIM));
                ps.setString(6, StringUtils.left(homePostalCode, SQL_POSTALCODE_DIM));
                ps.setString(7, StringUtils.left(homeCountry, SQL_COUNTRY_DIM));
                ps.setString(8, StringUtils.left(homePostalOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM));
                ps.setString(9, StringUtils.left(homeExtendedAddress, SQL_EXTENDEDADDRESS_DIM));

                ps.executeUpdate();

                DBTools.close(null, ps, null);
            }
        }

        if (otherAddressBook != null) {

            String otherStreet = Property.stringFrom(otherAddressBook.getStreet());
            String otherCity = Property.stringFrom(otherAddressBook.getCity());
            String otherPostalCode = Property.stringFrom(otherAddressBook.getPostalCode());
            String otherState = Property.stringFrom(otherAddressBook.getState());
            String otherCountry = Property.stringFrom(otherAddressBook.getCountry());
            String otherPostalOfficeAddress = Property.stringFrom(otherAddressBook.getPostOfficeAddress());
            String otherExtendedAddress = Property.stringFrom(otherAddressBook.getExtendedAddress());

            String otherLabel = Property.stringFrom(otherAddressBook.getLabel());
            if (otherLabel != null) {
                String[] label = { otherLabel, FIELD_OTHER_LABEL };
                labels.add(label);
            }

            String[] otherAddressFields = { otherStreet, otherCity, otherPostalCode, otherCountry, otherState,
                    otherPostalOfficeAddress, otherExtendedAddress };

            if (!hasOnlyEmptyOrNullContent(otherAddressFields)) {

                ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                ps.setLong(1, id);
                ps.setInt(2, ADDRESS_TYPE_OTHER);
                ps.setString(3, replaceNewLine(StringUtils.left(otherStreet, SQL_STREET_DIM)));
                ps.setString(4, StringUtils.left(otherCity, SQL_CITY_DIM));
                ps.setString(5, StringUtils.left(otherState, SQL_STATE_DIM));
                ps.setString(6, StringUtils.left(otherPostalCode, SQL_POSTALCODE_DIM));
                ps.setString(7, StringUtils.left(otherCountry, SQL_COUNTRY_DIM));
                ps.setString(8, StringUtils.left(otherPostalOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM));
                ps.setString(9, StringUtils.left(otherExtendedAddress, SQL_EXTENDEDADDRESS_DIM));

                ps.executeUpdate();

                DBTools.close(null, ps, null);

            }
        }

        if (workAddressBook != null) {

            String workStreet = Property.stringFrom(workAddressBook.getStreet());
            String workCity = Property.stringFrom(workAddressBook.getCity());
            String workPostalCode = Property.stringFrom(workAddressBook.getPostalCode());
            String workState = Property.stringFrom(workAddressBook.getState());
            String workCountry = Property.stringFrom(workAddressBook.getCountry());
            String workPostalOfficeAddress = Property.stringFrom(workAddressBook.getPostOfficeAddress());
            String workExtendedAddress = Property.stringFrom(workAddressBook.getExtendedAddress());

            String workLabel = Property.stringFrom(workAddressBook.getLabel());
            if (workLabel != null) {
                String[] label = { workLabel, FIELD_BUSINESS_LABEL };
                labels.add(label);
            }

            String[] workAddressFields = { workStreet, workCity, workPostalCode, workCountry, workState,
                    workPostalOfficeAddress, workExtendedAddress };

            if (!hasOnlyEmptyOrNullContent(workAddressFields)) {

                ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                ps.setLong(1, id);
                ps.setInt(2, ADDRESS_TYPE_WORK);
                ps.setString(3, replaceNewLine(StringUtils.left(workStreet, SQL_STREET_DIM)));
                ps.setString(4, StringUtils.left(workCity, SQL_CITY_DIM));
                ps.setString(5, StringUtils.left(workState, SQL_STATE_DIM));
                ps.setString(6, StringUtils.left(workPostalCode, SQL_POSTALCODE_DIM));
                ps.setString(7, StringUtils.left(workCountry, SQL_COUNTRY_DIM));
                ps.setString(8, StringUtils.left(workPostalOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM));
                ps.setString(9, StringUtils.left(workExtendedAddress, SQL_EXTENDEDADDRESS_DIM));

                ps.executeUpdate();

                DBTools.close(null, ps, null);
            }

        }

        //
        // labels
        //
        if (!labels.isEmpty()) {

            ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = labels.size(); i < l; i++) {

                String[] label = labels.get(i);

                String labelType = label[1];

                if ((FIELD_HOME_LABEL).equals(labelType)) {
                    type = TYPE_HOME_LABEL;
                } else if ((FIELD_BUSINESS_LABEL).equals(labelType)) {
                    type = TYPE_BUSINESS_LABEL;
                } else if ((FIELD_OTHER_LABEL).equals(labelType)) {
                    type = TYPE_OTHER_LABEL;
                } else {
                    //
                    // Unknown property: saves nothing
                    //
                    continue;
                }

                String labelValue = label[0];
                if (labelValue != null && labelValue.length() != 0) {
                    if (labelValue.length() > SQL_LABEL_DIM) {
                        labelValue = labelValue.substring(0, SQL_LABEL_DIM);
                    }

                    ps.setLong(1, id);
                    ps.setInt(2, type);
                    ps.setString(3, labelValue);

                    ps.executeUpdate();
                }

            }

            DBTools.close(null, ps, null);

        }

        if (hasPhoto) {
            insertPhoto(con, Long.parseLong(cw.getId()), photo);
        }

    } catch (Exception e) {
        throw new DAOException("Error adding contact.", e);
    } finally {
        DBTools.close(con, ps, null);
    }

    if (log.isTraceEnabled()) {
        log.trace("Added item with ID '" + id + "'");
    }
}

From source file:org.openmicroscopy.shoola.env.data.OMEROGateway.java

/**
 * Returns the collection of annotations of a given type.
 *
 * @param ctx The security context./*  w  w w .  j a  v  a  2s  . c  o m*/
 * @param annotationType   The type of annotation.
 * @param terms            The terms to search for.
 * @param start            The lower bound of the time interval
 *                      or <code>null</code>.
 * @param end            The lower bound of the time interval
 *                      or <code>null</code>.
 * @param exp            The experimenter who annotated the object.
 * @return See above.
 * @throws DSOutOfServiceException  If the connection is broken, or logged
 *                                  in.
 * @throws DSAccessException        If an error occurred while trying to
 *                                  retrieve data from OMEDS service.
 */
List filterBy(SecurityContext ctx, Class annotationType, List<String> terms, Timestamp start, Timestamp end,
        ExperimenterData exp) throws DSOutOfServiceException, DSAccessException {
    Connector c = getConnector(ctx, true, false);
    SearchPrx service = null;
    try {
        service = c.getSearchService();
        if (start != null && end != null)
            service.onlyAnnotatedBetween(omero.rtypes.rtime(start.getTime()),
                    omero.rtypes.rtime(end.getTime()));
        if (exp != null) {
            Details d = new DetailsI();
            d.setOwner(exp.asExperimenter());
        }

        List<String> t = prepareTextSearch(terms, service);
        service.onlyType(convertPojos(annotationType).getName());
        List rType = new ArrayList();
        //service.bySomeMustNone(fSome, fMust, fNone);
        service.bySomeMustNone(t, null, null);
        Object size = handleSearchResult(convertTypeForSearch(annotationType), rType, service);
        if (size instanceof Integer)
            rType = new ArrayList();
        return rType;
    } catch (Exception e) {
        handleException(e, "Filtering by annotation not valid");
    } finally {
        if (service != null)
            c.close(service);
    }
    return new ArrayList();
}

From source file:org.openmicroscopy.shoola.env.data.OMEROGateway.java

/**
 * Searches the images acquired or created during a given period of time.
 *
 * @param ctx The security context.//from  w w w  . j  a  v  a 2s.  c o  m
 * @param context The context of the search.
 * @return See above.
 * @throws DSOutOfServiceException  If the connection is broken, or logged
 *                                  in.
 * @throws DSAccessException        If an error occurred while trying to
 *                                  retrieve data from OMEDS service.
 */
Set searchByTime(SecurityContext ctx, SearchDataContext context)
        throws DSOutOfServiceException, DSAccessException {
    Connector c = getConnector(ctx, true, false);
    ParametersI param = new ParametersI();
    param.map = new HashMap<String, RType>();
    StringBuffer buf = new StringBuffer();
    buf.append("select img from Image as img ");
    buf.append("left outer join fetch img.pixels as pix ");
    buf.append("left outer join fetch pix.pixelsType as pt ");
    buf.append("left outer join fetch img.details.owner as owner ");
    boolean condition = false;
    Timestamp start = context.getStart();
    Timestamp end = context.getEnd();
    //Sets the time
    switch (context.getTimeIndex()) {
    case SearchDataContext.CREATION_TIME:
        if (start != null) {
            condition = true;
            buf.append("where img.acquisitionDate > :start ");
            param.map.put("start", omero.rtypes.rtime(start.getTime()));
            if (end != null) {
                param.map.put("end", omero.rtypes.rtime(end.getTime()));
                buf.append("and img.acquisitionDate < :end ");
            }
        } else {
            if (end != null) {
                condition = true;
                param.map.put("end", omero.rtypes.rtime(end.getTime()));
                buf.append("where img.acquisitionDate < :end ");
            }
        }
        break;
    case SearchDataContext.MODIFICATION_TIME:
        if (start != null) {
            condition = true;
            param.map.put("start", omero.rtypes.rtime(start.getTime()));
            buf.append("where img.details.creationEvent.time > :start ");
            if (end != null) {
                param.map.put("end", omero.rtypes.rtime(end.getTime()));
                buf.append("and img.details.creationEvent.time < :end ");
            }
        } else {
            if (end != null) {
                condition = true;
                param.map.put("end", omero.rtypes.rtime(end.getTime()));
                buf.append("where img.details.creationEvent.time < :end ");
            }
        }
        break;
    case SearchDataContext.ANNOTATION_TIME:
    }
    try {
        IQueryPrx service = c.getQueryService();
        List<ExperimenterData> l = context.getOwners();
        List<Long> ids = new ArrayList<Long>();
        if (l != null) {
            Iterator<ExperimenterData> i = l.iterator();
            while (i.hasNext()) {
                ids.add(i.next().getId());
            }
        }
        param.addLongs("ids", ids);
        if (condition) {
            buf.append(" and owner.id in (:ids)");
        } else
            buf.append("where owner.id in (:ids)");

        return PojoMapper.asDataObjects(service.findAllByQuery(buf.toString(), param));
    } catch (Throwable e) {
        handleException(e, "Cannot retrieve the images.");
    }

    return new HashSet();
}

From source file:org.openmicroscopy.shoola.env.data.OMEROGateway.java

/**
 * Searches for data.//from w  w w  . j a va 2s.  com
 *
 * @param ctx The security context.
 * @param context The context of search.
 * @return The found objects.
 * @throws DSOutOfServiceException  If the connection is broken, or logged
 *                                  in.
 * @throws DSAccessException        If an error occurred while trying to
 *                                  retrieve data from OMEDS service.
 */
Object performSearch(SecurityContext ctx, SearchDataContext context)
        throws DSOutOfServiceException, DSAccessException {
    Map<Integer, Object> results = new HashMap<Integer, Object>();
    List<Class> types = context.getTypes();
    List<Integer> scopes = context.getScope();
    if (CollectionUtils.isEmpty(types))
        return new HashMap();

    Connector c = getConnector(ctx, true, false);
    SearchPrx service = null;
    try {
        service = c.getSearchService();
        service.clearQueries();
        service.setAllowLeadingWildcard(true);
        service.setCaseSentivice(context.isCaseSensitive());
        Timestamp start = context.getStart();
        Timestamp end = context.getEnd();
        //Sets the time
        if (start != null || end != null) {
            switch (context.getTimeIndex()) {
            case SearchDataContext.CREATION_TIME:
                if (start != null && end != null)
                    service.onlyCreatedBetween(omero.rtypes.rtime(start.getTime()),
                            omero.rtypes.rtime(end.getTime()));
                else if (start != null && end == null)
                    service.onlyCreatedBetween(omero.rtypes.rtime(start.getTime()), null);
                else if (start == null && end != null)
                    service.onlyCreatedBetween(null, omero.rtypes.rtime(end.getTime()));
                break;
            case SearchDataContext.MODIFICATION_TIME:
                if (start != null && end != null)
                    service.onlyModifiedBetween(omero.rtypes.rtime(start.getTime()),
                            omero.rtypes.rtime(end.getTime()));
                else if (start != null && end == null)
                    service.onlyModifiedBetween(omero.rtypes.rtime(start.getTime()), null);
                else if (start == null && end != null)
                    service.onlyModifiedBetween(null, omero.rtypes.rtime(end.getTime()));
                break;
            case SearchDataContext.ANNOTATION_TIME:
                if (start != null && end != null)
                    service.onlyAnnotatedBetween(omero.rtypes.rtime(start.getTime()),
                            omero.rtypes.rtime(end.getTime()));
                else if (start != null && end == null)
                    service.onlyAnnotatedBetween(omero.rtypes.rtime(start.getTime()), null);
                else if (start == null && end != null)
                    service.onlyAnnotatedBetween(null, omero.rtypes.rtime(end.getTime()));
            }
        }
        List<ExperimenterData> users = context.getOwners();
        Iterator i;
        ExperimenterData exp;
        Details d;
        //owner
        List<Details> owners = new ArrayList<Details>();
        if (users != null && users.size() > 0) {
            i = users.iterator();
            while (i.hasNext()) {
                exp = (ExperimenterData) i.next();
                d = new DetailsI();
                d.setOwner(exp.asExperimenter());
                owners.add(d);
            }
        }

        List<String> some = prepareTextSearch(context.getSome(), service);
        List<String> must = prepareTextSearch(context.getMust(), service);
        List<String> none = prepareTextSearch(context.getNone(), service);

        List<String> supportedTypes = new ArrayList<String>();
        i = types.iterator();
        while (i.hasNext())
            supportedTypes.add(convertPojos((Class) i.next()).getName());

        List rType;

        Object size;
        Integer key;
        i = scopes.iterator();
        while (i.hasNext())
            results.put((Integer) i.next(), new ArrayList());

        Iterator<Details> owner;
        i = scopes.iterator();
        List<String> fSome = null, fMust = null, fNone = null;
        List<String> fSomeSec = null, fMustSec = null, fNoneSec = null;
        service.onlyType(Image.class.getName());
        while (i.hasNext()) {
            key = (Integer) i.next();
            rType = (List) results.get(key);
            size = null;
            if (key == SearchDataContext.TAGS) {
                fSome = formatText(some, "tag");
                fMust = formatText(must, "tag");
                fNone = formatText(none, "tag");
            } else if (key == SearchDataContext.NAME) {
                fSome = formatText(some, "name");
                fMust = formatText(must, "name");
                fNone = formatText(none, "name");
            } else if (key == SearchDataContext.DESCRIPTION) {
                fSome = formatText(some, "description");
                fMust = formatText(must, "description");
                fNone = formatText(none, "description");
            } else if (key == SearchDataContext.FILE_ANNOTATION) {
                fSome = formatText(some, "file.name");
                fMust = formatText(must, "file.name");
                fNone = formatText(none, "file.name");
                fSomeSec = formatText(some, "file.contents");
                fMustSec = formatText(must, "file.contents");
                fNoneSec = formatText(none, "file.contents");
            } else if (key == SearchDataContext.TEXT_ANNOTATION) {
                fSome = formatText(some, "annotation", "NOT", "tag");
                fMust = formatText(must, "annotation", "NOT", "tag");
                fNone = formatText(none, "annotation", "NOT", "tag");
            } else if (key == SearchDataContext.URL_ANNOTATION) {
                fSome = formatText(some, "url");
                fMust = formatText(must, "url");
                fNone = formatText(none, "url");
            } else if (key == SearchDataContext.ID) {
                fSome = formatText(some, "id");
                fMust = formatText(must, "id");
                fNone = formatText(none, "id");
            } else {
                fSome = formatText(some, "");
                fMust = formatText(must, "");
                fNone = formatText(none, "");
            }
            owner = owners.iterator();
            //if (fSome != null) {
            //while (owner.hasNext()) {
            //d = owner.next();
            //service.onlyOwnedBy(d);
            service.bySomeMustNone(fSome, fMust, fNone);
            size = handleSearchResult(convertTypeForSearch(Image.class), rType, service);
            if (size instanceof Integer)
                results.put(key, size);
            service.clearQueries();
            if (!(size instanceof Integer) && fSomeSec != null && fSomeSec.size() > 0) {
                service.bySomeMustNone(fSomeSec, fMustSec, fNoneSec);
                size = handleSearchResult(convertTypeForSearch(Image.class), rType, service);
                if (size instanceof Integer)
                    results.put(key, size);
                service.clearQueries();
            }
            //}
            //}
        }
        return results;
    } catch (Throwable e) {
        handleException(e, "Cannot perform the search.");
    } finally {
        if (service != null)
            c.close(service);
    }
    return null;
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public int wiederholendeLoseAnlegen(TheClientDto theClientDto) {

    int iAnzahlAngelegterLose = 0;
    DateFormatSymbols symbols = new DateFormatSymbols(theClientDto.getLocUi());
    String[] defaultMonths = symbols.getMonths();
    int iStandarddurchlaufzeit = 0;
    try {//from  ww  w  .  ja va2s .  c o m
        ParametermandantDto parameter = getParameterFac().getMandantparameter(theClientDto.getMandant(),
                ParameterFac.KATEGORIE_FERTIGUNG, ParameterFac.INTERNEBESTELLUNG_DEFAULTDURCHLAUFZEIT);
        iStandarddurchlaufzeit = ((Integer) parameter.getCWertAsObject()).intValue();
    } catch (RemoteException ex2) {
        throwEJBExceptionLPRespectOld(ex2);
    }

    Session session = FLRSessionFactory.getFactory().openSession();

    Criteria crit = session.createCriteria(FLRWiederholendelose.class);

    crit.add(Restrictions.eq("mandant_c_nr", theClientDto.getMandant()));
    crit.add(Restrictions.eq(FertigungFac.FLR_WIEDERHOLENDELOSE_B_VERSTECKT, Helper.boolean2Short(false)));

    List<?> resultList = crit.list();
    Iterator<?> resultListIterator = resultList.iterator();
    while (resultListIterator.hasNext()) {
        FLRWiederholendelose flrWiederholendelose = (FLRWiederholendelose) resultListIterator.next();

        // Naechster faelliger Termin nach Heute
        Calendar cBeginn = Calendar.getInstance();
        cBeginn.setTimeInMillis(flrWiederholendelose.getT_termin().getTime());

        String intervall = flrWiederholendelose.getAuftragwiederholungsintervall_c_nr();

        Timestamp tHeute = Helper.cutTimestamp(new Timestamp(System.currentTimeMillis()));

        while (cBeginn.getTimeInMillis() < tHeute.getTime()) {

            if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_2WOECHENTLICH)) {
                cBeginn.set(Calendar.DAY_OF_MONTH, cBeginn.get(Calendar.DAY_OF_MONTH) + 14);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_WOECHENTLICH)) {
                cBeginn.set(Calendar.DAY_OF_MONTH, cBeginn.get(Calendar.DAY_OF_MONTH) + 7);
            }

            if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_JAHR)) {
                cBeginn.set(Calendar.YEAR, cBeginn.get(Calendar.YEAR) + 1);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_2JAHR)) {
                cBeginn.set(Calendar.YEAR, cBeginn.get(Calendar.YEAR) + 2);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_3JAHR)) {
                cBeginn.set(Calendar.YEAR, cBeginn.get(Calendar.YEAR) + 3);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_4JAHR)) {
                cBeginn.set(Calendar.YEAR, cBeginn.get(Calendar.YEAR) + 4);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_5JAHR)) {
                cBeginn.set(Calendar.YEAR, cBeginn.get(Calendar.YEAR) + 5);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_MONATLICH)) {
                cBeginn.set(Calendar.MONTH, cBeginn.get(Calendar.MONTH) + 1);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_QUARTAL)) {
                cBeginn.set(Calendar.MONTH, cBeginn.get(Calendar.MONTH) + 3);
            }
        }

        Timestamp tBeginndatumFuerLos = new Timestamp(cBeginn.getTimeInMillis());
        // Voreilende Tage abziehen

        String monatsname = defaultMonths[cBeginn.get(Calendar.MONTH)];
        int iJahr = cBeginn.get(Calendar.YEAR);

        int iTageVoreilend = flrWiederholendelose.getI_tagevoreilend();
        cBeginn.set(Calendar.DAY_OF_MONTH, cBeginn.get(Calendar.DAY_OF_MONTH) - iTageVoreilend);

        Timestamp tAnlagedatum = new Timestamp(cBeginn.getTimeInMillis());

        if (tAnlagedatum.before(tHeute) || tAnlagedatum.equals(tHeute)) {
            // try {
            Query query = em.createNamedQuery("LosfindWiederholendeloseIIdTProduktionsbeginnMandantCNr");
            query.setParameter(1, flrWiederholendelose.getI_id());
            query.setParameter(2, tBeginndatumFuerLos);
            query.setParameter(3, theClientDto.getMandant());
            Collection<?> cl = query.getResultList();
            // if (cl.isEmpty()) {
            // throw new EJBExceptionLP(EJBExceptionLP.FEHLER, null);
            // }
            LosDto[] lose = assembleLosDtos(cl);

            // Wenn noch nicht angelegt
            if (lose.length == 0) {

                WiederholendeloseDto dto = wiederholendeloseFindByPrimaryKey(flrWiederholendelose.getI_id());
                String projektname = "";
                if (dto.getCProjekt() != null) {
                    projektname += dto.getCProjekt() + " ";
                }
                projektname += monatsname + " " + iJahr;

                if (projektname.length() > 50) {
                    projektname = projektname.substring(0, 49);
                }

                LosDto losDto = new LosDto();
                losDto.setWiederholendeloseIId(dto.getIId());
                losDto.setCProjekt(projektname);
                losDto.setFertigungsgruppeIId(dto.getFertigungsgruppeIId());
                losDto.setKostenstelleIId(dto.getKostenstelleIId());
                losDto.setLagerIIdZiel(dto.getLagerIIdZiel());
                losDto.setMandantCNr(theClientDto.getMandant());
                losDto.setNLosgroesse(dto.getNLosgroesse());
                losDto.setPartnerIIdFertigungsort(dto.getPartnerIIdFertigungsort());
                losDto.setStuecklisteIId(dto.getStuecklisteIId());
                losDto.setTProduktionsbeginn(new java.sql.Date(tBeginndatumFuerLos.getTime()));

                // Produktionsende

                try {

                    int laufzeit = iStandarddurchlaufzeit;
                    if (dto.getStuecklisteIId() != null) {
                        StuecklisteDto stuecklisteDto = getStuecklisteFac()
                                .stuecklisteFindByPrimaryKey(dto.getStuecklisteIId(), theClientDto);
                        if (stuecklisteDto.getNDefaultdurchlaufzeit() != null) {
                            laufzeit = stuecklisteDto.getNDefaultdurchlaufzeit().intValue();
                        }
                    }
                    Calendar cTemp = Calendar.getInstance();
                    cTemp.setTimeInMillis(tBeginndatumFuerLos.getTime());
                    cTemp.set(Calendar.DAY_OF_MONTH, cTemp.get(Calendar.DAY_OF_MONTH) + laufzeit);
                    losDto.setTProduktionsende(new java.sql.Date(cTemp.getTime().getTime()));
                    context.getBusinessObject(FertigungFac.class).createLos(losDto, theClientDto);
                } catch (RemoteException ex1) {
                    throwEJBExceptionLPRespectOld(ex1);
                }

                iAnzahlAngelegterLose++;
            }
            // }
            // catch (FinderException ex) {
            // throw new EJBExceptionLP(EJBExceptionLP.FEHLER, ex);
            // }

        }

    }

    return iAnzahlAngelegterLose;
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

public ArrayList<LosAusAuftragDto> holeAlleMoeglichenUnterloseEinerStueckliste(Integer artikelIId,
        BigDecimal zielmenge, int stdVorlaufzeit, Timestamp tLetzterBeginn, ArrayList<LosAusAuftragDto> losDtos,
        AuftragDto auftragDto, BigDecimal bdLosgroesse, TheClientDto theClientDto) {
    try {/* w w w.  j a  v a2s . c  om*/
        StuecklisteDto stuecklisteDto = getStuecklisteFac()
                .stuecklisteFindByMandantCNrArtikelIIdOhneExc(artikelIId, theClientDto);

        if (stuecklisteDto != null && !stuecklisteDto.getStuecklisteartCNr()
                .equals(StuecklisteFac.STUECKLISTEART_HILFSSTUECKLISTE)) {
            ArrayList<?> stuecklisteAufegloest = getStuecklisteFac().getStrukturDatenEinerStueckliste(
                    stuecklisteDto.getIId(), theClientDto,
                    StuecklisteReportFac.REPORT_STUECKLISTE_OPTION_SORTIERUNG_ARTIKELNR, 0, null, false, true,
                    zielmenge, null, true);

            Timestamp tEnde = Helper.addiereTageZuTimestamp(tLetzterBeginn, -stdVorlaufzeit);

            if (stuecklisteDto.getNDefaultdurchlaufzeit() == null) {
                stuecklisteDto.setNDefaultdurchlaufzeit(new BigDecimal(0));
            }
            Timestamp tBeginn = Helper.addiereTageZuTimestamp(tEnde,
                    -stuecklisteDto.getNDefaultdurchlaufzeit().intValue());

            LosAusAuftragDto laDto = new LosAusAuftragDto();

            LosDto losDto = new LosDto();

            losDto.setTProduktionsbeginn(new java.sql.Date(tBeginn.getTime()));
            losDto.setTProduktionsende(new java.sql.Date(tEnde.getTime()));
            losDto.setStuecklisteIId(stuecklisteDto.getIId());
            losDto.setLagerIIdZiel(stuecklisteDto.getLagerIIdZiellager());
            losDto.setFertigungsgruppeIId(stuecklisteDto.getFertigungsgruppeIId());
            losDto.setNLosgroesse(zielmenge.multiply(bdLosgroesse));
            losDto.setKostenstelleIId(auftragDto.getKostenstelleIId());
            losDto.setCProjekt(auftragDto.getCBezProjektbezeichnung());
            laDto.setLosDto(losDto);

            laDto.setFehlmengen(getFehlmengeFac()
                    .getAnzahlFehlmengeEinesArtikels(stuecklisteDto.getArtikelIId(), theClientDto));
            laDto.setReservierungen(
                    getReservierungFac().getAnzahlReservierungen(stuecklisteDto.getArtikelIId(), theClientDto));

            BigDecimal lagerstand = new BigDecimal(0);
            LagerDto[] allelaegerDtos = getLagerFac().lagerFindByMandantCNr(theClientDto.getMandant());

            for (int i = 0; i < allelaegerDtos.length; i++) {
                if (Helper.short2boolean(allelaegerDtos[i].getBInternebestellung())) {
                    lagerstand = lagerstand.add(getLagerFac().getLagerstand(stuecklisteDto.getArtikelIId(),
                            allelaegerDtos[i].getIId(), theClientDto));
                }

            }

            laDto.setLagerstand(lagerstand);
            laDto.setOffeneFertigungsmenge(
                    getFertigungFac().getAnzahlInFertigung(stuecklisteDto.getArtikelIId(), theClientDto));

            losDtos.add(laDto);

            for (int j = 0; j < stuecklisteAufegloest.size(); j++) {
                StuecklisteMitStrukturDto strukt = (StuecklisteMitStrukturDto) stuecklisteAufegloest.get(j);

                if (strukt.getStuecklistepositionDto() != null
                        && strukt.getStuecklistepositionDto().getArtikelIId() != null) {

                    losDtos = holeAlleMoeglichenUnterloseEinerStueckliste(
                            strukt.getStuecklistepositionDto().getArtikelIId(),
                            strukt.getStuecklistepositionDto().getNZielmenge().multiply(zielmenge),
                            stdVorlaufzeit, tBeginn, losDtos, auftragDto, bdLosgroesse, theClientDto);

                }
            }

        }
    } catch (RemoteException e) {
        throwEJBExceptionLPRespectOld(e);
    }
    return losDtos;
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

public Integer holeTageslos(Integer lagerIId, String mandantCNr, int iStandarddurchlaufzeit,
        boolean bSofortverbrauch, TheClientDto theClientDto) {

    Integer losIId = null;/* ww  w . j  a va2s .c  om*/

    TageslosDto tageslosDto = null;
    try {
        tageslosDto = getKuecheFac().tageslosFindByLagerIIdBSofortverbrauch(lagerIId,
                Helper.boolean2Short(bSofortverbrauch));
    } catch (RemoteException e) {
        throwEJBExceptionLPRespectOld(e);
    }

    if (tageslosDto != null) {
        // Nun das erste ausgegebene Los mit der angegebenen Kostenstelle
        // des heutigen Tages suchen
        Session session = FLRSessionFactory.getFactory().openSession();
        String sQuery3 = "FROM FLRLosReport AS l WHERE l.kostenstelle_i_id=" + tageslosDto.getKostenstelleIId()
                + " AND l.stueckliste_i_id IS NULL AND l.status_c_nr IN('" + FertigungFac.STATUS_IN_PRODUKTION
                + "','" + FertigungFac.STATUS_TEILERLEDIGT + "') AND l.t_produktionsbeginn='"
                + Helper.formatDateWithSlashes(new java.sql.Date(System.currentTimeMillis())) + "' ";

        if (bSofortverbrauch) {
            sQuery3 += " AND l.flrfertigungsgruppe.c_bez='" + StuecklisteFac.FERTIGUNGSGRUPPE_SOFORTVERBRAUCH
                    + "' ";
        } else {
            sQuery3 += " AND l.flrfertigungsgruppe.c_bez NOT IN('"
                    + StuecklisteFac.FERTIGUNGSGRUPPE_SOFORTVERBRAUCH + "') ";
        }
        sQuery3 += " ORDER BY l.t_produktionsbeginn DESC";

        org.hibernate.Query hquery3 = session.createQuery(sQuery3);
        hquery3.setMaxResults(1);
        List<?> resultList3 = hquery3.list();
        Iterator<?> resultListIterator3 = resultList3.iterator();

        if (resultListIterator3.hasNext()) {
            FLRLosReport rep = (FLRLosReport) resultListIterator3.next();
            losIId = rep.getI_id();
        } else {
            // Wenn keines gefunden wurde, dann ein neues anlegen
            Timestamp tHeute = Helper.cutTimestamp(new Timestamp(System.currentTimeMillis()));

            Calendar cTemp = Calendar.getInstance();
            cTemp.set(Calendar.DAY_OF_YEAR, cTemp.get(Calendar.DAY_OF_YEAR) + iStandarddurchlaufzeit);

            LosDto losDto = new LosDto();
            losDto.setTProduktionsbeginn(new java.sql.Date(tHeute.getTime()));
            losDto.setTProduktionsende(new java.sql.Date(cTemp.getTimeInMillis()));
            losDto.setKostenstelleIId(tageslosDto.getKostenstelleIId());
            losDto.setMandantCNr(mandantCNr);
            losDto.setNLosgroesse(new BigDecimal(1));
            try {
                FertigungsgruppeDto[] fgDto = getStuecklisteFac().fertigungsgruppeFindByMandantCNr(mandantCNr,
                        theClientDto);

                if (fgDto != null && fgDto.length > 0) {
                    losDto.setFertigungsgruppeIId(fgDto[0].getIId());
                }

                if (bSofortverbrauch) {
                    Fertigungsgruppe fertigungsgruppe;
                    try {
                        Query query = em.createNamedQuery("FertigungsgruppefindByMandantCNrCBez");
                        query.setParameter(1, mandantCNr);
                        query.setParameter(2, StuecklisteFac.FERTIGUNGSGRUPPE_SOFORTVERBRAUCH);
                        fertigungsgruppe = (Fertigungsgruppe) query.getSingleResult();

                        losDto.setFertigungsgruppeIId(fertigungsgruppe.getIId());

                    } catch (javax.persistence.NoResultException e) {
                        FertigungsgruppeDto fertigungsgruppeDto = new FertigungsgruppeDto();

                        fertigungsgruppeDto.setCBez(StuecklisteFac.FERTIGUNGSGRUPPE_SOFORTVERBRAUCH);
                        fertigungsgruppeDto.setISort(getStuecklisteFac().getNextFertigungsgruppe(theClientDto));

                        Integer i = getStuecklisteFac().createFertigungsgruppe(fertigungsgruppeDto,
                                theClientDto);
                        losDto.setFertigungsgruppeIId(i);
                    }

                }

                MandantDto mandantDto = getMandantFac().mandantFindByPrimaryKey(mandantCNr, theClientDto);
                losDto.setPartnerIIdFertigungsort(mandantDto.getPartnerIId());

                LagerDto lagerDtoAbbuchungslager = getLagerFac()
                        .lagerFindByPrimaryKey(tageslosDto.getLagerIIdAbbuchung());

                String projekt = "Tageslos " + Helper.formatDatum(tHeute, theClientDto.getLocUi()) + " "
                        + lagerDtoAbbuchungslager.getCNr();

                losDto.setCProjekt(projekt);
                losDto.setLagerIIdZiel(getLagerFac().getHauptlagerDesMandanten(theClientDto).getIId());

                losIId = getFertigungFac().createLos(losDto, theClientDto).getIId();

                getFertigungFac().gebeLosAus(losIId, true, false, theClientDto, null);

            } catch (RemoteException e) {
                throwEJBExceptionLPRespectOld(e);
            }

        }
        session.close();
    }
    return losIId;
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

@TransactionAttribute(TransactionAttributeType.NEVER)
public LosDto createLoseAusAuftrag(LosDto losDto, Integer auftragIId, TheClientDto theClientDto) {

    LosDto losReturn = null;//  ww w  . j  a v a 2  s. co m
    try {
        AuftragDto auftragDto = getAuftragFac().auftragFindByPrimaryKey(auftragIId);

        KundeDto kdDto = getKundeFac().kundeFindByPrimaryKey(auftragDto.getKundeIIdAuftragsadresse(),
                theClientDto);
        if (auftragDto.getAuftragstatusCNr().equals(LocaleFac.STATUS_ANGELEGT)
                || auftragDto.getAuftragstatusCNr().equals(LocaleFac.STATUS_OFFEN)
                || auftragDto.getAuftragstatusCNr().equals(LocaleFac.STATUS_TEILERLEDIGT)) {
            AuftragpositionDto[] dtos = getAuftragpositionFac().auftragpositionFindByAuftrag(auftragIId);
            for (int i = 0; i < dtos.length; i++) {
                StuecklisteDto stuecklisteDto = getStuecklisteFac()
                        .stuecklisteFindByMandantCNrArtikelIIdOhneExc(dtos[i].getArtikelIId(), theClientDto);
                if (stuecklisteDto != null) {
                    if (dtos[i].getNOffeneMenge() != null && dtos[i].getNOffeneMenge().doubleValue() > 0)
                        losDto.setAuftragpositionIId(dtos[i].getIId());
                    losDto.setNLosgroesse(dtos[i].getNOffeneMenge());

                    // SP1595 Termine berechnen

                    Timestamp tAuftragsliefertermin = dtos[i].getTUebersteuerbarerLiefertermin();

                    Timestamp tEnde = Helper.addiereTageZuTimestamp(tAuftragsliefertermin,
                            -kdDto.getILieferdauer());

                    int durchlaufzeit = 0;
                    if (stuecklisteDto.getNDefaultdurchlaufzeit() != null) {
                        durchlaufzeit = stuecklisteDto.getNDefaultdurchlaufzeit().intValue();
                    }

                    Timestamp tBeginn = Helper.addiereTageZuTimestamp(tEnde, -durchlaufzeit);

                    if (tBeginn.before(Helper.cutTimestamp(new Timestamp(System.currentTimeMillis())))) {

                        tBeginn = Helper.cutTimestamp(new Timestamp(System.currentTimeMillis()));
                        tEnde = Helper.addiereTageZuTimestamp(tBeginn, durchlaufzeit);
                    }

                    losDto.setTProduktionsbeginn(new java.sql.Date(tBeginn.getTime()));
                    losDto.setTProduktionsende(new java.sql.Date(tEnde.getTime()));

                    losDto.setStuecklisteIId(stuecklisteDto.getIId());
                    losReturn = getFertigungFac().createLos(losDto, theClientDto);
                }
            }
        }
    } catch (RemoteException e) {
        throwEJBExceptionLPRespectOld(e);
    }
    return losReturn;
}