List of usage examples for org.joda.time DateMidnight getMillis
public long getMillis()
From source file:com.google.android.apps.paco.Experiment.java
License:Open Source License
private void ensureScheduleIsGeneratedForPeriod(DateTime now, Context context) { DateMidnight periodStart = getPeriodStart(now); AlarmStore alarmStore = new AlarmStore(context); List<DateTime> signalTimes = alarmStore.getSignals(getId(), periodStart.getMillis()); if (signalTimes.size() == 0) { generateNextPeriod(periodStart, alarmStore); }//from w w w. j ava2s . co m }
From source file:com.google.android.apps.paco.Experiment.java
License:Open Source License
private void generateNextPeriod(DateMidnight generatingPeriodStart, AlarmStore alarmStore) { if (isExperimentOver(generatingPeriodStart.toDateTime())) { return;/* ww w .j av a 2s . com*/ } alarmStore.deleteSignalsForPeriod(getId(), generatingPeriodStart.getMillis()); List<DateTime> signalTimes = generateSignalTimesForPeriod(generatingPeriodStart); storeSignalTimes(generatingPeriodStart, signalTimes, alarmStore); }
From source file:com.google.android.apps.paco.Experiment.java
License:Open Source License
private void storeSignalTimes(DateMidnight periodStart, List<DateTime> times, AlarmStore alarmStore) { long periodStartMillis = periodStart.getMillis(); for (DateTime alarmTime : times) { alarmStore.storeSignal(periodStartMillis, getId(), alarmTime.getMillis()); }//from w w w . j av a 2s . co m }
From source file:com.google.walkaround.wave.server.googleimport.DaysSinceEpoch.java
License:Open Source License
private static long fromDateMidnight(DateMidnight d) { return fromMillis(d.getMillis()); }
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 {/* w w w . j a v a2s. 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:com.roflcode.fitnessChallenge.FetchFitbitActivities.java
License:Apache License
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { logger = serviceProvider.getLoggerService(FetchFitbitActivities.class); logger.debug("get fitbit activities ------------------------------"); String stackmobUserID = request.getParams().get("stackmob_user_id"); String startDateStr = request.getParams().get("start_date"); String endDateStr = request.getParams().get("end_date"); if (endDateStr == "") { endDateStr = startDateStr;//from w w w . ja v a 2 s. co m } if (stackmobUserID == null || stackmobUserID.isEmpty()) { HashMap<String, String> errParams = new HashMap<String, String>(); errParams.put("error", "stackmobUserID was empty or null"); return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request } FitbitApiClientAgent agent = AgentInitializer.GetInitializedAgent(serviceProvider, stackmobUserID); if (agent == null) { HashMap<String, String> errParams = new HashMap<String, String>(); errParams.put("error", "could not initialize fitbit client agent"); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errParams); // http 500 internal error } HashMap<String, String> credentials = AgentInitializer.GetStoredFitbitCredentials(serviceProvider, stackmobUserID); String fitbitUserID = credentials.get("fitbituserid"); LocalUserDetail user = new LocalUserDetail(stackmobUserID); FitbitUser fitbitUser = new FitbitUser(fitbitUserID); //LocalDate today = new LocalDate(DateTimeZone.UTC); DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy"); DateTime dt = formatter.parseDateTime(startDateStr); LocalDate startDate = new LocalDate(dt); dt = formatter.parseDateTime(endDateStr); LocalDate endDate = new LocalDate(dt); //TimeZone tz = TimeZone.getTimeZone("GMT-8:00"); //LocalDate today = new LocalDate(DateTimeZone.forTimeZone(tz)); //LocalDate today = new LocalDate(DateTimeZone.forTimeZone(tz)); //LocalDate yesterday = today.minusDays(1); logger.debug("entering date loop " + startDate.toString() + " end: " + endDate.toString()); for (LocalDate date = startDate; date.isBefore(endDate) || date.isEqual(endDate); date = date.plusDays(1)) { logger.debug("date: " + date.toString()); Activities activities; try { activities = agent.getActivities(user, fitbitUser, date); } catch (FitbitAPIException ex) { logger.error("failed to get activities", ex); HashMap<String, String> errParams = new HashMap<String, String>(); errParams.put("error", "could not get activities"); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errParams); // http 500 internal error } ActivitiesSummary summary = activities.getSummary(); // private Integer floors = null; // private Double elevation = null; // private List<ActivityDistance> distances; DataService dataService = serviceProvider.getDataService(); DateMidnight dateMidnight = date.toDateMidnight(); long millis = dateMidnight.getMillis(); List<SMCondition> query; List<SMObject> result; // build a query query = new ArrayList<SMCondition>(); query.add(new SMEquals("theusername", new SMString(stackmobUserID))); query.add(new SMEquals("activity_date", new SMInt(millis))); // execute the query try { boolean newActivity = false; SMValue activityId; result = dataService.readObjects("activity", query); SMObject activityObject; //activity was in the datastore, so update if (result != null && result.size() == 1) { activityObject = result.get(0); List<SMUpdate> update = new ArrayList<SMUpdate>(); update.add(new SMSet("active_score", new SMInt((long) summary.getActiveScore()))); update.add(new SMSet("steps", new SMInt((long) summary.getSteps()))); update.add(new SMSet("floors", new SMInt((long) summary.getFloors()))); update.add(new SMSet("sedentary_minutes", new SMInt((long) summary.getSedentaryMinutes()))); update.add(new SMSet("lightly_active_minutes", new SMInt((long) summary.getLightlyActiveMinutes()))); update.add( new SMSet("fairly_active_minutes", new SMInt((long) summary.getFairlyActiveMinutes()))); update.add(new SMSet("very_active_minutes", new SMInt((long) summary.getVeryActiveMinutes()))); activityId = activityObject.getValue().get("activity_id"); logger.debug("update object"); dataService.updateObject("activity", activityId, update); logger.debug("updated object"); } else { Map<String, SMValue> activityMap = new HashMap<String, SMValue>(); activityMap.put("theusername", new SMString(stackmobUserID)); activityMap.put("activity_date", new SMInt(millis)); activityMap.put("activity_date_str", new SMString(date.toString())); activityMap.put("active_score", new SMInt((long) summary.getActiveScore())); activityMap.put("steps", new SMInt((long) summary.getSteps())); activityMap.put("floors", new SMInt((long) summary.getFloors())); activityMap.put("sedentary_minutes", new SMInt((long) summary.getSedentaryMinutes())); activityMap.put("lightly_active_minutes", new SMInt((long) summary.getLightlyActiveMinutes())); activityMap.put("fairly_active_minutes", new SMInt((long) summary.getFairlyActiveMinutes())); activityMap.put("very_active_minutes", new SMInt((long) summary.getVeryActiveMinutes())); activityObject = new SMObject(activityMap); logger.debug("create object"); activityObject = dataService.createObject("activity", activityObject); logger.debug("created object"); activityId = activityObject.getValue().get("activity_id"); newActivity = true; } } catch (InvalidSchemaException e) { HashMap<String, String> errMap = new HashMap<String, String>(); errMap.put("error", "invalid_schema"); errMap.put("detail", e.toString()); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error } catch (DatastoreException e) { HashMap<String, String> errMap = new HashMap<String, String>(); errMap.put("error", "datastore_exception"); errMap.put("detail", e.toString()); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error } catch (Exception e) { HashMap<String, String> errMap = new HashMap<String, String>(); errMap.put("error", "unknown"); errMap.put("detail", e.toString()); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error } } Map<String, Object> returnMap = new HashMap<String, Object>(); returnMap.put("success?", "think so"); // returnMap.put("activity_id", activityId); // returnMap.put("newActivity", newActivity); //returnMap.put("activitiesJson", activities); logger.debug("completed get activities"); return new ResponseToProcess(HttpURLConnection.HTTP_OK, returnMap); }
From source file:ddf.metrics.plugin.webconsole.MetricsWebConsolePlugin.java
License:Open Source License
void addMonthlyReportUrls(PrintWriter pw, int numMonthlyReports, String metricsServiceUrl) { DateTime input = newDateTime();/*from w w w . j a v a 2s .co m*/ LOGGER.debug("NOW: {}", input); for (int i = 1; i <= numMonthlyReports; i++) { try { DateMidnight startOfLastMonth = new DateMidnight(input.minusMonths(i).withDayOfMonth(1)); String startDate = urlEncodeDate(startOfLastMonth); LOGGER.debug("Previous Month (start): {} (ms = {})", startDate, startOfLastMonth.getMillis()); DateTime endOfLastMonth = startOfLastMonth.plusMonths(1).toDateTime().minus(1 /* millisecond */); String endDate = urlEncodeDate(endOfLastMonth); LOGGER.debug("Previous Month (end): {} (ms = {})", endOfLastMonth, endOfLastMonth.getMillis()); startTableRow(pw, i); addCellLabelForRange(pw, startOfLastMonth, endOfLastMonth); addXLSCellLink(pw, startDate, endDate, metricsServiceUrl); addPPTCellLink(pw, startDate, endDate, metricsServiceUrl); endTableRow(pw); } catch (UnsupportedEncodingException e) { LOGGER.info("Unsupported encoding exception adding monthly reports", e); } } }
From source file:ddf.metrics.plugin.webconsole.MetricsWebConsolePlugin.java
License:Open Source License
void addYearlyReportUrls(PrintWriter pw, int numYearlyReports, String metricsServiceUrl) { DateTime input = newDateTime();// w ww .ja v a 2 s . c o m LOGGER.debug("NOW: {}", input); for (int i = 1; i <= numYearlyReports; i++) { try { DateMidnight startOfLastYear = new DateMidnight(input.minusYears(1).withDayOfYear(1)); String startDate = urlEncodeDate(startOfLastYear); LOGGER.debug("Previous Year (start): {} (ms = {})", startOfLastYear, startOfLastYear.getMillis()); DateTime endOfLastYear = startOfLastYear.plusYears(1).toDateTime().minus(1 /* millisecond */); String endDate = urlEncodeDate(endOfLastYear); LOGGER.debug("Previous Year (end): {}, (ms = {})", endOfLastYear, endOfLastYear.getMillis()); String urlText = startOfLastYear.toString("yyyy"); LOGGER.debug("URL text = [{}]", urlText); startTableRow(pw, i); addCellLabel(pw, urlText); addXLSCellLink(pw, startDate, endDate, metricsServiceUrl); addPPTCellLink(pw, startDate, endDate, metricsServiceUrl); endTableRow(pw); } catch (UnsupportedEncodingException e) { LOGGER.info("Unsupported encoding exception adding yearly reports", e); } } }
From source file:hu.akarnokd.utils.database.DBParams.java
License:Apache License
/** * Add a new parameter value.//from w w w. j a va 2 s . c o m * @param value the value * @return this * @throws SQLException on error */ public DBParams add(DateMidnight value) throws SQLException { if (value != null) { pstmt.setDate(p++, new Date(value.getMillis())); } else { pstmt.setNull(p++, Types.DATE); } return this; }
From source file:io.viewserver.core.BusinessDayCalculator.java
License:Apache License
public int getBusinessDay(ReadableDateTime start, ReadableDateTime end) { DateMidnight startMidnight = new DateMidnight(start); DateMidnight endMidnight = new DateMidnight(end); int weekdayStart = startMidnight.get(DateTimeFieldType.dayOfWeek()); int weekdayEnd = endMidnight.get(DateTimeFieldType.dayOfWeek()); if (weekdayStart == DateTimeConstants.SATURDAY) { startMidnight = startMidnight.plusDays(2); weekdayStart = DateTimeConstants.MONDAY; } else if (weekdayStart == DateTimeConstants.SUNDAY) { startMidnight = startMidnight.plusDays(1); weekdayStart = DateTimeConstants.MONDAY; }/*from w ww . jav a 2 s.c om*/ if (weekdayEnd == DateTimeConstants.SATURDAY) { endMidnight = endMidnight.minusDays(1); weekdayEnd = DateTimeConstants.FRIDAY; } else if (weekdayEnd == DateTimeConstants.SUNDAY) { endMidnight = endMidnight.minusDays(2); weekdayEnd = DateTimeConstants.FRIDAY; } int days = Days.daysBetween(startMidnight, endMidnight).getDays(); startMidnight = startMidnight.plusDays(DateTimeConstants.SATURDAY - weekdayStart); endMidnight = endMidnight.plusDays(DateTimeConstants.SATURDAY - weekdayEnd); int daysBetweenWeekends = (int) ((endMidnight.getMillis() - startMidnight.getMillis()) / (24 * 60 * 60 * 1000)); int weekendDays = daysBetweenWeekends * 2 / 7; days -= weekendDays; return days; }