List of usage examples for org.joda.time DateTime getYear
public int getYear()
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 ww w . j a v a 2s . co m*/ return cal; }
From source file:org.apache.flume.ext.source.SyslogParser.java
License:Apache License
/** * Parse the RFC3164 date format. This is trickier than it sounds because this * format does not specify a year so we get weird edge cases at year * boundaries. This implementation tries to "do what I mean". * @param ts RFC3164-compatible timestamp to be parsed * @return Typical (for Java) milliseconds since the UNIX epoch *//*from ww w. ja v a2 s . c om*/ protected long parseRfc3164Time(String ts) { DateTime now = DateTime.now(); int year = now.getYear(); ts = TWO_SPACES.matcher(ts).replaceFirst(" "); DateTime date; try { date = rfc3164Format.parseDateTime(ts); } catch (IllegalArgumentException e) { logger.debug("rfc3164 date parse failed on (" + ts + "): invalid format", e); return 0; } // try to deal with boundary cases, i.e. new year's eve. // rfc3164 dates are really dumb. // NB: cannot handle replaying of old logs or going back to the future if (date != null) { DateTime fixed = date.withYear(year); // flume clock is ahead or there is some latency, and the year rolled if (fixed.isAfter(now) && fixed.minusMonths(1).isAfter(now)) { fixed = date.withYear(year - 1); // flume clock is behind and the year rolled } else if (fixed.isBefore(now) && fixed.plusMonths(1).isBefore(now)) { fixed = date.withYear(year + 1); } date = fixed; } if (date == null) { return 0; } return date.getMillis(); }
From source file:org.apache.flume.serialization.SyslogAvroEventSerializer.java
License:Apache License
/** * Returns epoch time in millis, or 0 if the string cannot be parsed. * We use two date formats because the date spec in rfc3164 is kind of weird. * <br/>/*from w w w . j av a 2s . c o m*/ * <b>Warning:</b> logic is used here to determine the year even though it's * not part of the timestamp format, and we assume that the machine running * Flume has a clock that is at least close to the same day as the machine * that generated the event. We also assume that the event was generated * recently. */ private static long parseRfc3164Date(String in) { DateTime date = null; try { date = dateFmt1.parseDateTime(in); } catch (IllegalArgumentException e) { // ignore the exception, we act based on nullity of date object logger.debug("Date parse failed on ({}), trying single-digit date", in); } if (date == null) { try { date = dateFmt2.parseDateTime(in); } catch (IllegalArgumentException e) { // ignore the exception, we act based on nullity of date object logger.debug("2nd date parse failed on ({}), unknown date format", in); } } // hacky stuff to try and deal with boundary cases, i.e. new year's eve. // rfc3164 dates are really dumb. // NB: cannot handle replaying of old logs or going back to the future if (date != null) { DateTime now = new DateTime(); int year = now.getYear(); DateTime corrected = date.withYear(year); // flume clock is ahead or there is some latency, and the year rolled if (corrected.isAfter(now) && corrected.minusMonths(1).isAfter(now)) { corrected = date.withYear(year - 1); // flume clock is behind and the year rolled } else if (corrected.isBefore(now) && corrected.plusMonths(1).isBefore(now)) { corrected = date.withYear(year + 1); } date = corrected; } if (date == null) { return 0; } return date.getMillis(); }
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. */// www.j av a 2 s . c o m 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); } }
From source file:org.apache.phoenix.expression.function.YearFunction.java
License:Apache License
@Override public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { Expression expression = getChildExpression(); if (!expression.evaluate(tuple, ptr)) { return false; }/*from w ww . j a va 2 s . c o m*/ if (ptr.getLength() == 0) { return true; //means null } long dateTime = inputCodec.decodeLong(ptr, expression.getSortOrder()); DateTime dt = new DateTime(dateTime); int year = dt.getYear(); PDataType returnType = getDataType(); byte[] byteValue = new byte[returnType.getByteSize()]; returnType.getCodec().encodeInt(year, byteValue, 0); ptr.set(byteValue); return true; }
From source file:org.apache.streams.util.DateUtil.java
License:Apache License
public static DateTime determineDateTime(String dateString, DateTimeZone theTimeZone) throws ParseException { DateTime beforeTimeZone = determineDateTime(dateString); return new DateTime(beforeTimeZone.getYear(), beforeTimeZone.getMonthOfYear(), beforeTimeZone.getDayOfMonth(), beforeTimeZone.getHourOfDay(), beforeTimeZone.getMinuteOfHour(), beforeTimeZone.getSecondOfMinute(), beforeTimeZone.getMillisOfSecond(), theTimeZone); }
From source file:org.apache.streams.util.DateUtil.java
License:Apache License
public static Set<String> getAliasesForDateRange(DateTime startDate, DateTime endDate, String prefix) { Set<String> aliases = new HashSet<String>(); aliases.add(prefix + "_" + getDateAbbreviation(startDate.getYear(), startDate.getMonthOfYear())); if (endDate == null) { return aliases; }/*from ww w. j av a 2 s . c o m*/ while (endDate.isAfter(startDate)) { aliases.add(prefix + "_" + getDateAbbreviation(endDate.getYear(), endDate.getMonthOfYear())); endDate = endDate.minusMonths(1); } return aliases; }
From source file:org.apache.tajo.util.datetime.DateTimeUtil.java
License:Apache License
public static long getMonth(DateTime dateTime) { return convertToMicroSeconds( dateTime.withTimeAtStartOfDay().withDate(dateTime.getYear(), dateTime.getMonthOfYear(), 1)); }