List of usage examples for org.joda.time DateTime getDayOfMonth
public int getDayOfMonth()
From source file:nl.welteninstituut.tel.la.importers.fitbit.FitbitTask.java
License:Open Source License
@Override public void run() { try {//from w ww . ja v a 2 s . com OauthServiceAccount account = getAccount(AccountJDO.FITBITCLIENT, accountId); if (account != null) { if (start == null) { if (account.getLastSynced() == null) { String startDate = Configuration.get(Configuration.STARTDATE); if (startDate != null) { start = new DateTime(startDate + "T00:00"); } else { LOG.severe(Configuration.STARTDATE + " is missing from configuration"); } } else { start = new DateTime(account.getLastSynced()).withSecondOfMinute(0).withMillisOfSecond(0) .plusMinutes(1); } } if (deviceLastSynced == null) { deviceLastSynced = getDeviceLastSynced(account); } if (start != null && deviceLastSynced != null && start.isBefore(deviceLastSynced)) { DateTime end = start.plusHours(4); if (end.isAfter(deviceLastSynced)) { end = new DateTime(deviceLastSynced).withSecondOfMinute(0).withMillisOfSecond(0) .plusMinutes(1); } // check if the period spans to next day if (end.getDayOfMonth() != start.getDayOfMonth()) { // if so reset to start of day because heart rate can // only // be retrieved for a single calendar day end = end.withTimeAtStartOfDay(); } System.out.println("processing from " + start + " to " + end); JSONObject stepCountData = new JSONObject(readURL(getStepcountURL(start, end), account)); JSONObject heartRateData = new JSONObject(readURL(getHeartrateURL(start, end), account)); if (!stepCountData.has("errors") && !heartRateData.has("errors")) { AccountJDO pa = AccountManager.getAccount(account.getPrimaryAccount()); String mbox = pa != null ? pa.getEmail() : null; String xapiTemplate = "{\"timestamp\":\"%s\"," + "\"actor\": {\"objectType\": \"Agent\",\"mbox\":\"mailto:" + mbox + "\"}," + "\"verb\":{\"id\":\"https://brindlewaye.com/xAPITerms/verbs/walked\"," + "\"display\":{\"en-US\":\"indicates the user walked number of steps\"}}," + "\"object\":{\"objectType\":\"Activity\",\"id\":\"StepCount\",\"definition\":{\"name\":{\"en-US\":\"step count\"}," + "\"description\":{\"en-US\":\"step count\"},\"type\":\"http://activitystrea.ms/schema/1.0/event\"}}," + "\"result\":{\"response\":\"%d\"}}"; processData(stepCountData, "activities-steps", xapiTemplate); xapiTemplate = "{\"timestamp\":\"%s\"," + "\"actor\": {\"objectType\": \"Agent\",\"mbox\":\"mailto:" + mbox + "\"}," + "\"verb\":{\"id\":\"http://adlnet.gov/expapi/verbs/experienced\"," + "\"display\":{\"en-US\":\"indicates the user experienced something\"}}," + "\"object\":{\"objectType\":\"Activity\",\"id\":\"HeartRate\",\"definition\":{\"name\":{\"en-US\":\"heart rate\"}," + "\"description\":{\"en-US\":\"heart rate\"},\"type\":\"http://activitystrea.ms/schema/1.0/event\"}}," + "\"result\":{\"response\":\"%d\"}}"; processData(heartRateData, "activities-heart", xapiTemplate); } // store time of last block data that was // synchronized account.setLastSynced(end.toDate()); OauthServiceAccountManager.updateOauthServiceAccount(account); // Daisy chain task for next period if (end.isBefore(deviceLastSynced)) { ImportTask.scheduleTask(new FitbitTask(accountId, end, deviceLastSynced)); } } } else { LOG.severe("no fitbit service account found for " + accountId); } } catch (JSONException | IOException e) { LOG.severe("aborting fitbit import for " + accountId + " reason: " + e.getMessage()); } }
From source file:orc.lib.orchard.forms.DateTimeRangesField.java
License:Open Source License
private static String toTimeID(final DateTime date) { return date.getYear() + "_" + date.getMonthOfYear() + "_" + date.getDayOfMonth() + "_" + date.getHourOfDay();// ww w.j av a 2 s. c o m }
From source file:org.adl.datamodels.datatypes.DateTimeValidatorImpl.java
/** * Compares two valid data model elements for equality. * /*from w w w. j a v a 2s .co m*/ * @param iFirst The first value being compared. * * @param iSecond The second value being compared. * * @param iDelimiters The common set of delimiters associated with the * values being compared. * * @return Returns <code>true</code> if the two values are equal, otherwise * <code>false</code>. */ @Override public boolean compare(String iFirst, String iSecond, List<DMDelimiter> iDelimiters) { boolean equal = true; DateTimeFormatter dtp = ISODateTimeFormat.dateTimeParser(); try { // Parse the first string and remove the sub-seconds DateTime dt1 = dtp.parseDateTime(iFirst); dt1 = new DateTime(dt1.getYear(), dt1.getMonthOfYear(), dt1.getDayOfMonth(), dt1.getHourOfDay(), dt1.getMinuteOfHour(), dt1.getSecondOfMinute(), 0); // Parse the second string and remove the sub-seconds DateTime dt2 = dtp.parseDateTime(iSecond); dt2 = new DateTime(dt2.getYear(), dt2.getMonthOfYear(), dt2.getDayOfMonth(), dt2.getHourOfDay(), dt2.getMinuteOfHour(), dt2.getSecondOfMinute(), 0); equal = dt1.equals(dt2); } catch (Exception e) { // String format error -- these cannot be equal equal = false; } return equal; }
From source file:org.akop.crosswords.fragment.DatePickerFragment.java
License:Open Source License
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { DateTime dateTime = null; Bundle args = getArguments();// w ww . j ava 2 s .c o m if (args != null) { long dateMillis = args.getLong("dateMillis", -1); if (dateMillis != -1) { dateTime = new DateTime(dateMillis); } } if (dateTime == null) { dateTime = DateTime.now(); } final DatePickerDialog pickerDialog = new DatePickerDialog(getActivity(), R.style.Theme_Crosswords_Default_Dialog, null, dateTime.getYear(), dateTime.getMonthOfYear() - 1, dateTime.getDayOfMonth()); // Workaround for the JellyBean bug // http://stackoverflow.com/questions/11444238/jelly-bean-datepickerdialog-is-there-a-way-to-cancel pickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { notifyListener(pickerDialog.getDatePicker()); } }); pickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(android.R.string.cancel), (DialogInterface.OnClickListener) null); return pickerDialog; }
From source file:org.akop.crosswords.model.PuzzleSource.java
License:Open Source License
public String createDateUrl(DateTime date) { StringBuilder sb = new StringBuilder(); int start = 0; Matcher matcher = URL_TEMPLATE_FINDER.matcher(mUrlTemplate); while (matcher.find()) { sb.append(mUrlTemplate, start, matcher.start()); start = matcher.end();/*from w w w .ja v a2s . co m*/ String match = matcher.group(1); if (PH_TWO_DIGIT_YEAR.equals(match)) { String year = String.format("%02d", date.getYear()); sb.append(year.substring(year.length() - 2)); } else if (PH_TWO_DIGIT_MONTH.equals(match)) { sb.append(String.format("%02d", date.getMonthOfYear())); } else if (PH_TWO_DIGIT_DAY.equals(match)) { sb.append(String.format("%02d", date.getDayOfMonth())); } } sb.append(mUrlTemplate, start, mUrlTemplate.length()); return sb.toString(); }
From source file:org.alfresco.po.share.workflow.WorkFlowPage.java
License:Open Source License
/** * Method to select a date from Calender date picker. The date should be in * "dd/MM/yyyy" format/*from ww w .j a v a2 s . co m*/ * * @param date String */ public void selectDateFromCalendar(String date) throws InterruptedException { if (StringUtils.isEmpty(date)) { throw new IllegalArgumentException("Date cannot be empty"); } DateTime dueDate; int due; try { dueDate = DateTimeFormat.forPattern("dd/MM/yyyy").parseDateTime(date); due = dueDate.getDayOfMonth(); } catch (IllegalArgumentException iae) { throw new IllegalArgumentException("Due date should be in \"dd/MM/yyyy\" format"); } try { DateTime today = new DateTime(); waitForElement(DUE_DATED_PICKER, SECONDS.convert(maxPageLoadingTime, MILLISECONDS)); driver.findElement(DUE_DATED_PICKER).click(); if (dueDate.isBeforeNow() && !dueDate.toLocalDate().toString(DateTimeFormat.forPattern("dd-MM-yyyy")) .equals(today.toLocalDate().toString(DateTimeFormat.forPattern("dd-MM-yyyy")))) { throw new UnsupportedOperationException("Due date cannot be in past"); } else { WebElement calenderElement = findAndWait(By.cssSelector("table[id$='_workflowDueDate-cntrl']")); waitForElement(By.cssSelector("a.calnav"), SECONDS.convert(maxPageLoadingTime, MILLISECONDS)); calenderElement.findElement(By.cssSelector("a.calnav")).click(); WebElement monthAndYearSelector = findAndWait(By.cssSelector("div.yui-cal-nav")); Select monthSelector = new Select( driver.findElement(By.cssSelector("select[id$='_workflowDueDate-cntrl_nav_month']"))); monthSelector.selectByValue(String.valueOf(dueDate.getMonthOfYear() - 1)); monthAndYearSelector.findElement(By.cssSelector("input[id$='_workflowDueDate-cntrl_nav_year']")) .clear(); monthAndYearSelector.findElement(By.cssSelector("input[id$='_workflowDueDate-cntrl_nav_year']")) .sendKeys(String.valueOf(dueDate.getYear())); monthAndYearSelector.findElement(By.cssSelector("button[id$='_workflowDueDate-cntrl_nav_submit']")) .click(); // Wait for the title to show the month waitUntilVisible(By.cssSelector("a.calnav"), dueDate.toString(DateTimeFormat.forPattern("MMMM yyyy")), SECONDS.convert(maxPageLoadingTime, MILLISECONDS)); calenderElement = findAndWait(By.cssSelector("table[id$='_workflowDueDate-cntrl']>tbody")); List<WebElement> allDays = calenderElement.findElements(By.cssSelector("a.selector")); for (WebElement day : allDays) { if (Integer.parseInt(day.getText()) == (due)) { day.click(); break; } } } } catch (NoSuchElementException nse) { throw new PageOperationException("Unable to find element: ", nse); } catch (TimeoutException te) { throw new PageOperationException("Timed out on waiting for: ", te); } }
From source file:org.aludratest.cloud.web.report.ResourceReportUtil.java
License:Apache License
private static JavaScriptObject createTimeEntry(DateTime time, int activeResources) { JavaScriptObject result = new JavaScriptObject(); time = time.toDateTime(DateTimeZone.UTC); // convert time to JavaScript UTC time StringBuilder sbDateTime = new StringBuilder(); sbDateTime.append("Date.UTC("); sbDateTime.append(time.getYear()).append(", "); sbDateTime.append(time.getMonthOfYear() - 1).append(", "); sbDateTime.append(time.getDayOfMonth()).append(", "); sbDateTime.append(time.getHourOfDay()).append(", "); sbDateTime.append(time.getMinuteOfHour()).append(", "); sbDateTime.append(time.getSecondOfMinute()).append(", "); sbDateTime.append(time.getMillisOfSecond()).append(")"); result.set("x", new JavaScriptCodeFragment(sbDateTime.toString())); result.set("y", new JavaScriptCodeFragment("" + activeResources)); return result; }
From source file:org.apache.beam.sdk.io.gcp.spanner.MutationGroupEncoder.java
License:Apache License
private static Date decodeDate(int daysSinceEpoch) { DateTime jodaDate = MIN_DATE.plusDays(daysSinceEpoch); return Date.fromYearMonthDay(jodaDate.getYear(), jodaDate.getMonthOfYear(), jodaDate.getDayOfMonth()); }
From source file:org.apache.beam.sdk.io.jdbc.JdbcUtil.java
License:Apache License
private static Calendar getDateOrTimeOnly(DateTime dateTime, boolean wantDateOnly) { Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone(dateTime.getZone().getID())); if (wantDateOnly) { // return date only cal.set(Calendar.YEAR, dateTime.getYear()); cal.set(Calendar.MONTH, dateTime.getMonthOfYear() - 1); cal.set(Calendar.DATE, dateTime.getDayOfMonth()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); } else { // return time only cal.set(Calendar.YEAR, 1970); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, dateTime.getHourOfDay()); cal.set(Calendar.MINUTE, dateTime.getMinuteOfHour()); cal.set(Calendar.SECOND, dateTime.getSecondOfMinute()); cal.set(Calendar.MILLISECOND, dateTime.getMillisOfSecond()); }//from w ww .java 2s. c o m return cal; }
From source file:org.apache.hive.hcatalog.pig.HCatBaseStorer.java
License:Apache License
/** * Convert from Pig value object to Hive value object * This method assumes that {@link #validateSchema(org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema, org.apache.hive.hcatalog.data.schema.HCatFieldSchema, org.apache.pig.impl.logicalLayer.schema.Schema, org.apache.hive.hcatalog.data.schema.HCatSchema, int)} * which checks the types in Pig schema are compatible with target Hive table, has been called. *///from w w w . j av a 2 s . c om private Object getJavaObj(Object pigObj, HCatFieldSchema hcatFS) throws HCatException, BackendException { try { if (pigObj == null) return null; // The real work-horse. Spend time and energy in this method if there is // need to keep HCatStorer lean and go fast. Type type = hcatFS.getType(); switch (type) { case BINARY: return ((DataByteArray) pigObj).get(); case STRUCT: HCatSchema structSubSchema = hcatFS.getStructSubSchema(); // Unwrap the tuple. List<Object> all = ((Tuple) pigObj).getAll(); ArrayList<Object> converted = new ArrayList<Object>(all.size()); for (int i = 0; i < all.size(); i++) { converted.add(getJavaObj(all.get(i), structSubSchema.get(i))); } return converted; case ARRAY: // Unwrap the bag. DataBag pigBag = (DataBag) pigObj; HCatFieldSchema tupFS = hcatFS.getArrayElementSchema().get(0); boolean needTuple = tupFS.getType() == Type.STRUCT; List<Object> bagContents = new ArrayList<Object>((int) pigBag.size()); Iterator<Tuple> bagItr = pigBag.iterator(); while (bagItr.hasNext()) { // If there is only one element in tuple contained in bag, we throw away the tuple. bagContents.add(getJavaObj(needTuple ? bagItr.next() : bagItr.next().get(0), tupFS)); } return bagContents; case MAP: Map<?, ?> pigMap = (Map<?, ?>) pigObj; Map<Object, Object> typeMap = new HashMap<Object, Object>(); for (Entry<?, ?> entry : pigMap.entrySet()) { // the value has a schema and not a FieldSchema typeMap.put( // Schema validation enforces that the Key is a String (String) entry.getKey(), getJavaObj(entry.getValue(), hcatFS.getMapValueSchema().get(0))); } return typeMap; case STRING: case INT: case BIGINT: case FLOAT: case DOUBLE: return pigObj; case SMALLINT: if ((Integer) pigObj < Short.MIN_VALUE || (Integer) pigObj > Short.MAX_VALUE) { handleOutOfRangeValue(pigObj, hcatFS); return null; } return ((Integer) pigObj).shortValue(); case TINYINT: if ((Integer) pigObj < Byte.MIN_VALUE || (Integer) pigObj > Byte.MAX_VALUE) { handleOutOfRangeValue(pigObj, hcatFS); return null; } return ((Integer) pigObj).byteValue(); case BOOLEAN: if (pigObj instanceof String) { if (((String) pigObj).trim().compareTo("0") == 0) { return Boolean.FALSE; } if (((String) pigObj).trim().compareTo("1") == 0) { return Boolean.TRUE; } throw new BackendException("Unexpected type " + type + " for value " + pigObj + " of class " + pigObj.getClass().getName(), PigHCatUtil.PIG_EXCEPTION_CODE); } return Boolean.parseBoolean(pigObj.toString()); case DECIMAL: BigDecimal bd = (BigDecimal) pigObj; DecimalTypeInfo dti = (DecimalTypeInfo) hcatFS.getTypeInfo(); if (bd.precision() > dti.precision() || bd.scale() > dti.scale()) { handleOutOfRangeValue(pigObj, hcatFS); return null; } return HiveDecimal.create(bd); case CHAR: String charVal = (String) pigObj; CharTypeInfo cti = (CharTypeInfo) hcatFS.getTypeInfo(); if (charVal.length() > cti.getLength()) { handleOutOfRangeValue(pigObj, hcatFS); return null; } return new HiveChar(charVal, cti.getLength()); case VARCHAR: String varcharVal = (String) pigObj; VarcharTypeInfo vti = (VarcharTypeInfo) hcatFS.getTypeInfo(); if (varcharVal.length() > vti.getLength()) { handleOutOfRangeValue(pigObj, hcatFS); return null; } return new HiveVarchar(varcharVal, vti.getLength()); case TIMESTAMP: DateTime dt = (DateTime) pigObj; return new Timestamp(dt.getMillis());//getMillis() returns UTC time regardless of TZ case DATE: /** * We ignore any TZ setting on Pig value since java.sql.Date doesn't have it (in any * meaningful way). So the assumption is that if Pig value has 0 time component (midnight) * we assume it reasonably 'fits' into a Hive DATE. If time part is not 0, it's considered * out of range for target type. */ DateTime dateTime = ((DateTime) pigObj); if (dateTime.getMillisOfDay() != 0) { handleOutOfRangeValue(pigObj, hcatFS, "Time component must be 0 (midnight) in local timezone; Local TZ val='" + pigObj + "'"); return null; } /*java.sql.Date is a poorly defined API. Some (all?) SerDes call toString() on it [e.g. LazySimpleSerDe, uses LazyUtils.writePrimitiveUTF8()], which automatically adjusts for local timezone. Date.valueOf() also uses local timezone (as does Date(int,int,int). Also see PigHCatUtil#extractPigObject() for corresponding read op. This way a DATETIME from Pig, when stored into Hive and read back comes back with the same value.*/ return new Date(dateTime.getYear() - 1900, dateTime.getMonthOfYear() - 1, dateTime.getDayOfMonth()); default: throw new BackendException("Unexpected HCat type " + type + " for value " + pigObj + " of class " + pigObj.getClass().getName(), PigHCatUtil.PIG_EXCEPTION_CODE); } } catch (BackendException e) { // provide the path to the field in the error message throw new BackendException((hcatFS.getName() == null ? " " : hcatFS.getName() + ".") + e.getMessage(), e); } }