Example usage for org.joda.time LocalDateTime LocalDateTime

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

Introduction

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

Prototype

public LocalDateTime() 

Source Link

Document

Constructs an instance set to the current local time evaluated using ISO chronology in the default zone.

Usage

From source file:at.wada811.dayscounter.view.appwidget.CounterAppWidgetProvider.java

License:Apache License

@TargetApi(Build.VERSION_CODES.KITKAT)
public static void setDateChangeAlarm(Context context) {
    Intent intent = new Intent(DateTimeChangeReceiver.ACTION_DATE_CHANGED);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    LocalDateTime today = new LocalDateTime();
    LocalDateTime tomorrow = today.plusDays(1);
    alarmManager.cancel(pendingIntent);//from  www .  j  a  va2 s  . co m
    if (AndroidUtils.isLessThanBuildVersion(Build.VERSION_CODES.KITKAT)) {
        alarmManager.set(AlarmManager.RTC, tomorrow.toDateTime().getMillis(), pendingIntent);
    } else {
        alarmManager.setExact(AlarmManager.RTC, tomorrow.toDateTime().getMillis(), pendingIntent);
    }
}

From source file:azkaban.app.jmx.JobScheduler.java

License:Apache License

public String scheduleWorkflow(String jobName, boolean ignoreDeps, int hour, int minutes, int seconds,
        String scheduledDate, boolean isRecurring, int period, String periodUnits) {
    String errorMsg = null;/*from  ww  w  .  j a v a2s.  c  om*/
    if (jobName == null || jobName.trim().length() == 0) {
        errorMsg = "You must select at least one job to run.";
        logger.error(errorMsg);
        return errorMsg;
    }
    JobDescriptor descriptor = jobManager.getJobDescriptor(jobName);
    if (descriptor == null) {
        errorMsg = "Job: '" + jobName + "' doesn't exist.";
        logger.error(errorMsg);
        return errorMsg;
    }

    DateTime day = null;
    DateTime time = null;
    try {
        if (scheduledDate == null || scheduledDate.trim().length() == 0) {
            day = new LocalDateTime().toDateTime();
            time = day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(seconds);
            if (day.isAfter(time)) {
                time = time.plusDays(1);
            }
        } else {
            try {
                day = DateTimeFormat.forPattern("MM-dd-yyyy").parseDateTime(scheduledDate);
            } catch (IllegalArgumentException e) {
                logger.error(e);
                return "Invalid date: '" + scheduledDate + "', \"MM-dd-yyyy\" format is expected.";
            }
            time = day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(seconds);
        }
    } catch (IllegalFieldValueException e) {
        logger.error(e);
        return "Invalid schedule time (see logs): " + e.getMessage();

    }
    ReadablePeriod thePeriod = null;
    if (isRecurring) {
        if ("d".equals(periodUnits)) {
            thePeriod = Days.days(period);
        } else if ("h".equals(periodUnits)) {
            thePeriod = Hours.hours(period);
        } else if ("m".equals(periodUnits)) {
            thePeriod = Minutes.minutes(period);
        } else if ("s".equals(periodUnits)) {
            thePeriod = Seconds.seconds(period);
        } else {
            errorMsg = "Unknown period unit: " + periodUnits;
            logger.error(errorMsg);
            return errorMsg;
        }
    }
    try {
        if (thePeriod == null) {
            scheduler.schedule(jobName, time, ignoreDeps);
        } else {
            scheduler.schedule(jobName, time, thePeriod, ignoreDeps);
        }
        return "Schedule Successful!";
    } catch (Exception e) {
        logger.error(e);
        return "Schedule Failed (see logs): " + e.getMessage();
    }
}

From source file:azkaban.web.pages.IndexServlet.java

License:Apache License

private String scheduleJobs(AzkabanApplication app, HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    String[] jobNames = req.getParameterValues("jobs");
    if (!hasParam(req, "jobs")) {
        addError(req, "You must select at least one job to run.");
        return "";
    }/* w w w .  jav  a 2s .  co  m*/

    if (hasParam(req, "flow_now")) {
        if (jobNames.length > 1) {
            addError(req, "Can only run flow instance on one job.");
            return "";
        }

        String jobName = jobNames[0];
        JobManager jobManager = app.getJobManager();
        JobDescriptor descriptor = jobManager.getJobDescriptor(jobName);
        if (descriptor == null) {
            addError(req, "Can only run flow instance on one job.");
            return "";
        } else {
            return req.getContextPath() + "/flow?job_id=" + jobName;
        }
    } else {
        for (String job : jobNames) {
            if (hasParam(req, "schedule")) {
                int hour = getIntParam(req, "hour");
                int minutes = getIntParam(req, "minutes");
                boolean isPm = getParam(req, "am_pm").equalsIgnoreCase("pm");
                String scheduledDate = req.getParameter("date");
                DateTime day = null;
                if (scheduledDate == null || scheduledDate.trim().length() == 0) {
                    day = new LocalDateTime().toDateTime();
                } else {
                    try {
                        day = DateTimeFormat.forPattern("MM-dd-yyyy").parseDateTime(scheduledDate);
                    } catch (IllegalArgumentException e) {
                        addError(req, "Invalid date: '" + scheduledDate + "'");
                        return "";
                    }
                }

                ReadablePeriod thePeriod = null;
                if (hasParam(req, "is_recurring"))
                    thePeriod = parsePeriod(req);

                if (isPm && hour < 12)
                    hour += 12;
                hour %= 24;

                app.getScheduleManager().schedule(job,
                        day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(0), thePeriod,
                        false);

                addMessage(req, job + " scheduled.");
            } else if (hasParam(req, "run_now")) {
                boolean ignoreDeps = !hasParam(req, "include_deps");
                try {
                    app.getJobExecutorManager().execute(job, ignoreDeps);
                } catch (JobExecutionException e) {
                    addError(req, e.getMessage());
                    return "";
                }
                addMessage(req, "Running " + job);
            } else {
                addError(req, "Neither run_now nor schedule param is set.");
            }
        }
        return "";
    }

}

From source file:azkaban.webapp.servlet.ScheduleServlet.java

License:Apache License

private DateTime parseDateTime(String scheduleDate, String scheduleTime) {
    // scheduleTime: 12,00,pm,PDT
    String[] parts = scheduleTime.split(",", -1);
    int hour = Integer.parseInt(parts[0]);
    int minutes = Integer.parseInt(parts[1]);
    boolean isPm = parts[2].equalsIgnoreCase("pm");

    DateTimeZone timezone = parts[3].equals("UTC") ? DateTimeZone.UTC : DateTimeZone.getDefault();

    // scheduleDate: 02/10/2013
    DateTime day = null;//from  ww w  . jav a 2s .c om
    if (scheduleDate == null || scheduleDate.trim().length() == 0) {
        day = new LocalDateTime().toDateTime();
    } else {
        day = DateTimeFormat.forPattern("MM/dd/yyyy").withZone(timezone).parseDateTime(scheduleDate);
    }

    hour %= 12;

    if (isPm)
        hour += 12;

    DateTime firstSchedTime = day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(0);

    return firstSchedTime;
}

From source file:ca.ualberta.physics.cssdp.catalogue.dao.UrlDataProductDao.java

License:Apache License

public void process(UrlDataProductUpdateMap urlDataProductUpdateMap) {

    if (urlDataProductUpdateMap.getUrls().size() == 0) {
        return;/*from  w w  w.  j  a va 2s .co  m*/
    }

    /*
     * The size of scannedUrlDataProducts should be <= jdbc batch size
     * configured.
     */

    // we have to resort to hibernate directly because JPA does not have
    // scrolling capability
    Session session = emp.get().unwrap(Session.class).getSessionFactory().openSession();

    Transaction tx = session.beginTransaction();

    // "in" clause limit is 2^16 on Postgresql, it might be different on
    // other dbs
    String hqlString = "from UrlDataProduct urldp where urldp.url in (:urls)";

    // the fastest way to scroll through the existing data
    Query q = session.createQuery(hqlString);
    q.setParameterList("urls", urlDataProductUpdateMap.getUrls());
    q.setCacheMode(CacheMode.IGNORE);
    ScrollableResults existingData = q.scroll(ScrollMode.FORWARD_ONLY);

    while (existingData.next()) {

        UrlDataProduct existing = (UrlDataProduct) existingData.get(0);
        UrlDataProduct updated = urlDataProductUpdateMap.get(existing.getUrl());

        if (updated != null) {

            /*
             * Only bother to update the record if it's actually changed.
             * Note that the scan timestamp is ignored in the check because
             * that isn't something the provider changed. A change can also
             * mean the url was deleted, and now it's back.
             */
            if (existing.hasChanged(updated)) {
                // existing.setDataProduct(updated.getDataProduct());
                existing.setUrl(updated.getUrl());
                existing.setStartTimestamp(updated.getStartTimestamp());
                existing.setEndTimestamp(updated.getEndTimestamp());
                existing.setScanTimestamp(updated.getScanTimestamp());
                existing.setDeleted(false);
                urlDataProductUpdateMap.remove(updated.getUrl());
                session.update(existing);
            } else {
                // remove it so it's not duplicated
                urlDataProductUpdateMap.remove(existing.getUrl());
            }

        } else {

            // if we get here it means the existing url has been removed
            // from the server, set "delete" it from the catalogue
            existing.setDeleted(true);
            existing.setScanTimestamp(new LocalDateTime());

        }

    }

    // persist the new url mappings
    for (String newUrl : urlDataProductUpdateMap.getUrls()) {
        UrlDataProduct newUrlDataProduct = urlDataProductUpdateMap.get(newUrl);
        session.save(newUrlDataProduct);
        logger.debug("saved a mapping: " + newUrlDataProduct.getUrl());
    }

    session.flush();
    session.clear();

    tx.commit();
    session.close();

}

From source file:ca.ualberta.physics.cssdp.domain.auth.Session.java

License:Apache License

public boolean hasExpired() {
    return Hours.hoursBetween(tokenDate, new LocalDateTime()).getHours() > 48;
}

From source file:ca.ualberta.physics.cssdp.file.remote.command.RecursiveLs.java

License:Apache License

@Override
public void execute(RemoteConnection connection) {

    if (!hasError()) {
        try {// www.  j  a va2  s . c o m
            connection.connect();
            String rootUrl = connection.getHostEntry().getProtocol().name() + "://"
                    + (connection.getHostEntry().getProtocol().equals(Protocol.file) ? ""
                            : connection.getHostEntry().getHostname())
                    + rootDir;

            RemoteFile root = new RemoteFile(rootUrl, 0, new LocalDateTime(), true);

            fileList.addAll(visit(connection, root));

        } catch (Exception e) {
            logger.error("Recursive LS failed ", e);
            error(Throwables.getRootCause(e).getMessage());
        } finally {
            connection.disconnect();
            setDone(true);
        }

    }

}

From source file:ca.ualberta.physics.cssdp.file.service.CacheService.java

License:Apache License

public ServiceResponse<CachedFile> get(String md5) {

    ServiceResponse<CachedFile> sr = new ServiceResponse<CachedFile>();

    final CachedFile cachedFile = cachedFileDao.get(md5);
    if (cachedFile != null) {

        new ManualTransaction(sr, emp.get()) {

            @Override//from  ww  w. j  ava  2 s . co m
            public void onError(Exception e, ServiceResponse<?> sr) {
                sr.error(e.getMessage());
            }

            @Override
            public void doInTransaction() {
                cachedFile.setLastAccessed(new LocalDateTime());
                cachedFileDao.update(cachedFile);
            }
        };
        if (cachedFile.exists()) {
            sr.setPayload(cachedFile);
        } else {
            sr.error("File cache is inconsistent! The actual file is missing.  "
                    + "Remove this MD5 from cache to clean up the inconsistent state.");
        }
    } else {
        sr.warn("No cached file found for MD5 " + md5);
    }

    return sr;
}

From source file:ch.icclab.cyclops.resource.impl.ExternalAppResource.java

License:Open Source License

/**
 * Receives the JSON data sent by an external application
 *
 * Pseudo Code//from   w  w w .  java 2s .  com
 * 1. Receive the data
 * 2. Extract the JSON array
 * 3. Send the JSON array to saveData() for further processing
 *
 * @param entity
 * @return Representation A JSON response is returned
 */
@Post("json:json")
public Representation receiveRequest(JsonRepresentation entity) {

    JSONArray jsonArr = null;
    boolean output = true;

    LocalDateTime currentDateTime = new LocalDateTime();
    Response response = new Response();
    Representation jsonResponse = new JsonRepresentation(response);
    ResponseUtil util = new ResponseUtil();

    try {
        jsonArr = entity.getJsonArray();
        output = saveData(jsonArr);
    } catch (JSONException e) {
        output = false;
        e.printStackTrace();
    }
    response.setTimestamp(currentDateTime.toDateTime().toString());
    if (output) {
        response.setStatus("Success");
        response.setMessage("Data saved into the DB");
    } else {
        response.setStatus("Failure");
        response.setMessage("Data could not be saved into the DB");
    }
    jsonResponse = util.toJson(response);
    return jsonResponse;
}

From source file:ch.icclab.cyclops.resource.impl.MeterResource.java

License:Open Source License

/**
 * Receives the JSON data consisting of meter selection status
 *
 * Pseudo Code/*w w w. j  av  a 2  s  .  co m*/
 * 1. Receive the data
 * 2. Extract the JSON array
 * 3. Send the JSON array to saveData() for persistence into the DB
 *
 * @param entity The body of the POST request
 * @return Representation A JSON response containing the status of the request serviced
 */
@Post("json:json")
public Representation setMeterList(Representation entity) {
    boolean output = true;
    ObjectMapper mapper = new ObjectMapper();
    String jsonData = null;
    JsonRepresentation request = null;
    JsonRepresentation responseJson = null;
    LocalDateTime currentDateTime = new LocalDateTime();
    Response response = new Response();

    // Get the JSON representation of the incoming POST request
    try {
        request = new JsonRepresentation(entity);
    } catch (IOException e) {
        e.printStackTrace();
    }
    //Set the isMeterListReset to TRUE
    Flag.setMeterListReset(true);
    // Process the incoming request
    try {
        output = saveData(request.getJsonObject());
    } catch (JSONException e) {
        output = false;
        e.printStackTrace();
    }
    // Set the time stamp
    response.setTimestamp(currentDateTime.toDateTime().toString());
    // Set the status and message
    if (output) {
        response.setStatus("Success");
        response.setMessage("Data saved into the DB");
    } else {
        response.setStatus("Failure");
        response.setMessage("Data could not be saved into the DB");
    }
    // Convert the Java object to a JSON string
    try {
        jsonData = mapper.writeValueAsString(response);
        responseJson = new JsonRepresentation(jsonData);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

    return responseJson;
}