Example usage for org.joda.time DateMidnight DateMidnight

List of usage examples for org.joda.time DateMidnight DateMidnight

Introduction

In this page you can find the example usage for org.joda.time DateMidnight DateMidnight.

Prototype

public DateMidnight(Object instant, Chronology chronology) 

Source Link

Document

Constructs an instance from an Object that represents a datetime, using the specified chronology.

Usage

From source file:com.google.walkaround.wave.server.googleimport.DaysSinceEpoch.java

License:Open Source License

public static DateMidnight toDateMidnightUTC(long daysSinceEpoch) {
    return new DateMidnight(daysSinceEpoch * MILLIS_PER_DAY, DateTimeZone.UTC);
}

From source file:com.netflix.ice.basic.BasicLineItemProcessor.java

License:Apache License

public Result process(long startMilli, boolean processDelayed, ProcessorConfig config, String[] items,
        Map<Product, ReadWriteData> usageDataByProduct, Map<Product, ReadWriteData> costDataByProduct,
        Map<String, Double> ondemandRate) {
    if (StringUtils.isEmpty(items[accountIdIndex]) || StringUtils.isEmpty(items[productIndex])
            || StringUtils.isEmpty(items[usageTypeIndex]) || StringUtils.isEmpty(items[operationIndex])
            || StringUtils.isEmpty(items[usageQuantityIndex]) || StringUtils.isEmpty(items[costIndex]))
        return Result.ignore;

    Account account = config.accountService.getAccountById(items[accountIdIndex]);
    if (account == null)
        return Result.ignore;

    double usageValue = Double.parseDouble(items[usageQuantityIndex]);
    double costValue = Double.parseDouble(items[costIndex]);

    long millisStart;
    long millisEnd;
    try {/*from w  ww . ja  va2s  . c o m*/
        millisStart = amazonBillingDateFormat.parseMillis(items[startTimeIndex]);
        millisEnd = amazonBillingDateFormat.parseMillis(items[endTimeIndex]);
    } catch (IllegalArgumentException e) {
        millisStart = amazonBillingDateFormat2.parseMillis(items[startTimeIndex]);
        millisEnd = amazonBillingDateFormat2.parseMillis(items[endTimeIndex]);
    }

    Product product = config.productService.getProductByAwsName(items[productIndex]);
    boolean reservationUsage = "Y".equals(items[reservedIndex]);
    ReformedMetaData reformedMetaData = reform(millisStart, config, product, reservationUsage,
            items[operationIndex], items[usageTypeIndex], items[descriptionIndex], costValue);
    product = reformedMetaData.product;
    Operation operation = reformedMetaData.operation;
    UsageType usageType = reformedMetaData.usageType;
    Zone zone = Zone.getZone(items[zoneIndex], reformedMetaData.region);

    int startIndex = (int) ((millisStart - startMilli) / AwsUtils.hourMillis);
    int endIndex = (int) ((millisEnd + 1000 - startMilli) / AwsUtils.hourMillis);

    Result result = Result.hourly;
    if (product == Product.ec2_instance) {
        result = processEc2Instance(processDelayed, reservationUsage, operation, zone);
    } else if (product == Product.redshift) {
        result = processRedshift(processDelayed, reservationUsage, operation, costValue);
    } else if (product == Product.data_transfer) {
        result = processDataTranfer(processDelayed, usageType);
    } else if (product == Product.cloudhsm) {
        result = processCloudhsm(processDelayed, usageType);
    } else if (product == Product.ebs) {
        result = processEbs(usageType);
    } else if (product == Product.rds) {
        result = processRds(usageType);
    }

    if (result == Result.ignore || result == Result.delay)
        return result;

    if (usageType.name.startsWith("TimedStorage-ByteHrs"))
        result = Result.daily;

    boolean monthlyCost = StringUtils.isEmpty(items[descriptionIndex]) ? false
            : items[descriptionIndex].toLowerCase().contains("-month");

    ReadWriteData usageData = usageDataByProduct.get(null);
    ReadWriteData costData = costDataByProduct.get(null);
    ReadWriteData usageDataOfProduct = usageDataByProduct.get(product);
    ReadWriteData costDataOfProduct = costDataByProduct.get(product);

    if (result == Result.daily) {
        DateMidnight dm = new DateMidnight(millisStart, DateTimeZone.UTC);
        millisStart = dm.getMillis();
        startIndex = (int) ((millisStart - startMilli) / AwsUtils.hourMillis);
        endIndex = startIndex + 24;
    } else if (result == Result.monthly) {
        startIndex = 0;
        endIndex = usageData.getNum();
        int numHoursInMonth = new DateTime(startMilli, DateTimeZone.UTC).dayOfMonth().getMaximumValue() * 24;
        usageValue = usageValue * endIndex / numHoursInMonth;
        costValue = costValue * endIndex / numHoursInMonth;
    }

    if (monthlyCost) {
        int numHoursInMonth = new DateTime(startMilli, DateTimeZone.UTC).dayOfMonth().getMaximumValue() * 24;
        usageValue = usageValue * numHoursInMonth;
    }

    int[] indexes;
    if (endIndex - startIndex > 1) {
        usageValue = usageValue / (endIndex - startIndex);
        costValue = costValue / (endIndex - startIndex);
        indexes = new int[endIndex - startIndex];
        for (int i = 0; i < indexes.length; i++)
            indexes[i] = startIndex + i;
    } else {
        indexes = new int[] { startIndex };
    }

    TagGroup tagGroup = TagGroup.getTagGroup(account, reformedMetaData.region, zone, product, operation,
            usageType, null);
    TagGroup resourceTagGroup = null;

    if (costValue > 0 && !reservationUsage && product == Product.ec2_instance
            && tagGroup.operation == Operation.ondemandInstances) {
        String key = operation + "|" + tagGroup.region + "|" + usageType;
        ondemandRate.put(key, costValue / usageValue);
    }

    double resourceCostValue = costValue;
    if (items.length > resourceIndex && !StringUtils.isEmpty(items[resourceIndex])
            && config.resourceService != null) {

        if (product == Product.ec2_instance && !reservationUsage && operation == Operation.ondemandInstances)
            operation = Operation
                    .getReservedInstances(config.reservationService.getDefaultReservationUtilization(0L));

        if (product == Product.ec2_instance && operation instanceof Operation.ReservationOperation) {
            UsageType usageTypeForPrice = usageType;
            if (usageType.name.endsWith(InstanceOs.others.name())) {
                usageTypeForPrice = UsageType.getUsageType(
                        usageType.name.replace(InstanceOs.others.name(), InstanceOs.windows.name()),
                        usageType.unit);
            }
            try {
                resourceCostValue = usageValue * config.reservationService.getLatestHourlyTotalPrice(
                        millisStart, tagGroup.region, usageTypeForPrice,
                        config.reservationService.getDefaultReservationUtilization(0L));
            } catch (Exception e) {
                logger.error("failed to get RI price for " + tagGroup.region + " " + usageTypeForPrice);
                resourceCostValue = -1;
            }
        }

        String resourceGroupStr = config.resourceService.getResource(account, reformedMetaData.region, product,
                items[resourceIndex], items, millisStart);
        if (!StringUtils.isEmpty(resourceGroupStr)) {
            ResourceGroup resourceGroup = ResourceGroup.getResourceGroup(resourceGroupStr);
            resourceTagGroup = TagGroup.getTagGroup(account, reformedMetaData.region, zone, product, operation,
                    usageType, resourceGroup);
            if (usageDataOfProduct == null) {
                usageDataOfProduct = new ReadWriteData();
                costDataOfProduct = new ReadWriteData();
                usageDataByProduct.put(product, usageDataOfProduct);
                costDataByProduct.put(product, costDataOfProduct);
            }
        }
    }

    if (config.randomizer != null && product == Product.monitor)
        return result;

    for (int i : indexes) {

        if (config.randomizer != null) {

            if (tagGroup.product != Product.rds && tagGroup.product != Product.s3
                    && usageData.getData(i).get(tagGroup) != null)
                break;

            long time = millisStart + i * AwsUtils.hourMillis;
            usageValue = config.randomizer.randomizeUsage(time,
                    resourceTagGroup == null ? tagGroup : resourceTagGroup, usageValue);
            costValue = usageValue * config.randomizer.randomizeCost(tagGroup);
        }
        if (product != Product.monitor) {
            Map<TagGroup, Double> usages = usageData.getData(i);
            Map<TagGroup, Double> costs = costData.getData(i);

            addValue(usages, tagGroup, usageValue, config.randomizer == null || tagGroup.product == Product.rds
                    || tagGroup.product == Product.s3);
            addValue(costs, tagGroup, costValue, config.randomizer == null || tagGroup.product == Product.rds
                    || tagGroup.product == Product.s3);
        } else {
            resourceCostValue = usageValue * config.costPerMonitorMetricPerHour;
        }

        if (resourceTagGroup != null) {
            Map<TagGroup, Double> usagesOfResource = usageDataOfProduct.getData(i);
            Map<TagGroup, Double> costsOfResource = costDataOfProduct.getData(i);

            if (config.randomizer == null || tagGroup.product == Product.rds
                    || tagGroup.product == Product.s3) {
                addValue(usagesOfResource, resourceTagGroup, usageValue, product != Product.monitor);
                if (!config.useCostForResourceGroup.equals("modeled") || resourceCostValue < 0) {
                    addValue(costsOfResource, resourceTagGroup, costValue, product != Product.monitor);

                } else {
                    addValue(costsOfResource, resourceTagGroup, resourceCostValue, product != Product.monitor);
                }
            } else {
                Map<String, Double> distribution = config.randomizer.getDistribution(tagGroup);
                for (Map.Entry<String, Double> entry : distribution.entrySet()) {
                    String app = entry.getKey();
                    double dist = entry.getValue();
                    resourceTagGroup = TagGroup.getTagGroup(account, reformedMetaData.region, zone, product,
                            operation, usageType, ResourceGroup.getResourceGroup(app));
                    double usage = usageValue * dist;
                    if (product == Product.ec2_instance)
                        usage = (int) usageValue * dist;
                    addValue(usagesOfResource, resourceTagGroup, usage, false);
                    addValue(costsOfResource, resourceTagGroup,
                            usage * config.randomizer.randomizeCost(tagGroup), false);
                }
            }
        }
    }

    return result;
}

From source file:io.viewserver.expression.function.DateToBusinessDay.java

License:Apache License

@Override
public int getInt(int row) {
    return businessDayCalculator.getBusinessDay(new DateMidnight(dateExpression.getLong(row), DateTimeZone.UTC),
            DateMidnight.now(DateTimeZone.UTC));
}

From source file:org.jasig.portlet.calendar.adapter.CalendarEventsDao.java

License:Apache License

/**
 * Get a JSON-appropriate representation of each recurrence of an event
 * within the specified time period.//from  w  ww.j av a  2 s. co m
 *
 * @param e
 * @param interval
 * @param usersConfiguredDateTimeZone
 * @return
 * @throws IOException
 * @throws URISyntaxException
 * @throws ParseException
 */
protected Set<CalendarDisplayEvent> getDisplayEvents(VEvent e, Interval interval, Locale locale,
        DateTimeZone usersConfiguredDateTimeZone) throws IOException, URISyntaxException, ParseException {

    final VEvent event = (VEvent) e.copy();

    DateTime eventStart;
    DateTime eventEnd = null;

    if (event.getStartDate().getTimeZone() == null && !event.getStartDate().isUtc()) {
        if (log.isDebugEnabled()) {
            log.debug("Identified event " + event.getSummary() + " as a floating event");
        }

        int offset = usersConfiguredDateTimeZone.getOffset(event.getStartDate().getDate().getTime());
        eventStart = new DateTime(event.getStartDate().getDate().getTime() - offset,
                usersConfiguredDateTimeZone);
        if (event.getEndDate() != null) {
            eventEnd = new DateTime(event.getEndDate().getDate().getTime() - offset,
                    usersConfiguredDateTimeZone);
        }

    } else {
        eventStart = new DateTime(event.getStartDate().getDate(), usersConfiguredDateTimeZone);
        if (event.getEndDate() != null) {
            eventEnd = new DateTime(event.getEndDate().getDate(), usersConfiguredDateTimeZone);
        }
    }

    if (eventEnd == null) {
        eventEnd = eventStart;
    }

    // Multi-day events may begin in the past;  make sure to choose a date in range for the first pass...
    final Date firstDayToProcess = interval.contains(event.getStartDate().getDate().getTime())
            ? event.getStartDate().getDate()
            : interval.getStart().toDate();

    DateMidnight startOfTheSpecificDay = new DateMidnight(firstDayToProcess, usersConfiguredDateTimeZone);
    DateMidnight endOfTheSpecificDay = startOfTheSpecificDay.plusDays(1);

    final DateTimeFormatter df = getDateFormatter(locale, usersConfiguredDateTimeZone);
    final DateTimeFormatter tf = getTimeFormatter(locale, usersConfiguredDateTimeZone);
    final Set<CalendarDisplayEvent> events = new HashSet<CalendarDisplayEvent>();
    final Interval eventInterval = new Interval(eventStart, eventEnd);

    do {
        final Interval theSpecificDay = new Interval(startOfTheSpecificDay.getMillis(),
                endOfTheSpecificDay.getMillis(), usersConfiguredDateTimeZone);

        /*
         * Test if the event interval abuts the start of the day or is within the day.
         * This start time check is needed for the corner case where a zero duration interval
         * is set for midnight.
         * The start times are tested directly as opposed to using abuts() because that method
         * also returns true if the intervals abut at the end of the day. We want to associate
         * instant events that start at midnight with the starting day, not the ending day.
         */
        if (theSpecificDay.getStart().isEqual(eventStart) || theSpecificDay.overlaps(eventInterval)) {
            final CalendarDisplayEvent json = new CalendarDisplayEvent(event, eventInterval, theSpecificDay, df,
                    tf);
            events.add(json);
        }

        startOfTheSpecificDay = startOfTheSpecificDay.plusDays(1);
        endOfTheSpecificDay = endOfTheSpecificDay.plusDays(1);

    } while (!startOfTheSpecificDay.isAfter(eventEnd) && interval.contains(startOfTheSpecificDay));

    return events;
}

From source file:org.jasig.portlet.calendar.util.DateUtil.java

License:Apache License

public static Interval getInterval(String startDate, int days, PortletRequest request) throws ParseException {
    final PortletSession session = request.getPortletSession();
    final String timezone = (String) session.getAttribute("timezone");
    final DateTimeZone tz = DateTimeZone.forID(timezone);
    final DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern("MMddyyyy").toFormatter()
            .withZone(tz);//w  w  w  .  jav a 2 s . com
    final DateMidnight start = new DateMidnight(df.parseDateTime(startDate), tz);

    return getInterval(start, days);
}

From source file:org.obm.push.protocol.data.TimeZoneConverterImpl.java

License:Open Source License

private ASSystemTime standardDate(TimeZone timeZone) {
    DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(timeZone);

    DateMidnight dateMidnight = new DateMidnight(DateTimeUtils.getInstantMillis(null), dateTimeZone);

    long firstDSTTransitionInstant = dateTimeZone.nextTransition(dateMidnight.getMillis());
    long secondDSTTransitionInstant = dateTimeZone.nextTransition(firstDSTTransitionInstant);

    if (firstDSTTransitionInstant == secondDSTTransitionInstant) {
        return systemTimeFromInstant(0, DateTimeZone.UTC);
    }/*from   w  w  w  .j  av a2  s. c  o  m*/

    if (dateTimeZone.isStandardOffset(firstDSTTransitionInstant)) {
        return systemTimeFromInstant(firstDSTTransitionInstant, dateTimeZone);
    }
    return systemTimeFromInstant(secondDSTTransitionInstant, dateTimeZone);
}

From source file:org.obm.push.protocol.data.TimeZoneConverterImpl.java

License:Open Source License

private ASSystemTime dayLightDate(TimeZone timeZone) {
    DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(timeZone);

    DateMidnight dateMidnight = new DateMidnight(DateTimeUtils.getInstantMillis(null), dateTimeZone);

    long firstDSTTransitionInstant = dateTimeZone.nextTransition(dateMidnight.getMillis());
    long secondDSTTransitionInstant = dateTimeZone.nextTransition(firstDSTTransitionInstant);

    if (firstDSTTransitionInstant == secondDSTTransitionInstant) {
        return systemTimeFromInstant(0, DateTimeZone.UTC);
    }/*from  w w w . j  ava  2s  . c o m*/

    if (dateTimeZone.isStandardOffset(firstDSTTransitionInstant)) {
        return systemTimeFromInstant(secondDSTTransitionInstant, dateTimeZone);
    }
    return systemTimeFromInstant(firstDSTTransitionInstant, dateTimeZone);
}

From source file:org.openmrs.calculation.AgeCalculation.java

License:Open Source License

/**
 * @see org.openmrs.calculation.patient.PatientAtATimeCalculation#evaluateForPatient(EvaluationInstanceData,
 *      Integer, Map, PatientCalculationContext)
 *//*from w w  w  .j a va2  s .  com*/
@Override
public CalculationResult evaluateForPatient(EvaluationInstanceData instanceData, Integer patientId,
        Map<String, Object> parameterValues, PatientCalculationContext context) {
    BirthdateData data = (BirthdateData) instanceData;
    CalculationResult r = null;
    Date birthdate = data.get(patientId);
    if (birthdate != null) {
        Chronology isoChronology = ISOChronology.getInstance();
        DateMidnight birthDate = new DateMidnight(birthdate, isoChronology);
        DateMidnight asOfDate = new DateMidnight(context.getNow(), isoChronology);
        if (parameterValues != null && "months".equals(parameterValues.get("units"))) {
            int months = Months.monthsBetween(birthDate, asOfDate).getMonths();
            r = new SimpleResult(months, this, context);
        } else {
            int years = Years.yearsBetween(birthDate, asOfDate).getYears();
            r = new SimpleResult(years, this, context);
        }
    }
    return r;
}

From source file:org.projectforge.web.calendar.CalendarPage.java

License:Open Source License

/**
 * @param startDate/*from w  w w.  j a  va2 s  . c o m*/
 * @return this for chaining.
 */
public CalendarPage setStartDate(final Date startDate) {
    form.getFilter().setStartDate(new DateMidnight(startDate, PFUserContext.getDateTimeZone()));
    return this;
}

From source file:org.sonatype.nexus.timeline.internal.DefaultTimeline.java

License:Open Source License

/**
 * Calculates the expected cluster name where given timestamp should be located. It adds new cluster if cluster with
 * calculated name not exists, hence, after the return from this method it is guaranteed that the cluster with name
 * returned does exists. Clusters have common prefixes (see {@link #DB_CLUSTER_PREFIX}) and suffix is timestamp's
 * date// w  w w .j  av a2  s. c om
 * (rounded to midnight) as string with pattern {@code YYYYMMDD}. As OrientDB DDL is not atomic, this method must be
 * mutually exclusive with method {@link #purgeOlderThan(int)}, hence both should be synchronized (or called from
 * synchronized block like this method). This method must be called outside of a TX as it performs DDL.
 */
private String maybeAddNewCluster(final ODatabaseDocumentTx db, final long timestamp) {
    final String name = String.format("%s%s", DB_CLUSTER_PREFIX,
            new DateMidnight(timestamp, DateTimeZone.UTC).toString("YYYYMMdd"));
    int cid = db.getClusterIdByName(name); // undocumented: if cluster not exists, returns -1
    if (cid == -1) {
        cid = db.addCluster(name);
        final OSchema schema = db.getMetadata().getSchema();
        final OClass type = schema.getClass(DB_CLASS);
        type.addClusterId(cid);
        log.info("Created new journal cluster; id: {}, name: {}", cid, name);
    } else {
        log.debug("Journal cluster exists; id: {}, name: {}", cid, name);
    }
    return name;
}