Example usage for java.util Date before

List of usage examples for java.util Date before

Introduction

In this page you can find the example usage for java.util Date before.

Prototype

public boolean before(Date when) 

Source Link

Document

Tests if this date is before the specified date.

Usage

From source file:edu.northwestern.bioinformatics.studycalendar.service.SubjectService.java

private List<ScheduledActivity> getPotentialUpcomingEvents(ScheduledCalendar calendar, Date offStudyDate) {
    List<ScheduledActivity> upcomingScheduledActivities = new ArrayList<ScheduledActivity>();
    for (ScheduledStudySegment studySegment : calendar.getScheduledStudySegments()) {
        if (!studySegment.isComplete()) {
            Map<Date, List<ScheduledActivity>> eventsByDate = studySegment.getActivitiesByDate();
            for (Date date : eventsByDate.keySet()) {
                List<ScheduledActivity> events = eventsByDate.get(date);
                for (ScheduledActivity event : events) {
                    if ((offStudyDate.before(event.getActualDate())
                            || offStudyDate.equals(event.getActualDate()))
                            && (ScheduledActivityMode.SCHEDULED == event.getCurrentState().getMode()
                                    || ScheduledActivityMode.CONDITIONAL == event.getCurrentState()
                                            .getMode())) {
                        upcomingScheduledActivities.add(event);
                    }// w w  w. j  a v a  2 s  . c o m
                }
            }
        }
    }
    return upcomingScheduledActivities;
}

From source file:github.popeen.dsub.activity.SubsonicFragmentActivity.java

private void loadRemotePlayQueue() {
    if (Util.getPreferences(this).getBoolean(Constants.PREFERENCES_KEY_RESUME_PLAY_QUEUE_NEVER, false)) {
        return;/*from w  ww . ja va2s  . co  m*/
    }

    final SubsonicActivity context = this;
    new SilentBackgroundTask<Void>(this) {
        private PlayerQueue playerQueue;

        @Override
        protected Void doInBackground() throws Throwable {
            try {
                MusicService musicService = MusicServiceFactory.getMusicService(context);
                PlayerQueue remoteState = musicService.getPlayQueue(context, null);

                // Make sure we wait until download service is ready
                DownloadService downloadService = getDownloadService();
                while (downloadService == null || !downloadService.isInitialized()) {
                    Util.sleepQuietly(100L);
                    downloadService = getDownloadService();
                }

                // If we had a remote state and it's changed is more recent than our existing state
                if (remoteState != null && remoteState.changed != null) {
                    // Check if changed + 30 seconds since some servers have slight skew
                    Date remoteChange = new Date(remoteState.changed.getTime() - ALLOWED_SKEW);
                    Date localChange = downloadService.getLastStateChanged();
                    if (localChange == null || localChange.before(remoteChange)) {
                        playerQueue = remoteState;
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Failed to get playing queue to server", e);
            }

            return null;
        }

        @Override
        protected void done(Void arg) {
            if (!context.isDestroyedCompat() && playerQueue != null) {
                promptRestoreFromRemoteQueue(playerQueue);
            }
        }
    }.execute();
}

From source file:vitkin.sfdc.mojo.wsdl.WsdlDownloadlMojo.java

/**
 * Tell if a session is older than an hour.
 *
 * @param client HTTP client for which to attempt deducing if the session has
 *               expired./*from   www .j  av  a2 s . co  m*/
 *
 * @return String The resource server for the session if the session hasn't
 *         expired. Null otherwise.
 */
private String getResourceServer(InnerHttpClient client) {
    Log logger = getLog();

    // Cookie 'oid' expiry date is supposed to be in 2 years in the future from
    // the date of creation of the cookie.
    final Calendar cal = GregorianCalendar.getInstance();
    cal.add(Calendar.YEAR, 2);
    cal.add(Calendar.HOUR, -1);

    final Date futureDate = cal.getTime();

    if (logger.isDebugEnabled()) {
        logger.debug("Future date: " + futureDate);
    }

    String resourceServer = null;

    for (Cookie cookie : client.getCookieStore().getCookies()) {
        final String name = cookie.getName();

        if ("oid".equals(name)) {
            final Date expiryDate = cookie.getExpiryDate();

            if (logger.isDebugEnabled()) {
                logger.debug("Expiry date: " + expiryDate);
            }

            if (futureDate.before(expiryDate)) {
                resourceServer = "https://" + cookie.getDomain();
            }

            break;
        }
    }

    return resourceServer;
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.services.ElasticsearchIndexService.java

/** Checks if an index/set-of-indexes spawned from a bucket
 * @param bucket/*  www.java2 s  .co  m*/
 */
protected Optional<JsonNode> handlePotentiallyNewIndex(final DataBucketBean bucket,
        final Optional<String> secondary_buffer, final boolean is_primary,
        final ElasticsearchIndexServiceConfigBean schema_config, final String index_type) {
    try {
        // Will need the current mapping regardless (this is just some JSON parsing so should be pretty quick):
        final XContentBuilder mapping = ElasticsearchIndexUtils.createIndexMapping(bucket, secondary_buffer,
                is_primary, schema_config, _mapper, index_type);
        final JsonNode user_mapping = _mapper.readTree(mapping.bytes().toUtf8());

        final String cache_key = bucket._id() + secondary_buffer.map(s -> ":" + s).orElse("") + ":"
                + Boolean.toString(is_primary);
        final Date current_template_time = _bucket_template_cache.getIfPresent(cache_key);
        if ((null == current_template_time)
                || current_template_time.before(Optional.ofNullable(bucket.modified()).orElse(new Date()))) {
            try {
                final GetIndexTemplatesRequest gt = new GetIndexTemplatesRequest()
                        .names(ElasticsearchIndexUtils.getBaseIndexName(bucket, secondary_buffer));
                final GetIndexTemplatesResponse gtr = _crud_factory.getClient().admin().indices()
                        .getTemplates(gt).actionGet();

                if (gtr.getIndexTemplates().isEmpty()
                        || !mappingsAreEquivalent(gtr.getIndexTemplates().get(0), user_mapping, _mapper)) {
                    // If no template, or it's changed, then update
                    final String base_name = ElasticsearchIndexUtils.getBaseIndexName(bucket, secondary_buffer);
                    _crud_factory.getClient().admin().indices().preparePutTemplate(base_name).setSource(mapping)
                            .execute().actionGet();

                    _logger.info(ErrorUtils.get("Updated mapping for bucket={0}, base_index={1}",
                            bucket.full_name(), base_name));
                }
            } catch (Exception e) {
                _logger.error(ErrorUtils.getLongForm("Error updating mapper bucket={1} err={0}", e,
                        bucket.full_name()));
            }
            _bucket_template_cache.put(cache_key, bucket.modified());
        }
        return Optional.of(user_mapping);
    } catch (Exception e) {
        return Optional.empty();
    }
}

From source file:com.dattasmoon.pebble.plugin.NotificationService.java

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    // handle the prefs changing, because of how accessibility services
    // work, sharedprefsonchange listeners don't work
    if (watchFile.lastModified() > lastChange) {
        loadPrefs();/* w ww  . ja  v  a  2 s . c  o  m*/
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Service: Mode is: " + String.valueOf(mode.ordinal()));
    }
    // if we are off, don't do anything.
    if (mode == Mode.OFF) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Service: Mode is off, not sending any notifications");
        }
        return;
    }

    //handle quiet hours
    if (quiet_hours) {

        Calendar c = Calendar.getInstance();
        Date now = new Date(0, 0, 0, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Checking quiet hours. Now: " + now.toString() + " vs "
                    + quiet_hours_before.toString() + " and " + quiet_hours_after.toString());
        }

        if (quiet_hours_before.after(quiet_hours_after)) {
            if (now.after(quiet_hours_after) && now.before(quiet_hours_before)) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, "Time is during quiet time. Returning.");
                }
                return;
            }

        } else if (now.before(quiet_hours_before) || now.after(quiet_hours_after)) {
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Time is before or after the quiet hours time. Returning.");
            }
            return;
        }

    }

    // handle if they only want notifications
    if (notifications_only) {
        if (event != null) {
            Parcelable parcelable = event.getParcelableData();
            if (!(parcelable instanceof Notification)) {

                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG,
                            "Event is not a notification and notifications only is enabled. Returning.");
                }
                return;
            }
        }
    }
    if (no_ongoing_notifs) {
        Parcelable parcelable = event.getParcelableData();
        if (parcelable instanceof Notification) {
            Notification notif = (Notification) parcelable;
            if ((notif.flags & Notification.FLAG_ONGOING_EVENT) == Notification.FLAG_ONGOING_EVENT) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG,
                            "Event is a notification, notification flag contains ongoing, and no ongoing notification is true. Returning.");
                }
                return;
            }
        } else {
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Event is not a notification.");
            }
        }
    }

    // Handle the do not disturb screen on settings
    PowerManager powMan = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    if (Constants.IS_LOGGABLE) {
        Log.d(Constants.LOG_TAG, "NotificationService.onAccessibilityEvent: notifScreenOn=" + notifScreenOn
                + "  screen=" + powMan.isScreenOn());
    }
    if (!notifScreenOn && powMan.isScreenOn()) {
        return;
    }

    if (event == null) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Event is null. Returning.");
        }
        return;
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Event: " + event.toString());
    }

    // main logic
    PackageManager pm = getPackageManager();

    String eventPackageName;
    if (event.getPackageName() != null) {
        eventPackageName = event.getPackageName().toString();
    } else {
        eventPackageName = "";
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Service package list is: ");
        for (String strPackage : packages) {
            Log.i(Constants.LOG_TAG, strPackage);
        }
        Log.i(Constants.LOG_TAG, "End Service package list");
    }

    switch (mode) {
    case EXCLUDE:
        // exclude functionality
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Mode is set to exclude");
        }

        for (String packageName : packages) {
            if (packageName.equalsIgnoreCase(eventPackageName)) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, packageName + " == " + eventPackageName
                            + " which is on the exclude list. Returning.");
                }
                return;
            }
        }
        break;
    case INCLUDE:
        // include only functionality
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Mode is set to include only");
        }
        boolean found = false;
        for (String packageName : packages) {
            if (packageName.equalsIgnoreCase(eventPackageName)) {
                found = true;
                break;
            }
        }
        if (!found) {
            Log.i(Constants.LOG_TAG, eventPackageName + " was not found in the include list. Returning.");
            return;
        }
        break;
    }

    // get the title
    String title = "";
    try {
        boolean renamed = false;
        for (int i = 0; i < pkg_renames.length(); i++) {
            if (pkg_renames.getJSONObject(i).getString("pkg").equalsIgnoreCase(eventPackageName)) {
                renamed = true;
                title = pkg_renames.getJSONObject(i).getString("to");
            }
        }
        if (!renamed) {
            title = pm.getApplicationLabel(pm.getApplicationInfo(eventPackageName, 0)).toString();
        }
    } catch (NameNotFoundException e) {
        title = eventPackageName;
    } catch (JSONException e) {
        title = eventPackageName;
    }

    // get the notification text
    String notificationText = event.getText().toString();
    // strip the first and last characters which are [ and ]
    notificationText = notificationText.substring(1, notificationText.length() - 1);

    if (notification_extras) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Fetching extras from notification");
        }
        Parcelable parcelable = event.getParcelableData();
        if (parcelable instanceof Notification) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                notificationText += "\n" + getExtraBigData((Notification) parcelable, notificationText.trim());
            } else {
                notificationText += "\n" + getExtraData((Notification) parcelable, notificationText.trim());
            }

        }
    }

    // Check ignore lists
    for (int i = 0; i < ignores.length(); i++) {
        try {
            JSONObject ignore = ignores.getJSONObject(i);
            String app = ignore.getString("app");
            boolean exclude = ignore.optBoolean("exclude", true);
            boolean case_insensitive = ignore.optBoolean("insensitive", true);
            if ((!app.equals("-1")) && (!eventPackageName.equalsIgnoreCase(app))) {
                //this rule doesn't apply to all apps and this isn't the app we're looking for.
                continue;
            }
            String regex = "";
            if (case_insensitive) {
                regex += "(?i)";
            }
            if (!ignore.getBoolean("raw")) {
                regex += Pattern.quote(ignore.getString("match"));
            } else {
                regex += ignore.getString("match");
            }
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(notificationText);
            if (m.find()) {
                if (exclude) {
                    if (Constants.IS_LOGGABLE) {
                        Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText + "' matches: '"
                                + regex + "' and exclude is on. Returning");
                    }
                    return;
                }
            } else {
                if (!exclude) {
                    if (Constants.IS_LOGGABLE) {
                        Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText
                                + "' does not match: '" + regex + "' and include is on. Returning");
                    }
                    return;
                }

            }
        } catch (JSONException e) {
            continue;
        }
    }

    // Send the alert to Pebble

    sendToPebble(title, notificationText);

    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, event.toString());
        Log.i(Constants.LOG_TAG, event.getPackageName().toString());
    }
}

From source file:nz.net.orcon.kanban.controllers.CardController.java

@SuppressWarnings("unchecked")
private List<CardNotification> retrieveNotifications(ObjectContentManager ocm, String cardNotificationUrl,
        String startDate, String endDate) throws ParseException {

    final List<CardNotification> cardNotifications = new ArrayList<CardNotification>();

    for (CardNotification cardNotification : (Collection<CardNotification>) ocm
            .getChildObjects(CardNotification.class, cardNotificationUrl)) {

        final Date notificationTime = cardNotification.getOccuredTime();
        if (notificationTime.after(listTools.decodeShortDate(startDate))) {
            if (notificationTime.before(listTools.decodeShortDate(endDate))) {
                cardNotifications.add(cardNotification);
            }/*from  w w w.  ja  va  2 s . c  o m*/
        }
    }
    return cardNotifications;
}

From source file:com.intuit.it.billing.data.BillingFileReader.java

/**
 * getBillingHistory is to be used to get  get the billing history of a given customer.
 * <p/>//from   w ww. j  a v a 2 s .c  o  m
 * <p/>
 * <b>DATABASE PROCEDURE:</b>
 *  
 * @code
 *  FUNCTION fn_get_history(
 *    customer   IN VARCHAR2,
 *    start_date IN DATE,
 *    end_date   IN DATE,
 *    page       IN INTEGER,
 *    records    IN INTEGER )
 *  RETURN ref_cursor;
 *  @endcode
 * <p/>
 * <b>DATABASE RESULT SET:</b>
 * <ul>
 *    <li>ITEM_ID,</li>
 *    <li>BILL_ITEM_NO,</li>
 *    <li>AR_ACCOUNT_NO,</li>
 *    <li>ACCOUNT_NO,</li>
 *    <li>ORDER_NO,</li>
 *    <li>ORDER_LINE_NO,</li>
 *    <li>EVENT_TYPE,</li>
 *    <li>CHARGE_TYPE,</li>
 *    <li> CURRENCY,</li>
 *    <li>CREATED_DATE,</li>
 *    <li>BILL_DATE,</li>
 *    <li>DUE_DATE,</li>
 *    <li>STATUS,</li>
 *    <li>REASON_CODE,</li>
 *    <li>ITEM_TOTAL,</li>
 *    <li>ITEM_DUE,</li>
 *    <li>ITEM_DISPUTED,</li>
 *    <li>ITEM_BASE,</li>
 *    <li>ITEM_TAX,</li>
 *    <li>ITEM_DESCRIPTION,</li>
 *    <li>ITEM_CODE,</li>
 *    <li>LICENSE,</li>
 *    <li>PAY_TYPE,</li>
 *    <li>PAY_DESCR,</li>
 *    <li>PAY_ACCT_TYPE,
 *    <li>PAY_PSON,</li>
 *    <li>QUANTITY </li>
 *  </ul>
 *  
 * @param customer  :  The Customer.accountNo of the customer we want history for
 * @param startDate : The starting date of the allocation - to be merged with a billing history record set
 * @param endDate   :  The ending date of the allocation - to be merged with a billing history record set
 * @param skip      :  Starting record for server side paging
 * @param pageSize  :  How many records to retrieve 
 * 
 * @return A list of LineItem objects in reverse date order sort
 */
@Override
public List<LineItem> getBillingHistory(String cust, Date startDate, Date endDate, Integer startPage,
        Integer pageSize) throws JSONException {

    List<LineItem> history = new ArrayList<LineItem>();

    try {
        //csv file containing data
        String strFile = directory + "h_" + cust + ".csv";
        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy h:mm");

        //create BufferedReader to read csv file
        BufferedReader br = new BufferedReader(new FileReader(strFile));
        String strLine = "";
        int lineNumber = 0, tokenNumber = 0;

        //read comma separated file line by line
        while ((strLine = br.readLine()) != null) {

            if (strLine.startsWith("$")) {
                continue;
            }

            lineNumber++;

            if (startPage >= 1 && lineNumber < startPage) {
                continue;
            }

            if (startPage >= 1 && lineNumber >= startPage + pageSize) {
                break;
            }

            //break comma separated line using ","
            String[] splitted = strLine.split(",");
            tokenNumber = 0;

            LineItem l = new LineItem();

            l.setRowId(Integer.parseInt(splitted[tokenNumber]));
            tokenNumber++;
            l.setItemID(splitted[tokenNumber]);
            tokenNumber++;
            l.setBillItemNo(splitted[tokenNumber]);
            tokenNumber++;
            l.setBillTo(splitted[tokenNumber]);
            tokenNumber++;
            tokenNumber++; // account

            l.setOrderLine(splitted[tokenNumber]);
            tokenNumber++;
            l.setOrderNo(splitted[tokenNumber]);
            tokenNumber++;
            l.setEventType(splitted[tokenNumber]);
            tokenNumber++;
            l.setChargeType(splitted[tokenNumber]);
            tokenNumber++;
            l.setCurrency(splitted[tokenNumber]);
            tokenNumber++;
            l.setCreatedDate(formatter.parse(splitted[tokenNumber]));
            tokenNumber++;

            Date d = l.getCreatedDate();
            if (d != null && startDate.after(formatter.parse("01/01/1990 00:00"))
                    && endDate.after(formatter.parse("01/01/1990 00:00"))) {
                if (d.before(startDate) || d.after(endDate)) {
                    lineNumber--;
                    continue;
                }
            }

            l.setBillDate(formatter.parse(splitted[tokenNumber]));
            tokenNumber++;
            l.setDueDate(formatter.parse(splitted[tokenNumber]));
            tokenNumber++;
            l.setStatus(Integer.parseInt(splitted[tokenNumber]));
            tokenNumber++;
            l.setReasonCode(splitted[tokenNumber]);
            tokenNumber++;
            l.setItemTotal(new BigDecimal(splitted[tokenNumber]));
            tokenNumber++;
            l.setItemDue(new BigDecimal(splitted[tokenNumber]));
            tokenNumber++;
            l.setItemDisputed(new BigDecimal(splitted[tokenNumber]));
            tokenNumber++;
            l.setBaseAmount(new BigDecimal(splitted[tokenNumber]));
            tokenNumber++;
            l.setTaxAmount(new BigDecimal(splitted[tokenNumber]));
            tokenNumber++;
            l.setItemDescription(splitted[tokenNumber]);
            tokenNumber++;
            l.setItemCode(splitted[tokenNumber]);
            tokenNumber++;
            l.setLicense(splitted[tokenNumber]);
            tokenNumber++;
            l.setPayType(splitted[tokenNumber]);
            tokenNumber++;
            l.setPayDescription(splitted[tokenNumber]);
            tokenNumber++;
            l.setPayAccountType(splitted[tokenNumber]);
            tokenNumber++;
            l.setpSON(splitted[tokenNumber]);
            tokenNumber++;
            l.setQuantity(Integer.parseInt(splitted[tokenNumber]));
            tokenNumber++;
            history.add(l);

        }

        br.close();

    } catch (Exception e) {
        System.out.println("Exception while reading csv file:  " + e);
        throw JSONException.noDataFound("Bad file read " + e.getMessage());

    }

    if (history == null || history.isEmpty()) {
        throw JSONException.noDataFound("Null set returned - no data found");
    }

    return history;
}

From source file:com.streamreduce.util.GitHubClient.java

/**
 * Retrieves the activity for the given connection based on the last poll date stored in the connection.
 *
 * Note: This list is already sorted in the proper order, contains no duplicates and contains only entries that
 *       are pertinent:/*from www . j  a  v a2s  . c om*/
 *
 *         * Entries will correspond with a project in the projectKeys set unless that set is empty/null and then
 *           entries can be for any project
 *         * Entries will after the last activity date in the connection
 *
 * @param projectKeys the project keys we're interested in or null for all
 * @param maxActivities the maximum number of results to return
 *
 * @return list of JSONObjects representing activity entries
 *
 * @throws InvalidCredentialsException if the connection associated with this client has invalid credentials
 * @throws IOException if anything goes wrong making the actual request
 */
public List<JSONObject> getActivity(Set<String> projectKeys, int maxActivities)
        throws InvalidCredentialsException, IOException {
    // The way we gather activity for a GitHub connection is by making a few events feeds calls, merging them
    // together and then returning the results.  The end result should be a list of pertinent events that have no
    // duplicates and includes all necessary events after the last poll period.
    //
    // The GitHub API request logic looks like this:
    //
    //   * /users/<user_id>/received_events: This is the list of events that the user has "received" by watching
    //                                       repositories/users.
    //   * /users/<user_id>/events: This is a list of events that the user itself has created.
    //   * /users/<user_id>/events/orgs/<org_id>: This is a list of events that have been performed within the
    //                                            the organization.  (This will also require a call prior to this
    //                                            to get the user's organizations, if any.)

    debugLog(LOGGER, "Getting activity");

    // Establish some defaults for fields that can be null
    projectKeys = (projectKeys != null ? projectKeys : new HashSet<String>());
    maxActivities = (maxActivities >= 1 ? maxActivities : 100);

    List<JSONObject> allActivityItems = new ArrayList<>();
    Set<Integer> processedActivityHashes = new HashSet<>();
    Date lastActivity = getLastActivityPollDate();
    Set<String> eventsUrls = new HashSet<>();
    String username = getConnectionCredentials().getIdentity();

    // Generate the list of events URLs to process
    eventsUrls.add(GITHUB_API_BASE + "users/" + username + "/received_events"); // User's received events
    eventsUrls.add(GITHUB_API_BASE + "users/" + username + "/events"); // User's events

    //        // To generate the list of organization URLs to process, we need to walk through the user's organizations list
    //        List<JSONObject> organizations = getOrganizations();
    //
    //        for (JSONObject organization : organizations) {
    //            eventsUrls.add(GITHUB_API_BASE + "users/" + username + "/events/orgs/" + organization.getString("login"));
    //        }

    for (String eventUrl : eventsUrls) {
        List<JSONObject> rawActivity = makeRequest(eventUrl, maxActivities, false);

        for (JSONObject activity : rawActivity) {
            String eventType = activity.getString("type");
            String repoName = activity.getJSONObject("repo").getString("name");
            Date activityDate = getCreatedDate(activity);

            // If we do not support the event type or its for a repository we don't monitor, move on
            if (!SUPPORTED_EVENT_TYPES.contains(eventType) || !projectKeys.contains(repoName)) {
                continue;
            }

            if (activityDate.before(lastActivity)) {
                break;
            }

            int activityHash = activity.hashCode();

            if (!processedActivityHashes.contains(activityHash) && allActivityItems.size() < maxActivities) {
                allActivityItems.add(activity);
                processedActivityHashes.add(activityHash);
            }
        }
    }

    // Sort the activities
    Collections.sort(allActivityItems, new Comparator<JSONObject>() {
        /**
         * {@inheritDoc}
         */
        @Override
        public int compare(JSONObject jo0, JSONObject jo1) {
            Date jod0 = getCreatedDate(jo0);
            Date jod1 = getCreatedDate(jo1);

            return jod0.compareTo(jod1);
        }
    });

    // Return only the maximum number of results if the list of activities is greater than the maximum requested
    if (allActivityItems.size() > maxActivities) {
        allActivityItems = allActivityItems.subList(0, maxActivities);
    }

    debugLog(LOGGER, "  Activities found: " + allActivityItems.size());

    return allActivityItems;
}

From source file:com.pinterest.teletraan.worker.AutoPromoter.java

boolean autoDeployDue(DeployBean deployBean, String cronExpressionString) {
    Date date = new Date();
    try {/*from   w  w w .  jav a  2  s  . c  o  m*/
        if (!CronExpression.isValidExpression(cronExpressionString)) {
            LOG.error(String.format("Cron expression %s is not valid. Ignore it.", cronExpressionString));
            return true;
        }
        CronExpression cronExpression = new CronExpression(cronExpressionString);
        if (deployBean == null) {
            return true;
        }
        Date lastDeloyDate = new Date(deployBean.getStart_date());
        Date nextDeployDate = cronExpression.getNextValidTimeAfter(lastDeloyDate);
        // Only run the cron deploy when the current date is equal or after the scheduled deploy date
        // since last deploy.
        //
        // If current date is before the next scheduled deploy date since last deploy, return false.
        if (date.before(nextDeployDate)) {
            LOG.info(String.format("The next scheduled deploy after last deploy %tc is %tc, now is: %tc",
                    nextDeployDate, lastDeloyDate, date));
            return false;
        } else {
            return true;
        }
    } catch (ParseException e) {
        LOG.error(String.format("Failed to parse cron expression: %s. Reason: %s", cronExpressionString,
                e.getMessage()));
        return true;
    } catch (Exception e) {
        LOG.error(String.format("Failed to validate date. Reason: %s", e.getMessage()));
        return true;
    }
}

From source file:com.intuit.it.billing.data.BillingFileReader.java

/**
 * getAllocationsList//from   w w  w. j  a  va 2s  . c  om
 * 
 * To be used in a caching method where we are pulling all of the allocations at once.  The way we can do this
 * is to merge a date range based set of billing history records with a date range set of allocations.
 * <p/>
 * <p/>
 * <b>DATABASE PROCEDURE:</b>
 *  
 * @code
 *     FUNCTION fn_get_allocations(
 *           customer IN VARCHAR2,
 *           start_date IN DATE,
 *           end_date   IN DATE )
 *        RETURN ref_cursor;
 * @endcode
 * <p/>
 * <b>DATABASE RESULT SET:</b>
 * <ul>
 *    <li>ALLOCATION_DATE,</li>
 *    <li>ALLOCATION_T, </li>
 *    <li>ALLOCATION_AMT,</li>
 *    <li>AR_ITEM_NO, </li>
 *    <li>BILL_ITEM_NO, </li>
 *    <li>ITEM_DESCRIPTION, </li>
 *    <li>ITEM_CODE,</li> 
 *    <li>AR_ITEM_DATE, </li>
 *    <li>BILL_ITEM_DATE </li>
 *    <li>LICENSE</li>
 *  </ul>
 *  
 * @param customer  :  The Customer.accountNo account number of the customer who's allocations we need
 * @param startDate : The starting date of the allocation - to be merged with a billing history record set
 * @param endDate  :  The ending date of the allocation - to be merged with a billing history record set
 * 
 * @return A list of Allocation objects. 
 * 
 */
@Override
public List<Allocation> getAllocationsList(String customer, Date startDate, Date endDate) throws JSONException {

    List<Allocation> allocs = new ArrayList<Allocation>();

    try {
        //csv file containing data
        String strFile = directory + "ac_" + customer + ".csv";
        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy h:mm");

        //create BufferedReader to read csv file
        BufferedReader br = new BufferedReader(new FileReader(strFile));
        String strLine = "";
        int lineNumber = 0, tokenNumber = 0;

        //read comma separated file line by line
        while ((strLine = br.readLine()) != null) {

            if (strLine.startsWith("$")) {
                continue;
            }

            lineNumber++;

            tokenNumber = 0;

            //break comma separated line using ","
            String[] splitted = strLine.split(",");

            Allocation l = new Allocation();

            l.setLicense(splitted[tokenNumber]);
            tokenNumber++;
            l.setAllocationDate(formatter.parse(splitted[tokenNumber]));
            tokenNumber++;

            Date d = l.getAllocationDate();
            if (d != null && d.after(formatter.parse("01/01/1990 00:00"))
                    && startDate.after(formatter.parse("01/01/1990 00:00"))
                    && endDate.after(formatter.parse("01/01/1990 00:00"))) {
                if (d.before(startDate) || d.after(endDate)) {
                    lineNumber--;
                    continue;
                }
            }

            l.setAllocationAmount(new BigDecimal(splitted[tokenNumber]));
            tokenNumber++;
            l.setAllocatedFromItem(splitted[tokenNumber]);
            tokenNumber++;
            l.setAllocatedToItem(splitted[tokenNumber]);
            tokenNumber++;
            l.setItemDescription(splitted[tokenNumber]);
            tokenNumber++;
            l.setItemCode(splitted[tokenNumber]);
            tokenNumber++;
            allocs.add(l);
        }

        br.close();

    } catch (Exception e) {
        System.out.println("Exception while reading csv file:  " + e);
        throw JSONException.noDataFound("Bad file read " + e.getMessage());

    }

    if (allocs == null || allocs.isEmpty()) {
        throw JSONException.noDataFound("Null set returned - no data found");
    }

    return allocs;
}