Example usage for java.sql Timestamp before

List of usage examples for java.sql Timestamp before

Introduction

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

Prototype

public boolean before(Timestamp ts) 

Source Link

Document

Indicates whether this Timestamp object is earlier than the given Timestamp object.

Usage

From source file:fr.paris.lutece.plugins.document.service.DocumentService.java

/**
 * Return the data of a document object/*from   w w  w  .jav  a 2  s .  c o  m*/
 * @param mRequest The MultipartHttpServletRequest
 * @param document The document object
 * @param locale The locale
 * @return data of document object
 */
public String getDocumentData(MultipartHttpServletRequest mRequest, Document document, Locale locale) {
    String strDocumentTitle = mRequest.getParameter(PARAMETER_DOCUMENT_TITLE);
    String strDocumentSummary = mRequest.getParameter(PARAMETER_DOCUMENT_SUMMARY);
    String strDocumentComment = mRequest.getParameter(PARAMETER_DOCUMENT_COMMENT);
    String strDateValidityBegin = mRequest.getParameter(PARAMETER_VALIDITY_BEGIN);
    String strDateValidityEnd = mRequest.getParameter(PARAMETER_VALIDITY_END);
    String strMailingListId = mRequest.getParameter(PARAMETER_MAILING_LIST);
    int nMailingListId = IntegerUtils.convert(strMailingListId, 0);
    String strPageTemplateDocumentId = mRequest.getParameter(PARAMETER_PAGE_TEMPLATE_DOCUMENT_ID);
    int nPageTemplateDocumentId = IntegerUtils.convert(strPageTemplateDocumentId, 0);
    String[] arrayCategory = mRequest.getParameterValues(PARAMETER_CATEGORY);

    // Check for mandatory value
    if (StringUtils.isBlank(strDocumentTitle) || StringUtils.isBlank(strDocumentSummary)) {
        return AdminMessageService.getMessageUrl(mRequest, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP);
    }

    // Check for illegal character character
    if (StringUtil.containsHtmlSpecialCharacters(strDocumentTitle)
            || StringUtil.containsHtmlSpecialCharacters(strDocumentSummary)) {
        return AdminMessageService.getMessageUrl(mRequest, Messages.MESSAGE_ILLEGAL_CHARACTER,
                AdminMessage.TYPE_STOP);
    }

    DocumentType documentType = DocumentTypeHome.findByPrimaryKey(document.getCodeDocumentType());
    List<DocumentAttribute> listAttributes = documentType.getAttributes();

    for (DocumentAttribute attribute : listAttributes) {
        String strAdminMessage = setAttribute(attribute, document, mRequest, locale);

        if (strAdminMessage != null) {
            return strAdminMessage;
        }
    }

    Timestamp dateValidityBegin = null;
    Timestamp dateValidityEnd = null;

    if ((strDateValidityBegin != null) && !strDateValidityBegin.equals("")) {
        Date dateBegin = DateUtil.formatDateLongYear(strDateValidityBegin, locale);

        if ((dateBegin == null)) {
            return AdminMessageService.getMessageUrl(mRequest, MESSAGE_INVALID_DATEBEGIN,
                    AdminMessage.TYPE_STOP);
        }

        dateValidityBegin = new Timestamp(dateBegin.getTime());

        if (dateValidityBegin.before(new Timestamp(0))) {
            return AdminMessageService.getMessageUrl(mRequest, MESSAGE_INVALID_DATE_BEFORE_70,
                    AdminMessage.TYPE_STOP);
        }
    }

    if ((strDateValidityEnd != null) && !strDateValidityEnd.equals("")) {
        Date dateEnd = DateUtil.formatDateLongYear(strDateValidityEnd, locale);

        if ((dateEnd == null)) {
            return AdminMessageService.getMessageUrl(mRequest, MESSAGE_INVALID_DATEEND, AdminMessage.TYPE_STOP);
        }

        dateValidityEnd = new Timestamp(dateEnd.getTime());

        if (dateValidityEnd.before(new Timestamp(0))) {
            return AdminMessageService.getMessageUrl(mRequest, MESSAGE_INVALID_DATE_BEFORE_70,
                    AdminMessage.TYPE_STOP);
        }
    }

    //validate period (dateEnd > dateBegin )
    if ((dateValidityBegin != null) && (dateValidityEnd != null)) {
        if (dateValidityEnd.before(dateValidityBegin)) {
            return AdminMessageService.getMessageUrl(mRequest, MESSAGE_ERROR_DATEEND_BEFORE_DATEBEGIN,
                    AdminMessage.TYPE_STOP);
        }
    }

    document.setTitle(strDocumentTitle);
    document.setSummary(strDocumentSummary);
    document.setComment(strDocumentComment);
    document.setDateValidityBegin(dateValidityBegin);
    document.setDateValidityEnd(dateValidityEnd);
    document.setMailingListId(nMailingListId);
    document.setPageTemplateDocumentId(nPageTemplateDocumentId);

    MetadataHandler hMetadata = documentType.metadataHandler();

    if (hMetadata != null) {
        document.setXmlMetadata(hMetadata.getXmlMetadata(mRequest.getParameterMap()));
    }

    document.setAttributes(listAttributes);

    //Categories
    List<Category> listCategories = new ArrayList<Category>();

    if (arrayCategory != null) {
        for (String strIdCategory : arrayCategory) {
            listCategories.add(CategoryHome.find(IntegerUtils.convert(strIdCategory)));
        }
    }

    document.setCategories(listCategories);

    return null; // No error
}

From source file:org.eevolution.form.VCRP.java

protected Timestamp[] getDayBorders(Timestamp dateTime, MMPCOrderNode node, MResourceType t) {

    Timestamp endDayTime = null;
    // The theoretical latest time on a day, where the work ends, dependent on
    // the resource type's time slot value
    if (t.isTimeSlot()) {

        endDayTime = DateTimeUtil.getDayBorder(dateTime, t.getTimeSlotEnd(), true);
    } else {/*from   w  ww.  j a  v  a  2 s  .  c  o m*/

        endDayTime = DateTimeUtil.getDayBorder(dateTime, null, true);
    }

    // Initialize the end time to the present, if the work ends at this day. Otherwise
    // the earliest possible start time for a day is set.
    endDayTime = (endDayTime.before(node.getDateFinishSchedule())) ? endDayTime : node.getDateFinishSchedule();

    Timestamp startDayTime = null;
    // The theoretical earliest time on a day, where the work begins, dependent on
    // the resource type's time slot value
    if (t.isTimeSlot()) {

        startDayTime = DateTimeUtil.getDayBorder(dateTime, t.getTimeSlotStart(), false);
    } else {

        startDayTime = DateTimeUtil.getDayBorder(dateTime, null, false);
    }

    // Initialize the end time to the present, if the work begins at this day. Otherwise
    // the earliest possible start time for a day is set.
    startDayTime = (startDayTime.after(node.getDateStartSchedule())) ? startDayTime
            : node.getDateStartSchedule();

    return new Timestamp[] { startDayTime, endDayTime };
}

From source file:com.alfaariss.oa.engine.requestor.jdbc.JDBCFactory.java

/**
 * Establish the most recent timestamp from the two Timestamps; returns -1 when 
 * @param ts1 Value for date 1; may be null
 * @param ts2 Value for date 2; may be null
 * @return Most recent date in ms since 1970, or -1 when it could not be established
 *///from   www  . ja va 2  s.  c om
private long getMostRecentDate(Timestamp ts1, Timestamp ts2) {
    // Both null? Then we don't know
    if (ts1 == null && ts2 == null)
        return -1;

    // Not both null, but tsPool is null? Then tsRequestors contains the time we want
    if (ts1 == null)
        return ts2.getTime();
    // Or tsPool is it when tsRequestors is null...
    if (ts2 == null)
        return ts1.getTime();

    // So, both are non-null; which one is most recent:
    if (ts1.before(ts2))
        return ts2.getTime();
    return ts1.getTime();
}

From source file:org.opencommercesearch.remote.assetmanager.editor.service.DefaultRuleAssetValidator.java

/**
 * Checks that the start and end date are properly specified.
 * <p/>/* w w w . j  a  va2 s  .co m*/
 * A common error would be to enter an end date which is before the given start date. 
 */
protected void validateStartAndEndDateUpdate(AssetEditorInfo editorInfo, PropertyUpdate startDateProperty,
        PropertyUpdate endDateProperty) {
    Timestamp startDate = null;
    Timestamp endDate = null;

    if (startDateProperty == null) {
        //This field wasn't updated, so fetch the value from the asset.
        RepositoryItem currentItem = (RepositoryItem) editorInfo.getAssetWrapper().getAsset();
        startDate = (Timestamp) currentItem.getPropertyValue(RuleProperty.START_DATE);
    } else {
        String startDateValue = (String) startDateProperty.getPropertyValue();

        if (startDateValue != null && !startDateValue.isEmpty()) {
            startDate = Timestamp.valueOf(startDateValue); //Timestamp.valueOf understands ISO 8601 date format.
        }
    }

    if (endDateProperty == null) {
        //This field wasn't updated, so fetch the value from the asset.
        RepositoryItem currentItem = (RepositoryItem) editorInfo.getAssetWrapper().getAsset();
        endDate = (Timestamp) currentItem.getPropertyValue(RuleProperty.END_DATE);
    } else {
        String endDateValue = (String) endDateProperty.getPropertyValue();
        if (endDateValue == null || endDateValue.isEmpty()) {
            editorInfo.getAssetService().addError(RuleProperty.END_DATE, NULL_PROPERTY_ERROR_MSG);
            return; //Don't do more validation.
        } else {
            endDate = Timestamp.valueOf(endDateValue); //Timestamp.valueOf understands ISO 8601 date format.
        }
    }

    if (startDate != null && endDate.before(startDate)) {
        editorInfo.getAssetService().addError(RuleProperty.END_DATE, INVALID_END_DATE_ERROR_MSG);
    }
}

From source file:org.epics.archiverappliance.retrieval.DataRetrievalServlet.java

/**
 * Parse the timeranges parameter and generate a list of TimeSpans.
 * @param resp/*from ww  w  .j  a v a 2  s .  co  m*/
 * @param pvName
 * @param requestTimes - list of timespans that we add the valid times to.
 * @param timeRangesStr
 * @return
 * @throws IOException
 */
private boolean parseTimeRanges(HttpServletResponse resp, String pvName, LinkedList<TimeSpan> requestTimes,
        String timeRangesStr) throws IOException {
    String[] timeRangesStrList = timeRangesStr.split(",");
    if (timeRangesStrList.length % 2 != 0) {
        String msg = "Need to specify an even number of times in timeranges for pv " + pvName + ". We have "
                + timeRangesStrList.length + " times";
        logger.error(msg);
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return false;
    }

    LinkedList<Timestamp> timeRangesList = new LinkedList<Timestamp>();
    for (String timeRangesStrItem : timeRangesStrList) {
        try {
            Timestamp ts = TimeUtils.convertFromISO8601String(timeRangesStrItem);
            timeRangesList.add(ts);
        } catch (IllegalArgumentException ex) {
            try {
                Timestamp ts = TimeUtils.convertFromDateTimeStringWithOffset(timeRangesStrItem);
                timeRangesList.add(ts);
            } catch (IllegalArgumentException ex2) {
                String msg = "Cannot parse time " + timeRangesStrItem;
                logger.warn(msg, ex2);
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
                return false;
            }
        }
    }

    assert (timeRangesList.size() % 2 == 0);
    Timestamp prevEnd = null;
    while (!timeRangesList.isEmpty()) {
        Timestamp t0 = timeRangesList.pop();
        Timestamp t1 = timeRangesList.pop();

        if (t1.before(t0)) {
            String msg = "For request, end " + t1.toString() + " is before start " + t0.toString() + " for pv "
                    + pvName;
            logger.error(msg);
            resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return false;
        }

        if (prevEnd != null) {
            if (t0.before(prevEnd)) {
                String msg = "For request, start time " + t0.toString() + " is before previous end time "
                        + prevEnd.toString() + " for pv " + pvName;
                logger.error(msg);
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
                return false;
            }
        }
        prevEnd = t1;
        requestTimes.add(new TimeSpan(t0, t1));
    }
    return true;
}

From source file:org.kuali.kra.irb.actions.ActionHelper.java

/**
 * Prepares all protocol actions for being filtered by setting their isInFilterView attribute.
 */// w  w  w.ja v  a  2 s . co  m
public void initFilterDatesView() {
    java.util.Date dayBeforeStartDate = null;
    java.util.Date dayAfterEndDate = null;

    if (filteredHistoryStartDate != null && filteredHistoryEndDate != null) {
        dayBeforeStartDate = DateUtils.addDays(filteredHistoryStartDate, -1);
        dayAfterEndDate = DateUtils.addDays(filteredHistoryEndDate, 1);
    }

    for (ProtocolActionBase protocolAction : getSortedProtocolActions()) {
        Timestamp actionDate = protocolAction.getActionDate();
        if (dayBeforeStartDate != null && dayAfterEndDate != null) {
            protocolAction.setIsInFilterView(
                    actionDate.after(dayBeforeStartDate) && actionDate.before(dayAfterEndDate));
        } else {
            protocolAction.setIsInFilterView(true);
        }
        if (protocolAction.getIsInFilterView()) {
            ((ProtocolAction) protocolAction).setQuestionnairePrintOptionFromHelper(this);
        }
    }
}

From source file:org.opentaps.amazon.product.AmazonProductServices.java

/**
 * Service looks over AmzonProductPrice and collect product prices that haven't been posted yet,
 * creates XML document for Price Feed and post it to Amazon.com.
 * @param dctx a <code>DispatchContext</code> value
 * @param context the service context <code>Map</code>
 * @return the service response <code>Map</code>
 *///from  w  w  w .  j  a  va 2  s  .c  o m
public static Map<String, Object> publishProductPriceToAmazon(DispatchContext dctx,
        Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    String prodId = (String) context.get("productId");

    try {
        List<EntityCondition> conditions = UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition(
                "statusId", EntityOperator.IN, Arrays.asList(AmazonConstants.statusProductCreated,
                        AmazonConstants.statusProductChanged, AmazonConstants.statusProductError)));
        if (UtilValidate.isNotEmpty(prodId)) {
            conditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, prodId));
        }

        TransactionUtil.begin();
        EntityListIterator amazonPriceIt = delegator.findListIteratorByCondition("AmazonProductPrice",
                EntityCondition.makeCondition(conditions, EntityOperator.AND), null,
                Arrays.asList("productId"));
        TransactionUtil.commit();

        // Prepare Price Feed document
        long messageId = 1;
        Map<GenericValue, String> invalidAmazonPrices = new HashMap<GenericValue, String>();
        List<GenericValue> validAmazonPrices = new ArrayList<GenericValue>();
        Document priceFeed = AmazonConstants.soapClient.createDocumentHeader(AmazonConstants.messageTypePrice);
        Element root = priceFeed.getDocumentElement();
        GenericValue amazonPrice = null;
        while ((amazonPrice = amazonPriceIt.next()) != null) {

            String errMessage = null;

            if (AmazonConstants.productPostRetryThreshold <= amazonPrice.getLong("postFailures").intValue()) {
                String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_PostPriceAttemptsOverThreshold",
                        UtilMisc.<String, Object>toMap("productId", amazonPrice.getString("productId"),
                                "threshold", AmazonConstants.productPostRetryThreshold),
                        locale);
                Debug.logInfo(errorLog, MODULE);
                continue;
            }

            // Ignore products marked deleted
            if (AmazonUtil.isAmazonProductDeleted(delegator, amazonPrice.getString("productId"))) {
                String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_IgnoringProductPrice_ProductDeleted",
                        UtilMisc.toMap("productId", amazonPrice.getString("productId")), locale);
                Debug.logError(errorLog, MODULE);
                continue;
            }

            // check if this product was exported and acknowledged earlier
            if (delegator.findCountByAnd("AmazonProduct",
                    UtilMisc.toMap("productId", amazonPrice.getString("productId"), "statusId",
                            AmazonConstants.statusProductPosted, "ackStatusId",
                            AmazonConstants.statusProductAckRecv)) != 1) {
                String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_PostPriceNonExistentProduct",
                        UtilMisc.toMap("productId", amazonPrice.getString("productId")), locale);
                Debug.logError(errorLog, MODULE);
                continue;
            }

            /*
             * Some elements are required. So, we get it first and go to next iteration
             * if some of these is absent.
             */

            String upc = null;
            if (AmazonConstants.requireUpcCodes || AmazonConstants.useUPCAsSKU) {

                // Establish and validate the UPC
                upc = getProductUPC(delegator, amazonPrice.getString("productId"), locale);
                if (UtilValidate.isEmpty(upc) && AmazonConstants.requireUpcCodes) {
                    errMessage = AmazonUtil.compoundError(errMessage,
                            UtilProperties.getMessage(AmazonConstants.errorResource,
                                    "AmazonError_MissingCodeUPC",
                                    UtilMisc.toMap("productId", amazonPrice.getString("productId")), locale));
                } else if (UtilValidate.isNotEmpty(upc) && !UtilProduct.isValidUPC(upc)) {
                    errMessage = AmazonUtil.compoundError(errMessage,
                            UtilProperties.getMessage(AmazonConstants.errorResource,
                                    "AmazonError_InvalidCodeUPC",
                                    UtilMisc.toMap("productId", amazonPrice.getString("productId")), locale));
                }
            }

            // Establish and validate the SKU
            String sku = getProductSKU(delegator, amazonPrice, upc);
            if (UtilValidate.isEmpty(sku) && !AmazonConstants.useUPCAsSKU) {
                errMessage = AmazonUtil
                        .compoundError(errMessage,
                                UtilProperties.getMessage(AmazonConstants.errorResource,
                                        "AmazonError_NoRequiredParameter", UtilMisc.toMap("parameterName",
                                                "SKU", "productName", amazonPrice.getString("productId")),
                                        locale));
            }

            if (UtilValidate.isNotEmpty(errMessage)) {
                invalidAmazonPrices.put(amazonPrice, errMessage);
                continue;
            }

            // Standard price - filtered by date
            BigDecimal standardPrice = null;
            String standardPriceCurrency = null;

            // Try to find a price for the Amazon productStoreGroup first
            EntityCondition cond = EntityCondition.makeCondition(EntityOperator.AND,
                    EntityCondition.makeCondition("productId", EntityOperator.EQUALS,
                            amazonPrice.getString("productId")),
                    EntityCondition.makeCondition("productPriceTypeId", EntityOperator.EQUALS,
                            AmazonConstants.priceStandard),
                    EntityCondition.makeCondition("productStoreGroupId", EntityOperator.EQUALS,
                            AmazonConstants.priceProductStoreGroup),
                    EntityUtil.getFilterByDateExpr());
            GenericValue standardPriceVal = EntityUtil.getFirst(delegator.findByCondition("ProductPrice", cond,
                    null, Arrays.asList("lastUpdatedStamp DESC")));
            if (UtilValidate.isEmpty(standardPriceVal)) {

                // If there's no price for the Amazon productStoreGroup, try _NA_
                cond = EntityCondition.makeCondition(EntityOperator.AND,
                        EntityCondition.makeCondition("productId", EntityOperator.EQUALS,
                                amazonPrice.getString("productId")),
                        EntityCondition.makeCondition("productPriceTypeId", EntityOperator.EQUALS,
                                AmazonConstants.priceStandard),
                        EntityCondition.makeCondition("productStoreGroupId", EntityOperator.EQUALS, "_NA_"),
                        EntityUtil.getFilterByDateExpr());
                standardPriceVal = EntityUtil.getFirst(delegator.findByCondition("ProductPrice", cond, null,
                        Arrays.asList("lastUpdatedStamp DESC")));
            }
            if (UtilValidate.isNotEmpty(standardPriceVal)) {
                standardPrice = standardPriceVal.getBigDecimal("price").setScale(AmazonConstants.decimals,
                        AmazonConstants.rounding);
                standardPriceCurrency = standardPriceVal.getString("currencyUomId");
            }

            // Sale price - NOT filtered by date
            BigDecimal salePrice = null;
            String salePriceCurrency = null;
            String saleStartDate = null;
            String saleEndDate = null;
            cond = EntityCondition.makeCondition(EntityOperator.AND,
                    EntityCondition.makeCondition("productId", EntityOperator.EQUALS,
                            amazonPrice.getString("productId")),
                    EntityCondition.makeCondition("productPriceTypeId", EntityOperator.EQUALS,
                            AmazonConstants.priceSale),
                    EntityCondition.makeCondition("productStoreGroupId", EntityOperator.EQUALS,
                            AmazonConstants.priceProductStoreGroup));
            GenericValue salePriceVal = EntityUtil.getFirst(delegator.findByCondition("ProductPrice", cond,
                    null, Arrays.asList("lastUpdatedStamp DESC")));
            if (UtilValidate.isNotEmpty(salePriceVal)) {
                salePrice = salePriceVal.getBigDecimal("price").setScale(AmazonConstants.decimals,
                        AmazonConstants.rounding);
                salePriceCurrency = salePriceVal.getString("currencyUomId");
                Timestamp fromDate = salePriceVal.getTimestamp("fromDate");
                Timestamp thruDate = salePriceVal.getTimestamp("thruDate");
                Timestamp now = UtilDateTime.nowTimestamp();
                if (UtilValidate.isEmpty(thruDate)) {
                    Debug.logInfo(
                            UtilProperties.getMessage(AmazonConstants.errorResource,
                                    "AmazonError_PostPriceNoSaleEndDate",
                                    UtilMisc.toMap("productId", amazonPrice.getString("productId")), locale),
                            MODULE);

                    // Amazon requires an end date for the sale, so add twenty years or so
                    saleEndDate = AmazonUtil
                            .convertTimestampToXSDate(new Timestamp(now.getTime() + 631152000000L));
                } else if (thruDate.before(now)) {
                    Debug.logInfo(
                            UtilProperties.getMessage(AmazonConstants.errorResource,
                                    "AmazonError_PostPriceSalePriceSkipped", UtilMisc.toMap("productId",
                                            amazonPrice.getString("productId"), "thruDate", thruDate),
                                    locale),
                            MODULE);

                    // The sale is over, so leave out the sale price so that it will be deleted in the Amazon system
                    salePrice = null;
                }
                if (UtilValidate.isEmpty(fromDate)) {

                    // Amazon requires a start date for the sale, so use the current time
                    saleStartDate = AmazonUtil.convertTimestampToXSDate(now);
                } else {

                    // Amazon requires dates to be in the future, so use the current time if the start date for the sale is past
                    saleStartDate = AmazonUtil.convertTimestampToXSDate(fromDate.before(now) ? now : fromDate);
                }
            }

            /*
            * Create and add required elements and values
            */
            Element message = priceFeed.createElement("Message");
            root.appendChild(message);
            UtilXml.addChildElementValue(message, "MessageID", "" + messageId, priceFeed);
            Element price = priceFeed.createElement("Price");
            message.appendChild(price);
            UtilXml.addChildElementValue(price, "SKU", sku, priceFeed);

            // Delist the product (set standard price to zero) if certain conditions are true
            boolean deListProduct = UtilValidate.isEmpty(standardPrice)
                    || ((UtilValidate.isEmpty(salePriceVal) && AmazonConstants.delistProductIfNoSalePrice));

            Element standardPriceElement = UtilXml.addChildElementValue(price, "StandardPrice",
                    deListProduct ? "0.0" : standardPrice.toString(), priceFeed);
            standardPriceElement.setAttribute("currency",
                    UtilValidate.isNotEmpty(standardPriceCurrency) ? standardPriceCurrency
                            : UtilProperties.getPropertyValue("opentaps.properties", "defaultCurrencyUomId"));
            if (UtilValidate.isEmpty(standardPrice)) {
                standardPriceElement.setAttribute("zero", "true");
            }
            if (UtilValidate.isNotEmpty(salePrice)) {
                Element sale = priceFeed.createElement("Sale");
                price.appendChild(sale);
                UtilXml.addChildElementValue(sale, "StartDate", saleStartDate, priceFeed);
                UtilXml.addChildElementValue(sale, "EndDate", saleEndDate, priceFeed);
                Element salePriceElement = UtilXml.addChildElementValue(sale, "SalePrice", salePrice.toString(),
                        priceFeed);
                salePriceElement.setAttribute("currency", salePriceCurrency);
            }

            amazonPrice.set("acknowledgeMessageId", "" + messageId);
            validAmazonPrices.add(amazonPrice);
            messageId++;
            if (messageId % 500 == 0) {
                Debug.logInfo(UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_Processed_Records_Price", UtilMisc.toMap("count", messageId), locale),
                        MODULE);
            }
        }
        amazonPriceIt.close();

        LinkedHashMap<GenericValue, String> emailErrorMessages = new LinkedHashMap<GenericValue, String>();

        if (UtilValidate.isEmpty(validAmazonPrices)) {
            String infoMessage = UtilProperties.getMessage(AmazonConstants.errorResource,
                    "AmazonError_PostNoNewPrices", locale);
            Debug.logInfo(infoMessage, MODULE);
        } else {

            boolean success = true;
            String postErrorMessage = null;
            long processingDocumentId = -1;
            try {
                String xml = UtilXml.writeXmlDocument(priceFeed);
                Debug.logVerbose(xml, MODULE);
                Writer writer = new OutputStreamWriter(new FileOutputStream(AmazonConstants.xmlOutputLocation
                        + "AmazonPriceFeed_" + AmazonConstants.xmlOutputDateFormat.format(new Date()) + ".xml"),
                        "UTF-8");
                writer.write(xml);
                writer.close();
                processingDocumentId = AmazonConstants.soapClient.postProductPrices(xml);
                Debug.logInfo(UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_ProcessingDocumentId_Price",
                        UtilMisc.toMap("processingDocumentId", processingDocumentId), locale), MODULE);
            } catch (RemoteException e) {
                success = false;
                postErrorMessage = e.getMessage();
                List<String> productIds = EntityUtil.getFieldListFromEntityList(validAmazonPrices, "productId",
                        true);
                String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_PostPriceError",
                        UtilMisc.toMap("productIds", productIds, "errorMessage", postErrorMessage), locale);
                Debug.logError(errorLog, MODULE);
            }

            // Store operational data of the post attempt
            for (GenericValue validAmazonPrice : validAmazonPrices) {
                validAmazonPrice.set("statusId",
                        success ? AmazonConstants.statusProductPosted : AmazonConstants.statusProductError);
                validAmazonPrice.set("postTimestamp", UtilDateTime.nowTimestamp());
                validAmazonPrice.set("postErrorMessage", success ? null : postErrorMessage);
                if (!success) {
                    validAmazonPrice.set("postFailures", validAmazonPrice.getLong("postFailures") + 1);
                }
                validAmazonPrice.set("processingDocumentId", success ? processingDocumentId : null);
                validAmazonPrice.set("ackStatusId", AmazonConstants.statusProductNotAcked);
                validAmazonPrice.set("acknowledgeTimestamp", null);
                validAmazonPrice.set("acknowledgeErrorMessage", null);
                validAmazonPrice.store();
                if (AmazonConstants.sendErrorEmails && !success) {
                    emailErrorMessages.put(validAmazonPrice, postErrorMessage);
                }
            }
        }

        for (GenericValue invalidAmazonPrice : invalidAmazonPrices.keySet()) {
            String errorMessage = invalidAmazonPrices.get(invalidAmazonPrice);
            invalidAmazonPrice.set("statusId", AmazonConstants.statusProductError);
            invalidAmazonPrice.set("postTimestamp", UtilDateTime.nowTimestamp());
            invalidAmazonPrice.set("postErrorMessage", errorMessage);
            invalidAmazonPrice.set("postFailures", invalidAmazonPrice.getLong("postFailures") + 1);
            invalidAmazonPrice.set("processingDocumentId", null);
            invalidAmazonPrice.set("ackStatusId", AmazonConstants.statusProductNotAcked);
            invalidAmazonPrice.set("acknowledgeTimestamp", null);
            invalidAmazonPrice.set("acknowledgeErrorMessage", null);
            invalidAmazonPrice.store();
            if (AmazonConstants.sendErrorEmails) {
                emailErrorMessages.put(invalidAmazonPrice, errorMessage);
            }
        }

        if (AmazonConstants.sendErrorEmails && UtilValidate.isNotEmpty(emailErrorMessages)) {
            AmazonUtil.sendBulkErrorEmail(dispatcher, userLogin, emailErrorMessages,
                    UtilProperties.getMessage(AmazonConstants.errorResource,
                            "AmazonError_ErrorEmailSubject_PostPrice", AmazonConstants.errorEmailLocale),
                    AmazonConstants.errorEmailScreenUriProducts);
        }

    } catch (GenericEntityException gee) {
        UtilMessage.createAndLogServiceError(gee, locale, MODULE);
    } catch (IOException ioe) {
        UtilMessage.createAndLogServiceError(ioe, locale, MODULE);
    } catch (GenericServiceException gse) {
        UtilMessage.createAndLogServiceError(gse, locale, MODULE);
    }

    return ServiceUtil.returnSuccess();
}

From source file:jp.co.ntts.vhut.logic.PrivateCloudLogic.java

@Override
public void updatePublicIpResources() {
    int count = Ipv4ConversionUtil.getHostAddressCount(cloudConfig.exIpStartAddress,
            cloudConfig.exIpEndAddress);
    count -= cloudConfig.getExIpExcludeList().size();
    List<PublicIpResource> toBeInsertList = new ArrayList<PublicIpResource>();
    List<PublicIpResource> toBeUpdateList = new ArrayList<PublicIpResource>();
    Timestamp currentDate = TimestampUtil.getCurrentDateAsTimestamp();
    Timestamp minDate = TimestampUtil.subtract(currentDate, 1, TimestampUtil.Unit.DAY);
    Timestamp maxDate = TimestampUtil.add(cloudConfig.getReservationEndTimeMax(), 1, TimestampUtil.Unit.DAY);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    Map<String, PublicIpResource> resourceMap = new HashMap<String, PublicIpResource>();
    //?/*  w  ww .  j  av a  2  s  .co  m*/
    List<PublicIpResource> oldResourceList = jdbcManager.from(PublicIpResource.class)
            .where(new SimpleWhere().eq(publicIpResource().cloudId(), cloudId)
                    .ge(publicIpResource().time(), minDate).le(publicIpResource().time(), maxDate))
            .getResultList();
    for (PublicIpResource oldResource : oldResourceList) {
        String key = dateFormat.format(oldResource.time);
        resourceMap.put(key, oldResource);
    }
    //??
    Timestamp targetDate = currentDate;
    while (targetDate.before(maxDate)) {
        String key = dateFormat.format(targetDate);
        PublicIpResource oldResource = resourceMap.get(key);
        if (oldResource == null) {
            //
            PublicIpResource newResource = new PublicIpResource();
            newResource.id = targetDate.getTime();
            newResource.publicIpMax = count;
            newResource.publicIpTerminablyUsed = 0;
            newResource.cloudId = cloudId;
            newResource.time = targetDate;
            toBeInsertList.add(newResource);
        } else {
            //
            oldResource.publicIpMax = count;
            toBeUpdateList.add(oldResource);
        }
        targetDate = TimestampUtil.add(targetDate, 1, TimestampUtil.Unit.DAY);
    }
    //??
    if (toBeInsertList.size() > 0) {
        jdbcManager.insertBatch(toBeInsertList).execute();
    }
    //??
    if (toBeUpdateList.size() > 0) {
        jdbcManager.updateBatch(toBeUpdateList).execute();
    }
}

From source file:jp.co.ntts.vhut.logic.PrivateCloudLogic.java

@Override
public void updateStorageResource() {
    //??/*from   w  ww. j a v a2  s.c  o m*/
    Integer size = 0;
    Storage storage = jdbcManager.from(Storage.class).id(cloudConfig.getRhevStorageId()).getSingleResult();
    if (storage != null) {
        size = storage.physicalSize;
    }
    //?
    List<StorageResource> toBeInsertList = new ArrayList<StorageResource>();
    List<StorageResource> toBeUpdateList = new ArrayList<StorageResource>();
    Timestamp currentDate = TimestampUtil.getCurrentDateAsTimestamp();
    Timestamp minDate = TimestampUtil.subtract(currentDate, 1, TimestampUtil.Unit.DAY);
    Timestamp maxDate = TimestampUtil.add(cloudConfig.getReservationEndTimeMax(), 1, TimestampUtil.Unit.DAY);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    Map<String, StorageResource> resourceMap = new HashMap<String, StorageResource>();
    //?
    List<StorageResource> oldResourceList = jdbcManager.from(StorageResource.class)
            .where(new SimpleWhere().eq(storageResource().storageId(), cloudConfig.getRhevStorageId())
                    .ge(storageResource().time(), minDate).le(storageResource().time(), maxDate))
            .getResultList();
    for (StorageResource oldResource : oldResourceList) {
        String key = dateFormat.format(oldResource.time);
        resourceMap.put(key, oldResource);
    }
    //??
    Timestamp targetDate = currentDate;
    while (targetDate.before(maxDate)) {
        String key = dateFormat.format(targetDate);
        StorageResource oldResource = resourceMap.get(key);
        if (oldResource == null) {
            //
            StorageResource newResource = new StorageResource();
            newResource.id = targetDate.getTime();
            newResource.storageMax = size;
            newResource.storageTerminablyUsed = 0;
            newResource.storageId = cloudConfig.getRhevStorageId();
            newResource.time = targetDate;
            toBeInsertList.add(newResource);
        } else {
            //
            oldResource.storageMax = size;
            toBeUpdateList.add(oldResource);
        }
        targetDate = TimestampUtil.add(targetDate, 1, TimestampUtil.Unit.DAY);
    }
    //??
    if (toBeInsertList.size() > 0) {
        jdbcManager.insertBatch(toBeInsertList).execute();
    }
    //??
    if (toBeUpdateList.size() > 0) {
        jdbcManager.updateBatch(toBeUpdateList).execute();
    }
}

From source file:jp.co.ntts.vhut.logic.PrivateCloudLogic.java

@Override
public void updateClusterResource() {
    //?CPU???/*from   w w  w.j a va2 s .  com*/
    Integer totalCpuCore = 0;
    Integer totalMemory = 0;
    List<Host> hosts = jdbcManager.from(Host.class).leftOuterJoin(host().conflict())
            .where(new SimpleWhere().eq(host().clusterId(), cloudConfig.getRhevClusterId())).getResultList();
    for (Host host : hosts) {
        if (host.conflict != null && host.conflict.detail.equals("Removed")) {
            continue;
        }
        totalCpuCore += host.cpuCore;
        totalMemory += host.memory;
    }
    //?
    List<ClusterResource> toBeInsertList = new ArrayList<ClusterResource>();
    List<ClusterResource> toBeUpdateList = new ArrayList<ClusterResource>();
    Timestamp currentDate = TimestampUtil.getCurrentDateAsTimestamp();
    Timestamp minDate = TimestampUtil.subtract(currentDate, 1, TimestampUtil.Unit.DAY);
    Timestamp maxDate = TimestampUtil.add(cloudConfig.getReservationEndTimeMax(), 1, TimestampUtil.Unit.DAY);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    Map<String, ClusterResource> resourceMap = new HashMap<String, ClusterResource>();
    //?
    List<ClusterResource> oldResourceList = jdbcManager.from(ClusterResource.class)
            .where(new SimpleWhere().eq(clusterResource().clusterId(), cloudConfig.getRhevClusterId())
                    .ge(clusterResource().time(), minDate).le(clusterResource().time(), maxDate))
            .getResultList();
    for (ClusterResource oldResource : oldResourceList) {
        String key = dateFormat.format(oldResource.time);
        resourceMap.put(key, oldResource);
    }
    //??
    Timestamp targetDate = currentDate;
    while (targetDate.before(maxDate)) {
        String key = dateFormat.format(targetDate);
        ClusterResource oldResource = resourceMap.get(key);
        if (oldResource == null) {
            //
            ClusterResource newResource = new ClusterResource();
            newResource.id = targetDate.getTime();
            newResource.cpuCoreMax = totalCpuCore;
            newResource.cpuCoreTerminablyUsed = 0;
            newResource.memoryMax = totalMemory;
            newResource.memoryTerminablyUsed = 0;
            newResource.clusterId = cloudConfig.getRhevClusterId();
            newResource.time = targetDate;
            toBeInsertList.add(newResource);
        } else {
            //
            oldResource.cpuCoreMax = totalCpuCore;
            oldResource.memoryMax = totalMemory;
            toBeUpdateList.add(oldResource);
        }
        targetDate = TimestampUtil.add(targetDate, 1, TimestampUtil.Unit.DAY);
    }
    //??
    if (toBeInsertList.size() > 0) {
        jdbcManager.insertBatch(toBeInsertList).execute();
    }
    //??
    if (toBeUpdateList.size() > 0) {
        jdbcManager.updateBatch(toBeUpdateList).execute();
    }
}