Example usage for org.apache.commons.lang.math LongRange containsLong

List of usage examples for org.apache.commons.lang.math LongRange containsLong

Introduction

In this page you can find the example usage for org.apache.commons.lang.math LongRange containsLong.

Prototype

public boolean containsLong(long value) 

Source Link

Document

Tests whether the specified long occurs within this range using long comparison.

This implementation overrides the superclass for performance as it is the most common case.

Usage

From source file:net.sourceforge.subsonic.controller.DownloadController.java

/**
 * Utility method for writing the content of a given file to a given output stream.
 *
 * @param file   The file to copy.//from w  ww  . j a  v a 2 s .c  o  m
 * @param out    The output stream to write to.
 * @param status The download status.
 * @param range  The byte range, may be <code>null</code>.
 * @throws IOException If an I/O error occurs.
 */
private void copyFileToStream(File file, OutputStream out, TransferStatus status, LongRange range)
        throws IOException {
    LOG.info("Downloading '" + FileUtil.getShortPath(file) + "' to " + status.getPlayer());

    final int bufferSize = 16 * 1024; // 16 Kbit
    InputStream in = new BufferedInputStream(new FileInputStream(file), bufferSize);

    try {
        byte[] buf = new byte[bufferSize];
        long bitrateLimit = 0;
        long lastLimitCheck = 0;

        while (true) {
            long before = System.currentTimeMillis();
            int n = in.read(buf);
            if (n == -1) {
                break;
            }
            out.write(buf, 0, n);

            // Don't sleep if outside range.
            if (range != null && !range.containsLong(status.getBytesSkipped() + status.getBytesTransfered())) {
                status.addBytesSkipped(n);
                continue;
            }

            status.addBytesTransfered(n);
            long after = System.currentTimeMillis();

            // Calculate bitrate limit every 5 seconds.
            if (after - lastLimitCheck > 5000) {
                bitrateLimit = 1024L * settingsService.getDownloadBitrateLimit()
                        / Math.max(1, statusService.getAllDownloadStatuses().size());
                lastLimitCheck = after;
            }

            // Sleep for a while to throttle bitrate.
            if (bitrateLimit != 0) {
                long sleepTime = 8L * 1000 * bufferSize / bitrateLimit - (after - before);
                if (sleepTime > 0L) {
                    try {
                        Thread.sleep(sleepTime);
                    } catch (Exception x) {
                        LOG.warn("Failed to sleep.", x);
                    }
                }
            }
        }
    } finally {
        out.flush();
        IOUtils.closeQuietly(in);
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.ClientRMService.java

/**
 * Get applications matching the {@link GetApplicationsRequest}. If
 * caseSensitive is set to false, applicationTypes in
 * GetApplicationRequest are expected to be in all-lowercase
 *///from w  ww .  ja v a2s  .c o  m
@Private
public GetApplicationsResponse getApplications(GetApplicationsRequest request, boolean caseSensitive)
        throws YarnException {
    UserGroupInformation callerUGI;
    try {
        callerUGI = UserGroupInformation.getCurrentUser();
    } catch (IOException ie) {
        LOG.info("Error getting UGI ", ie);
        throw RPCUtil.getRemoteException(ie);
    }

    Set<String> applicationTypes = request.getApplicationTypes();
    EnumSet<YarnApplicationState> applicationStates = request.getApplicationStates();
    Set<String> users = request.getUsers();
    Set<String> queues = request.getQueues();
    Set<String> tags = request.getApplicationTags();
    long limit = request.getLimit();
    LongRange start = request.getStartRange();
    LongRange finish = request.getFinishRange();
    ApplicationsRequestScope scope = request.getScope();

    final Map<ApplicationId, RMApp> apps = rmContext.getRMApps();
    Iterator<RMApp> appsIter;
    // If the query filters by queues, we can avoid considering apps outside
    // of those queues by asking the scheduler for the apps in those queues.
    if (queues != null && !queues.isEmpty()) {
        // Construct an iterator over apps in given queues
        // Collect list of lists to avoid copying all apps
        final List<List<ApplicationAttemptId>> queueAppLists = new ArrayList<List<ApplicationAttemptId>>();
        for (String queue : queues) {
            List<ApplicationAttemptId> appsInQueue = scheduler.getAppsInQueue(queue);
            if (appsInQueue != null && !appsInQueue.isEmpty()) {
                queueAppLists.add(appsInQueue);
            }
        }
        appsIter = new Iterator<RMApp>() {
            Iterator<List<ApplicationAttemptId>> appListIter = queueAppLists.iterator();
            Iterator<ApplicationAttemptId> schedAppsIter;

            @Override
            public boolean hasNext() {
                // Because queueAppLists has no empty lists, hasNext is whether the
                // current list hasNext or whether there are any remaining lists
                return (schedAppsIter != null && schedAppsIter.hasNext()) || appListIter.hasNext();
            }

            @Override
            public RMApp next() {
                if (schedAppsIter == null || !schedAppsIter.hasNext()) {
                    schedAppsIter = appListIter.next().iterator();
                }
                return apps.get(schedAppsIter.next().getApplicationId());
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("Remove not supported");
            }
        };
    } else {
        appsIter = apps.values().iterator();
    }

    List<ApplicationReport> reports = new ArrayList<ApplicationReport>();
    while (appsIter.hasNext() && reports.size() < limit) {
        RMApp application = appsIter.next();

        // Check if current application falls under the specified scope
        if (scope == ApplicationsRequestScope.OWN && !callerUGI.getUserName().equals(application.getUser())) {
            continue;
        }

        if (applicationTypes != null && !applicationTypes.isEmpty()) {
            String appTypeToMatch = caseSensitive ? application.getApplicationType()
                    : StringUtils.toLowerCase(application.getApplicationType());
            if (!applicationTypes.contains(appTypeToMatch)) {
                continue;
            }
        }

        if (applicationStates != null && !applicationStates.isEmpty()) {
            if (!applicationStates.contains(application.createApplicationState())) {
                continue;
            }
        }

        if (users != null && !users.isEmpty() && !users.contains(application.getUser())) {
            continue;
        }

        if (start != null && !start.containsLong(application.getStartTime())) {
            continue;
        }

        if (finish != null && !finish.containsLong(application.getFinishTime())) {
            continue;
        }

        if (tags != null && !tags.isEmpty()) {
            Set<String> appTags = application.getApplicationTags();
            if (appTags == null || appTags.isEmpty()) {
                continue;
            }
            boolean match = false;
            for (String tag : tags) {
                if (appTags.contains(tag)) {
                    match = true;
                    break;
                }
            }
            if (!match) {
                continue;
            }
        }

        // checkAccess can grab the scheduler lock so call it last
        boolean allowAccess = checkAccess(callerUGI, application.getUser(), ApplicationAccessType.VIEW_APP,
                application);
        if (scope == ApplicationsRequestScope.VIEWABLE && !allowAccess) {
            continue;
        }

        reports.add(application.createAndGetApplicationReport(callerUGI.getUserName(), allowAccess));
    }

    GetApplicationsResponse response = recordFactory.newRecordInstance(GetApplicationsResponse.class);
    response.setApplicationList(reports);
    return response;
}

From source file:org.openhab.io.caldav.internal.util.TimeRangeCalendar.java

/**
 * Find first TimeRange which contains the given <code>timeStamp</code>
 * @param timeStamp the TimeStamp to find
 * @return the first TimeRange which contains the given <code>timeStamp</code>
 * or <code>null</code> if no matching TimeRange exists
 *///from  ww  w  . j  a  va2 s .  c  o m
protected LongRange findTimeRange(long timeStamp) {
    for (LongRange range : excludedRanges) {
        if (range.containsLong(timeStamp)) {
            return range;
        }
    }
    return null;
}