Example usage for org.joda.time LocalDateTime now

List of usage examples for org.joda.time LocalDateTime now

Introduction

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

Prototype

public static LocalDateTime now() 

Source Link

Document

Obtains a LocalDateTime set to the current system millisecond time using ISOChronology in the default time zone.

Usage

From source file:act.apidoc.Endpoint.java

License:Apache License

private Object generateSampleData(BeanSpec spec, Set<Type> typeChain, List<String> nameChain) {
    Type type = spec.type();/*from   ww  w .j  av a2 s.co m*/
    if (typeChain.contains(type) && !isCollection(type)) {
        return S.concat(spec.name(), ":", type); // circular reference detected
    }
    typeChain.add(type);
    String name = spec.name();
    if (S.notBlank(name)) {
        nameChain.add(name);
    }
    if (null != fastJsonPropertyPreFilter) {
        String path = S.join(nameChain).by(".").get();
        if (!fastJsonPropertyPreFilter.matches(path)) {
            return null;
        }
    }
    Class<?> classType = spec.rawType();
    try {
        if (void.class == classType || Void.class == classType || Result.class.isAssignableFrom(classType)) {
            return null;
        }
        if (Object.class == classType) {
            return "<Any>";
        }
        try {
            if (classType.isEnum()) {
                Object[] ea = classType.getEnumConstants();
                int len = ea.length;
                return 0 < len ? ea[N.randInt(len)] : null;
            } else if (Locale.class == classType) {
                return (defLocale);
            } else if (String.class == classType) {
                String mockValue = S.random(5);
                if (spec.hasAnnotation(Sensitive.class)) {
                    return Act.crypto().encrypt(mockValue);
                }
                return S.random(5);
            } else if (classType.isArray()) {
                Object sample = Array.newInstance(classType.getComponentType(), 2);
                Array.set(sample, 0,
                        generateSampleData(BeanSpec.of(classType.getComponentType(), Act.injector()),
                                C.newSet(typeChain), C.newList(nameChain)));
                Array.set(sample, 1,
                        generateSampleData(BeanSpec.of(classType.getComponentType(), Act.injector()),
                                C.newSet(typeChain), C.newList(nameChain)));
                return sample;
            } else if ($.isSimpleType(classType)) {
                if (Enum.class == classType) {
                    return "<Any Enum>";
                }
                if (!classType.isPrimitive()) {
                    classType = $.primitiveTypeOf(classType);
                }
                return StringValueResolver.predefined().get(classType).resolve(null);
            } else if (LocalDateTime.class.isAssignableFrom(classType)) {
                return LocalDateTime.now();
            } else if (DateTime.class.isAssignableFrom(classType)) {
                return DateTime.now();
            } else if (LocalDate.class.isAssignableFrom(classType)) {
                return LocalDate.now();
            } else if (LocalTime.class.isAssignableFrom(classType)) {
                return LocalTime.now();
            } else if (Date.class.isAssignableFrom(classType)) {
                return new Date();
            } else if (classType.getName().contains(".ObjectId")) {
                return "<id>";
            } else if (BigDecimal.class == classType) {
                return BigDecimal.valueOf(1.1);
            } else if (BigInteger.class == classType) {
                return BigInteger.valueOf(1);
            } else if (ISObject.class.isAssignableFrom(classType)) {
                return null;
            } else if (Map.class.isAssignableFrom(classType)) {
                Map map = $.cast(Act.getInstance(classType));
                List<Type> typeParams = spec.typeParams();
                if (typeParams.isEmpty()) {
                    typeParams = Generics.typeParamImplementations(classType, Map.class);
                }
                if (typeParams.size() < 2) {
                    map.put(S.random(), S.random());
                    map.put(S.random(), S.random());
                } else {
                    Type keyType = typeParams.get(0);
                    Type valType = typeParams.get(1);
                    map.put(generateSampleData(BeanSpec.of(keyType, null, Act.injector()), C.newSet(typeChain),
                            C.newList(nameChain)),
                            generateSampleData(BeanSpec.of(valType, null, Act.injector()), C.newSet(typeChain),
                                    C.newList(nameChain)));
                    map.put(generateSampleData(BeanSpec.of(keyType, null, Act.injector()), C.newSet(typeChain),
                            C.newList(nameChain)),
                            generateSampleData(BeanSpec.of(valType, null, Act.injector()), C.newSet(typeChain),
                                    C.newList(nameChain)));
                }
            } else if (Iterable.class.isAssignableFrom(classType)) {
                Collection col = $.cast(Act.getInstance(classType));
                List<Type> typeParams = spec.typeParams();
                if (typeParams.isEmpty()) {
                    typeParams = Generics.typeParamImplementations(classType, Map.class);
                }
                if (typeParams.isEmpty()) {
                    col.add(S.random());
                } else {
                    Type componentType = typeParams.get(0);
                    col.add(generateSampleData(BeanSpec.of(componentType, null, Act.injector()),
                            C.newSet(typeChain), C.newList(nameChain)));
                    col.add(generateSampleData(BeanSpec.of(componentType, null, Act.injector()),
                            C.newSet(typeChain), C.newList(nameChain)));
                }
                return col;
            }

            if (null != stringValueResolver(classType)) {
                return S.random(5);
            }

            Object obj = Act.getInstance(classType);
            List<Field> fields = $.fieldsOf(classType);
            for (Field field : fields) {
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }
                if (ParamValueLoaderService.shouldWaive(field)) {
                    continue;
                }
                Class<?> fieldType = field.getType();
                Object val = null;
                try {
                    field.setAccessible(true);
                    val = generateSampleData(BeanSpec.of(field, Act.injector()), C.newSet(typeChain),
                            C.newList(nameChain));
                    Class<?> valType = null == val ? null : val.getClass();
                    if (null != valType && fieldType.isAssignableFrom(valType)) {
                        field.set(obj, val);
                    }
                } catch (Exception e) {
                    LOGGER.warn("Error setting value[%s] to field[%s.%s]", val, classType.getSimpleName(),
                            field.getName());
                }
            }
            return obj;
        } catch (Exception e) {
            LOGGER.warn("error generating sample data for type: %s", classType);
            return null;
        }
    } finally {
        //typeChain.remove(classType);
    }
}

From source file:at.wada811.dayscounter.view.activity.SettingsActivity.java

License:Apache License

@Override
protected void onCreate(Bundle savedInstanceState) {
    // catch UncaughtException
    Thread.setDefaultUncaughtExceptionHandler(new CrashExceptionHandler(getApplicationContext()));
    super.onCreate(savedInstanceState);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    setContentView(R.layout.activity_settings);
    ButterKnife.inject(this);
    // Window size dialog
    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.width = WindowManager.LayoutParams.MATCH_PARENT;
    params.height = WindowManager.LayoutParams.MATCH_PARENT;
    getWindow().setAttributes(params);/*from  w  w  w . j  a  v  a2  s .  c  o m*/
    LogUtils.d();
    // check Crash report
    File file = ResourceUtils.getFile(this, CrashExceptionHandler.FILE_NAME);
    if (file.exists()) {
        startActivity(new Intent(this, CrashReportActivity.class));
        finish();
        return;
    }
    // AppWidgetId
    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null) {
        appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
    }
    LogUtils.d("appWidgetId: " + appWidgetId);

    WidgetModel model = new WidgetModel(this, appWidgetId);
    viewModel = new Widget1x1ViewModel(this, model);
    // Title
    new EditTextBinding(titleEditText).bind(new Func<EditText, String>() {
        @Override
        public String apply(EditText editText) {
            return editText.getText().toString();
        }
    }, viewModel.getTitle(), new EditTextTextChanged() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            titleTextView.setText(viewModel.getTitle().getValue());
        }
    });
    titleEditText.setText(viewModel.getTitle().getValue());
    // Date
    String date = viewModel.getDate().getValue();
    LogUtils.d("date: " + date);
    LocalDateTime dateTime = date != null ? new LocalDateTime(date) : LocalDateTime.now();
    DatePickerBinding datePickerBinding = new DatePickerBinding(datePicker);
    datePickerBinding.bind(new Func<DatePicker, String>() {
        @Override
        public String apply(DatePicker datePicker) {
            return DatePickerUtils.format(datePicker);
        }
    }, viewModel.getDate(), new OnDateChangedListener() {
        @Override
        public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            diffTextView.setText(viewModel.getDiff().getValue());
            diffTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, viewModel.getDiffTextSize().getValue());
            daysTextView.setText(viewModel.getComparison().getValue());
        }
    });
    datePicker.init(dateTime.getYear(), dateTime.getMonthOfYear() - 1, dateTime.getDayOfMonth(),
            datePickerBinding.getOnDateChangedListener());
    diffTextView.setText(viewModel.getDiff().getValue());
    diffTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, viewModel.getDiffTextSize().getValue());
    daysTextView.setText(viewModel.getComparison().getValue());

    // Button
    submitButton.setOnClickListener(this);
}

From source file:ch.eitchnet.android.mabea.activity.TodayFragment.java

License:Open Source License

/**
 * @param expectedState/* w  w  w  .j  a  va  2 s .c  o  m*/
 * @param currentState
 * @return
 */
private boolean handleCurrentState(State expectedState, MabeaState currentState) {

    // if the state is as expected, then all is good
    if (expectedState.equals(currentState.getState())) {
        return true;
    }

    // we have a mismatch. We can recover from it, if the time stamp is 
    // later than what we have currently registered

    // so check if the server state is later than the current booking
    Today today = MabeaApplication.getContext().getToday();
    Booking latestBooking = today.getLatestBooking();
    LocalDateTime expectedDate = latestBooking.getTimestamp();
    LocalDateTime currentDate = currentState.getStateTime();
    if (expectedDate.isAfter(currentDate) && currentDate.isBefore(LocalDateTime.now())) {

        String title = "State mismatch";
        String msg = "The state on the server is {0} which is not the expected state {1}.\n\nThe local state can't be toggled as the local timestamp {2} is after the new state from the server. Please check your expected state.";
        msg = MessageFormat.format(msg, currentState.getState(), expectedState,
                JodaHelper.toDateHourMinute(expectedDate), JodaHelper.toDateHourMinute(currentDate));
        DialogUtil.showErrorDialog(getActivity(), title, msg);
        return false;
    }

    // fix state mismatch by adding a new booking
    Booking booking = new Booking(currentState.getState(), currentDate, currentState.getBalance());
    today.addBooking(booking);

    // notify user of fix
    String title = "State mismatch";
    String msg = "The state on the server is {0} which is not the expected state {1}.\n\nAs the time stamp of the current state is later than the latest booking, a new booking was added to today. Please check your expected state.";
    msg = MessageFormat.format(msg, currentState.getState(), expectedState,
            JodaHelper.toDateHourMinute(expectedDate), JodaHelper.toDateHourMinute(currentDate));
    DialogUtil.showErrorDialog(getActivity(), title, msg);

    return true;
}

From source file:ch.eitchnet.android.mabea.model.MabeaState.java

License:Open Source License

/**
 * Default constructor/* ww w.  j  av a 2s  .c om*/
 */
public MabeaState() {
    this.timeQueried = LocalDateTime.now();
    this.name = "";
    this.state = State.UNKNOWN;
}

From source file:ch.eitchnet.android.mabea.model.MabeaState.java

License:Open Source License

/**
 * Constructor to set all fields//from  w ww  .ja  v a2 s .co m
 * 
 * @param name
 * @param balance
 * @param remainingVacation
 * @param stateTime
 * @param state
 */
public MabeaState(String name, Duration balance, Duration remainingVacation, LocalDateTime stateTime,
        State state) {
    this.timeQueried = LocalDateTime.now();
    this.name = name;
    this.balance = balance;
    this.remainingVacation = remainingVacation;
    this.stateTime = stateTime;
    this.state = state;
}

From source file:ch.eitchnet.android.mabea.model.MabeaState.java

License:Open Source License

public Duration getAge() {
    return new Period(this.timeQueried, LocalDateTime.now()).toStandardDuration();
}

From source file:ch.eitchnet.android.mabea.model.Today.java

License:Open Source License

public void addBooking(Booking booking) {

    // only logged in our logged out bookings
    State newState = booking.getState();
    if (newState == State.UNKNOWN)
        throw new IllegalArgumentException("The booking may not have the state " + State.UNKNOWN);

    // must toggle current state
    Booking lastBooking = this.bookings.get(this.bookings.size() - 1);
    if (lastBooking.getState() == newState)
        throw new IllegalArgumentException("The latest booking already has state " + newState);

    // and be later than previous state
    if (booking.getTimestamp().isBefore(lastBooking.getTimestamp()))
        throw new IllegalArgumentException("New booking time stamp " + booking.getTimestamp()
                + " is not later than current time stamp " + lastBooking.getTimestamp());

    // and it should be earlier than now
    if (LocalDateTime.now().isBefore(booking.getTimestamp()))
        throw new IllegalArgumentException("The new booking has a time stamp later than now!");

    // then we can update the model
    this.bookings.add(booking);
    updateWorkToday();/*  www.  j  a v  a 2s .  c  o  m*/
}

From source file:ch.eitchnet.android.mabea.model.Today.java

License:Open Source License

public Duration getWorkToday() {
    Booking latestBooking = getLatestBooking();
    if (latestBooking.getState() == State.LOGGED_OUT)
        return workToday;

    Period period = new Period(latestBooking.getTimestamp(), LocalDateTime.now());
    return workToday.plus(period.toStandardDuration());
}

From source file:ch.icclab.cyclops.util.DateTimeUtil.java

License:Open Source License

/**
 * Generates the 1 hr time range (from and to) by computing the present server time
 *
 * @return dateTime A string consisting of from and to dateTime entries
 */// www . jav a 2  s  .c  om
public String[] getRange() {
    String from, to;
    String sMonth = null;
    String sDay = null;
    String stHour = null;
    String sHour = null;
    String sMin = null;
    String sSec = null;
    int year, month, day, hour, min, sec, tHour;
    String[] dateTime = new String[2];

    LocalDateTime currentDate = LocalDateTime.now();
    year = currentDate.getYear();
    month = currentDate.getMonthOfYear();
    if (month <= 9) {
        sMonth = "0" + month;
    } else {
        sMonth = month + "";
    }
    day = currentDate.getDayOfMonth();
    if (day <= 9) {
        sDay = "0" + day;
    } else {
        sDay = day + "";
    }
    hour = currentDate.getHourOfDay();
    if (hour <= 9) {
        sHour = "0" + hour;
    } else {
        sHour = hour + "";
    }
    min = currentDate.getMinuteOfHour();
    if (min <= 9) {
        sMin = "0" + min;
    } else {
        sMin = min + "";
    }
    sec = currentDate.getSecondOfMinute();
    if (sec <= 9) {
        sSec = "0" + sec;
    } else {
        sSec = sec + "";
    }

    to = year + "-" + sMonth + "-" + sDay + "T" + sHour + ":" + sMin + ":" + sSec + "Z";
    Date dateTo = getDate(to);
    //Converting to in UTC
    to = getString(dateTo);
    long sensuFrequency = Loader.getSettings().getSchedulerSettings().getSchedulerFrequency();

    long fromTimestamp = dateTo.getTime() - sensuFrequency * 1000;
    Date fromDate = new Date(fromTimestamp);

    from = getString(fromDate);

    dateTime[0] = to;
    dateTime[1] = from;

    return dateTime;
}

From source file:cherry.common.foundation.impl.BizDateTimeImpl.java

License:Apache License

@Transactional
@Override/*  ww  w  .jav a  2s.  c o  m*/
public LocalDateTime now() {
    DateTimeExpression<LocalDateTime> curDtm = currentTimestamp(LocalDateTime.class);
    SQLQuery query = createSqlQuery(bm);
    Tuple tuple = query.uniqueResult(curDtm, bm.offsetDay, bm.offsetHour, bm.offsetMinute, bm.offsetSecond);
    if (tuple == null) {
        return LocalDateTime.now();
    }
    return tuple.get(curDtm).plusDays(tuple.get(bm.offsetDay)).plusHours(tuple.get(bm.offsetHour))
            .plusMinutes(tuple.get(bm.offsetMinute)).plusSeconds(tuple.get(bm.offsetSecond));
}