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:com.einzig.ipst2.util.AsyncLogger.java

License:Open Source License

/**
 * Asynchronously calls android.util.Log as well as writes log to file
 *
 * @param level   Severity of the log/*from  ww w.jav  a 2  s  . com*/
 * @param scope   Scope the message was written from
 * @param message Message to be logged
 * @param callback Callback method that can be called to asynchronously log to console
 */
private void logAsync(String level, String scope, String message, LogCallback callback) {
    consoleQueue.add(callback);
    fileQueue.add(new LogEntry(level, LocalDateTime.now(), scope, message));
}

From source file:com.einzig.ipst2.util.CSVExportHelper.java

License:Open Source License

protected String doInBackground(String... urls) {
    DateTimeFormatter uiFormatter = helper.getUIFormatter();
    DateTimeFormatter fileFormatter = ISODateTimeFormat.basicDate();
    String date = fileFormatter.print(LocalDateTime.now());
    String fileName = "/IPST2-backup-" + exportType + "-" + date + ".csv";
    File root = Environment.getExternalStorageDirectory();
    File dir = new File(root.getAbsolutePath() + "/Download");
    File file = new File(dir, fileName);
    if (Environment.getExternalStorageDirectory() == null) {
        errorHappened = true;//from  w  ww. j  av a  2  s  . c o  m
        errorThatHappened = "No SD Card Found";
    } else {
        try {
            Logger.d(file.getAbsolutePath());
            CSVWriter mWriter = new CSVWriter(new FileWriter(file));
            Vector<? extends PortalSubmission> subList = db.getAllPortals(helper.isSeerOnly());
            SortHelper.sortList(subList, activity);

            String[] mExportChartHeaders = { "Portal Name", "Date Submitted", "Date Accepted", "Date Rejected",
                    "Status", "Live Address", "Intel Link URL", "Picture URL", "Rejection Reason", "Lat/Lon",
                    "Date Pattern" };

            mWriter.writeNext(mExportChartHeaders);

            for (PortalSubmission submission : subList) {
                Logger.d("PORTAL SUBMISSION ADDED TO CSV: " + submission.getName());
                String name = submission.getName();
                String dateSubmitted = "N/A";
                if (submission.getDateSubmitted() != null)
                    dateSubmitted = uiFormatter.print(submission.getDateSubmitted());

                String dateAccepted = "N/A";
                String dateRejected = "N/A";
                if (submission instanceof PortalAccepted || submission instanceof PortalRejected) {
                    if (((PortalResponded) submission).getDateResponded() != null) {
                        if (submission instanceof PortalAccepted)
                            dateAccepted = uiFormatter.print(((PortalResponded) submission).getDateResponded());
                        else
                            dateRejected = uiFormatter.print(((PortalResponded) submission).getDateResponded());
                    }
                }

                String status = "Pending";
                if (submission instanceof PortalAccepted)
                    status = "Accepted";
                else if (submission instanceof PortalRejected)
                    status = "Rejected";

                String liveAddress = "N/A";
                String intelLink = "N/A";
                String pictureURL = "N/A";
                String rejectionReason = "N/A";
                String latLonString = "N/A";

                if (submission.getPictureURL() != null)
                    pictureURL = submission.getPictureURL();

                if (submission instanceof PortalResponded) {
                    if (submission instanceof PortalAccepted) {
                        liveAddress = ((PortalAccepted) submission).getLiveAddress();
                        intelLink = ((PortalAccepted) submission).getIntelLinkURL();
                        try {
                            latLonString = intelLink.substring(intelLink.indexOf("=") + 1,
                                    intelLink.indexOf("&"));
                        } catch (java.lang.StringIndexOutOfBoundsException e) {
                            latLonString = "String Index was Out of Bounds";
                        }
                    } else if (submission instanceof PortalRejected) {
                        rejectionReason = ((PortalRejected) submission).getRejectionReason();
                    }
                }

                if (name != null)
                    name = name.replaceAll(",", "");

                status = status.replaceAll(",", "");

                if (liveAddress != null) {
                    liveAddress = liveAddress.replaceAll(",", "");
                }

                if (intelLink != null)
                    intelLink = intelLink.replaceAll(",", ",");

                if (rejectionReason != null)
                    rejectionReason = rejectionReason.replaceAll(",", "");

                String[] lineOfCSV = { name, dateSubmitted, dateAccepted, dateRejected, status, liveAddress,
                        intelLink, pictureURL, rejectionReason, latLonString, helper.getUIFormatterPattern() };

                if (exportType.equalsIgnoreCase("all"))
                    mWriter.writeNext(lineOfCSV);
                else if (exportType.equalsIgnoreCase("accepted"))
                    if (status.equalsIgnoreCase("Accepted"))
                        mWriter.writeNext(lineOfCSV);
            }
            mWriter.close();

            pathTofile = file.getAbsolutePath();

            //Intent sendIntent = new Intent(Intent.ACTION_SEND);
            //sendIntent.setType("application/csv");
            //sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
            //startActivity(sendIntent);
        } catch (Exception e) {
            e.printStackTrace();
            errorThatHappened = e.toString();
            errorHappened = true;
        }
        db.close();
    }

    return "";
}

From source file:com.ephemeraldreams.gallyshuttle.ui.MainFragment.java

License:Apache License

private void setScheduleId() {
    LocalDateTime now = LocalDateTime.now();
    int hour = now.getHourOfDay();
    int minute = now.getMinuteOfHour();
    if (hour >= 21 || (hour == 0 && minute <= 15)) {
        scheduleId = R.array.late_night_stations;
    } else {/*from w ww. ja  v a  2  s  . c  o m*/
        int day = now.getDayOfWeek();
        switch (day) {
        case SATURDAY:
        case SUNDAY:
            scheduleId = R.array.weekend_stations;
            break;
        default:
            scheduleId = R.array.continuous_stations;
            break;
        }
    }
}

From source file:com.ephemeraldreams.gallyshuttle.ui.MainFragment.java

License:Apache License

/**
 * Calculate time difference in milliseconds between now and next available shuttle arrival time.
 *
 * @param stationId Station id to get times from.
 * @return Duration between now and next arrival time in milliseconds.
 *///w w  w  . ja  v a 2s. c om
private long calculateTimeFromNowToNextArrivalAtStation(int stationId) {
    List<String> times = schedule.getTimes(stationId);
    LocalDateTime now = LocalDateTime.now();
    arrivalTime = null;
    LocalDateTime stationTime;
    for (String time : times) {
        stationTime = DateUtils.parseToLocalDateTime(time);
        Timber.d(stationTime.toString());

        //Workaround midnight exception case where station time was converted to midnight of current day instead of next day.
        if (stationTime.getHourOfDay() == 0 && now.getHourOfDay() != 0) {
            stationTime = stationTime.plusDays(1);
        }
        if (now.isBefore(stationTime)) {
            arrivalTime = stationTime;
            break;
        }
    }
    if (arrivalTime == null) {
        arrivalTimeTextView.setText(getString(R.string.arrival_not_available_message));
        return -1;
    } else {
        arrivalTimeTextView.setText(String.format(getString(R.string.until_arrival_time_message),
                DateUtils.formatTime(arrivalTime)));

        Duration duration = new Duration(now.toDateTime(), arrivalTime.toDateTime());
        long milliseconds = duration.getMillis();

        Timber.d("Now: " + DateUtils.formatTime(now));
        Timber.d("Arrival: " + DateUtils.formatTime(arrivalTime));
        Timber.d("Time difference between now and arrival: "
                + DateUtils.convertMillisecondsToTime(milliseconds));

        return milliseconds;
    }
}

From source file:com.ephemeraldreams.gallyshuttle.ui.MainFragment.java

License:Apache License

/**
 * Set a timer for arrival notification.
 *
 * @param notificationsBoxChecked Notification check box's checked status.
 *//*from  ww w  .ja  v  a2  s .  c  o  m*/
private void setArrivalNotificationTimer(boolean notificationsBoxChecked) {
    if (notificationsBoxChecked) {
        if (arrivalTime != null) {
            Intent notificationIntent = new Intent(getActivity(), ArrivalNotificationReceiver.class);
            notificationIntent.putExtra(ArrivalNotificationReceiver.EXTRA_STATION_NAME,
                    stationStopsAdapter.getItem(stationIndex));
            notificationPendingIntent = PendingIntent.getBroadcast(getActivity(), 0, notificationIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

            Duration duration = new Duration(LocalDateTime.now().toDateTime(), arrivalTime.toDateTime());
            long millis = duration.getMillis();
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millis,
                    notificationPendingIntent);
            Timber.d("Arrival Notification receiver set: " + DateUtils.convertMillisecondsToTime(millis));
        } else {
            Timber.d("Arrival Notification receiver not set. Arrival time is null.");
        }
    } else {
        alarmManager.cancel(notificationPendingIntent);
        Timber.d("Arrival Notification receiver cancelled.");
    }
}

From source file:com.ephemeraldreams.gallyshuttle.ui.receivers.ArrivalNotificationReceiver.java

License:Apache License

private void displayReminderNotification(Context context, Intent intent) {

    CharSequence stationName = intent.getCharSequenceExtra(EXTRA_STATION_NAME);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_directions_bus_white_48dp)
            .setContentTitle(context.getString(R.string.notification_title))
            .setContentText(//from  w  ww . j  a  v  a  2s.  c o  m
                    String.format(context.getString(R.string.notification_content), stationName.toString()))
            .setAutoCancel(true);
    if (vibrationEnabledBooleanPreference.get()) {
        builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
    }
    String ringtone = ringtoneChoiceStringPreference.get();
    if (!TextUtils.isEmpty(ringtone)) {
        Uri ringtoneUri = Uri.parse(ringtone);
        builder.setSound(ringtoneUri);
    }
    notificationManager.notify(0, builder.build());
    Timber.d("Notification sent: " + LocalDateTime.now().toLocalTime().toString());
}

From source file:com.fns.grivet.api.GrivetApiClientIT.java

License:Apache License

@Test
@Disabled("Cannot test w/ H2")
public void testNamedQueryRegistrationAndRetrievalSprocHappyPath() {
    registerTestType();//from  w  ww.ja v a  2 s.c om
    Resource r = resolver.getResource("classpath:TestSprocQuery.json");
    try {
        String sproc = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
        given().contentType("application/json").request().body(sproc).then().expect().statusCode(equalTo(204))
                .when().post("/api/v1/query");
        LocalDateTime now = LocalDateTime.now();
        Response response = given().contentType("application/json").request().then().expect()
                .statusCode(equalTo(200)).when()
                .get("/api/v1/query/sproc.getAttributesCreatedBefore?createdTime=" + now.toString());
        JSONArray result = new JSONArray(response.body().asString());
        Assertions.assertEquals(7, result.length());
        given().contentType("application/json").request().then().expect().statusCode(equalTo(204)).when()
                .delete("/api/v1/query/sproc.getAttributesCreatedBefore");
    } catch (IOException e) {
        fail(e.getMessage());
    }
    deregisterType();
}

From source file:com.hp.autonomy.hod.client.job.PollingJobStatusRunnable.java

License:MIT License

/**
 * Creates a new PollingJobStatusRunnable using the given token proxy
 * @param tokenProxy The token proxy used to submit the job
 * @param jobId The ID of the job//from w  w  w . j  av a 2 s.  c  o  m
 * @param callback The callback that will be called with the result
 * @param executorService The executor service responsible for running the runnable
 */
public PollingJobStatusRunnable(final TokenProxy<?, TokenType.Simple> tokenProxy, final Duration timeout,
        final JobId jobId, final HodJobCallback<T> callback, final ScheduledExecutorService executorService,
        final JobService<? extends JobStatus<T>> jobService) {
    this.tokenProxy = tokenProxy;
    this.jobId = jobId;
    this.callback = callback;
    this.executorService = executorService;
    this.jobService = jobService;
    this.timeout = timeout != null ? LocalDateTime.now().plus(timeout) : null;
}

From source file:com.hp.autonomy.hod.client.job.PollingJobStatusRunnable.java

License:MIT License

/**
 * Checks the status of the job. If the job has not finished, the runnable will schedule itself to run again after a
 * short wait/*w  ww  .j a v a2  s.c o  m*/
 */
@Override
public void run() {
    try {
        log.debug("About to check status for jobId {}", jobId);

        final JobStatus<T> jobStatus;

        if (tokenProxy != null) {
            jobStatus = jobService.getJobStatus(tokenProxy, jobId);
        } else {
            jobStatus = jobService.getJobStatus(jobId);
        }

        final Status jobStatusStatus = jobStatus.getStatus();

        if (jobStatusStatus == Status.FINISHED || jobStatusStatus == Status.FAILED) {
            for (final Action<T> action : jobStatus.getActions()) {
                final Status status = action.getStatus();

                if (status == Status.FINISHED) {
                    log.debug("Found a finished action, calling callback");

                    callback.success(action.getResult());
                } else if (status == Status.FAILED) {
                    log.debug("Found a failed action, calling callback");

                    for (final HodError error : action.getErrors()) {
                        log.debug("Error callback called with: {}", error);

                        callback.error(error.getErrorCode());
                    }
                }
            }
        } else if (timeout != null && timeout.isBefore(LocalDateTime.now())) {
            callback.timeout();
            log.debug("Timeout callback called");
        } else {
            log.debug("Not finished or failed, retrying");

            // we got a status successfully, so reset the counter
            tries.set(0);

            executorService.schedule(this, WAIT_SECONDS, TimeUnit.SECONDS);
        }
    } catch (final HodErrorException e) {
        log.error("Error retrieving job status for jobId: {}", jobId);
        log.error("Cause:", e);

        if (DO_NOT_RETRY_CODES.contains(e.getErrorCode())) {
            log.error("Unrecoverable error, will not retry");

            callback.error(e.getErrorCode());
        } else if (tries.get() >= MAX_TRIES) {
            log.error("Max retries reached, will not retry");

            callback.error(e.getErrorCode());
        } else {
            log.error("Retrying");

            tries.incrementAndGet();

            executorService.schedule(this, WAIT_SECONDS, TimeUnit.SECONDS);
        }
    } catch (final RuntimeException e) {
        log.error("Error retrieving job status for jobId: {}", jobId);
        log.error("Cause:", e);

        callback.handleException(e);
    }
}

From source file:com.hpe.software.utils.Utils.java

License:Apache License

/**
 * Connects to AgM//from w  ww  . j a v  a  2  s  . c o  m
 * @param conf
 * @param agmConnector
 * @throws AuthenticationException
 * @throws BadResponseException
 */
public static LocalDateTime connectToAgM(Configuration conf, AgmConnector agmConnector)
        throws AuthenticationException, BadResponseException {
    int expiresIn;
    expiresIn = agmConnector.connect(conf.getConfigValue(Configuration.Key.AGM_CLIENT_ID),
            conf.getConfigValue(Configuration.Key.AGM_CLIENT_SECRET));
    LocalDateTime retValue = LocalDateTime.now().plusSeconds(expiresIn);
    log.info("Connected to AgM; Connection token will expire at: " + retValue);

    return retValue;
}