Search in sources :

Example 6 with DateTime

use of org.joda.time.DateTime in project hive by apache.

the class AbstractHCatStorerTest method testWriteTimestamp.

/**
   * Note that the value that comes back from Hive will have local TZ on it. Using local is
   * arbitrary but DateTime needs TZ (or will assume default) and Hive does not have TZ. So if you
   * start with Pig value in TZ=x and write to Hive, when you read it back the TZ may be different.
   * The millis value should match, of course.
   *
   * @throws Exception
   */
@Test
public void testWriteTimestamp() throws Exception {
    // uses default TZ
    DateTime d = new DateTime(1991, 10, 11, 14, 23, 30, 10);
    pigValueRangeTest("junitTypeTest1", "timestamp", "datetime", null, d.toString(), d.toDateTime(DateTimeZone.getDefault()).toString());
    d = d.plusHours(2);
    pigValueRangeTest("junitTypeTest2", "timestamp", "datetime", HCatBaseStorer.OOR_VALUE_OPT_VALUES.Null, d.toString(), d.toDateTime(DateTimeZone.getDefault()).toString());
    d = d.toDateTime(DateTimeZone.UTC);
    pigValueRangeTest("junitTypeTest3", "timestamp", "datetime", null, d.toString(), d.toDateTime(DateTimeZone.getDefault()).toString());
    d = new DateTime(1991, 10, 11, 23, 24, 25, 26);
    pigValueRangeTest("junitTypeTest1", "timestamp", "datetime", null, d.toString(), d.toDateTime(DateTimeZone.getDefault()).toString());
    d = d.toDateTime(DateTimeZone.UTC);
    pigValueRangeTest("junitTypeTest3", "timestamp", "datetime", null, d.toString(), d.toDateTime(DateTimeZone.getDefault()).toString());
}
Also used : DateTime(org.joda.time.DateTime) Test(org.junit.Test) HCatBaseTest(org.apache.hive.hcatalog.mapreduce.HCatBaseTest)

Example 7 with DateTime

use of org.joda.time.DateTime in project hive by apache.

the class AbstractHCatStorerTest method testWriteDate3.

@Test
public void testWriteDate3() throws Exception {
    DateTime d = new DateTime(1991, 10, 11, 23, 10, DateTimeZone.forOffsetHours(-11));
    FrontendException fe = null;
    // expect to fail since the time component is not 0
    pigValueRangeTestOverflow("junitTypeTest4", "date", "datetime", HCatBaseStorer.OOR_VALUE_OPT_VALUES.Throw, d.toString(), FORMAT_4_DATE);
    pigValueRangeTestOverflow("junitTypeTest5", "date", "datetime", HCatBaseStorer.OOR_VALUE_OPT_VALUES.Null, d.plusHours(2).toString(), FORMAT_4_DATE);
    pigValueRangeTestOverflow("junitTypeTest6", "date", "datetime", HCatBaseStorer.OOR_VALUE_OPT_VALUES.Throw, d.plusMinutes(1).toString(), FORMAT_4_DATE);
}
Also used : DateTime(org.joda.time.DateTime) FrontendException(org.apache.pig.impl.logicalLayer.FrontendException) Test(org.junit.Test) HCatBaseTest(org.apache.hive.hcatalog.mapreduce.HCatBaseTest)

Example 8 with DateTime

use of org.joda.time.DateTime in project hive by apache.

the class HCatBaseStorer method getJavaObj.

/**
   * 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.
   */
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;
                //getMillis() returns UTC time regardless of TZ
                return new Timestamp(dt.getMillis());
            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);
    }
}
Also used : VarcharTypeInfo(org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HiveChar(org.apache.hadoop.hive.common.type.HiveChar) Timestamp(java.sql.Timestamp) DateTime(org.joda.time.DateTime) HCatSchema(org.apache.hive.hcatalog.data.schema.HCatSchema) DataByteArray(org.apache.pig.data.DataByteArray) DataBag(org.apache.pig.data.DataBag) CharTypeInfo(org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo) HiveVarchar(org.apache.hadoop.hive.common.type.HiveVarchar) BigDecimal(java.math.BigDecimal) Date(java.sql.Date) HCatFieldSchema(org.apache.hive.hcatalog.data.schema.HCatFieldSchema) BackendException(org.apache.pig.backend.BackendException) DecimalTypeInfo(org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo) DataType(org.apache.pig.data.DataType) Type(org.apache.hive.hcatalog.data.schema.HCatFieldSchema.Type) Map(java.util.Map) HashMap(java.util.HashMap) Tuple(org.apache.pig.data.Tuple)

Example 9 with DateTime

use of org.joda.time.DateTime in project android-betterpickers by code-troopers.

the class SampleCalendarDatePreselectedDate method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.text_and_button);
    mResultTextView = (TextView) findViewById(R.id.text);
    Button button = (Button) findViewById(R.id.button);
    mResultTextView.setText(R.string.no_value);
    button.setText(R.string.calendar_date_picker_set);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            DateTime towDaysAgo = DateTime.now().minusDays(2);
            CalendarDatePickerDialogFragment cdp = new CalendarDatePickerDialogFragment().setOnDateSetListener(SampleCalendarDatePreselectedDate.this).setPreselectedDate(towDaysAgo.getYear(), towDaysAgo.getMonthOfYear() - 1, towDaysAgo.getDayOfMonth());
            cdp.show(getSupportFragmentManager(), FRAG_TAG_DATE_PICKER);
        }
    });
}
Also used : CalendarDatePickerDialogFragment(com.codetroopers.betterpickers.calendardatepicker.CalendarDatePickerDialogFragment) Button(android.widget.Button) TextView(android.widget.TextView) View(android.view.View) DateTime(org.joda.time.DateTime)

Example 10 with DateTime

use of org.joda.time.DateTime in project kickmaterial by byoutline.

the class GlobalModule method providesGson.

@Provides
Gson providesGson() {
    GsonBuilder builder = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    JsonDeserializer<DateTime> deserializer = (json, typeOfT, context) -> new DateTime(json.getAsJsonPrimitive().getAsLong() * 1000);
    builder.registerTypeAdapter(DateTime.class, deserializer);
    return builder.create();
}
Also used : OttoObservableCachedFieldWithArgBuilder(com.byoutline.ottocachedfield.OttoObservableCachedFieldWithArgBuilder) Bus(com.squareup.otto.Bus) CachedField(com.byoutline.cachedfield.CachedField) GsonBuilder(com.google.gson.GsonBuilder) KickMaterialService(com.byoutline.kickmaterial.api.KickMaterialService) KickMaterialRequestInterceptor(com.byoutline.kickmaterial.api.KickMaterialRequestInterceptor) Picasso(com.squareup.picasso.Picasso) FieldNamingPolicy(com.google.gson.FieldNamingPolicy) Module(dagger.Module) ObservableCachedFieldWithArg(com.byoutline.observablecachedfield.ObservableCachedFieldWithArg) Gson(com.google.gson.Gson) RetrofitHelper.apiValueProv(com.byoutline.ibuscachedfield.util.RetrofitHelper.apiValueProv) GsonConverterFactory(retrofit2.converter.gson.GsonConverterFactory) OttoCachedFieldBuilder(com.byoutline.ottocachedfield.OttoCachedFieldBuilder) KickMaterialApp(com.byoutline.kickmaterial.KickMaterialApp) LruCacheWithPlaceholders(com.byoutline.kickmaterial.utils.LruCacheWithPlaceholders) Nullable(javax.annotation.Nullable) Provides(dagger.Provides) CachedFieldWithArg(com.byoutline.cachedfield.CachedFieldWithArg) com.byoutline.kickmaterial.events(com.byoutline.kickmaterial.events) AccessTokenProvider(com.byoutline.kickmaterial.managers.AccessTokenProvider) DateTime(org.joda.time.DateTime) LoginManager(com.byoutline.kickmaterial.managers.LoginManager) Retrofit(retrofit2.Retrofit) List(java.util.List) OkHttpClient(okhttp3.OkHttpClient) SharedPreferences(android.content.SharedPreferences) JsonDeserializer(com.google.gson.JsonDeserializer) com.byoutline.kickmaterial.model(com.byoutline.kickmaterial.model) OttoCachedFieldWithArgBuilder(com.byoutline.ottocachedfield.OttoCachedFieldWithArgBuilder) GsonBuilder(com.google.gson.GsonBuilder) DateTime(org.joda.time.DateTime) Provides(dagger.Provides)

Aggregations

DateTime (org.joda.time.DateTime)3381 Test (org.junit.Test)1000 Test (org.testng.annotations.Test)499 DateTimeRfc1123 (com.microsoft.rest.DateTimeRfc1123)349 ResponseBody (okhttp3.ResponseBody)332 ArrayList (java.util.ArrayList)299 LocalDate (org.joda.time.LocalDate)256 Date (java.util.Date)239 Interval (org.joda.time.Interval)200 Result (io.druid.query.Result)153 ServiceCall (com.microsoft.rest.ServiceCall)148 HashMap (java.util.HashMap)144 BigDecimal (java.math.BigDecimal)132 List (java.util.List)131 DateTimeZone (org.joda.time.DateTimeZone)127 LocalDateTime (org.joda.time.LocalDateTime)98 UUID (java.util.UUID)93 DateTimeFormatter (org.joda.time.format.DateTimeFormatter)88 IOException (java.io.IOException)85 Map (java.util.Map)85