Example usage for com.google.common.collect ImmutableSet isEmpty

List of usage examples for com.google.common.collect ImmutableSet isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:com.google.caliper.runner.CaliperRun.java

private static Collection<BenchmarkMethod> chooseBenchmarkMethods(BenchmarkClass benchmarkClass,
        Instrument instrument, CaliperOptions options) throws InvalidBenchmarkException {
    ImmutableMap<String, BenchmarkMethod> methodMap = benchmarkClass.findAllBenchmarkMethods(instrument);

    ImmutableSet<String> names = options.benchmarkMethodNames();

    // TODO(kevinb): this doesn't seem to prevent bogus names on cmd line yet
    return names.isEmpty() ? methodMap.values() : Maps.filterKeys(methodMap, Predicates.in(names)).values();
}

From source file:com.outerspacecat.icalendar.RecurrencePredicates.java

/**
 * Returns a predicate for determining whether or not to keep instances of
 * {@link FixedSchedule}. The returned predicate will return {@code true} for
 * a given {@link FixedSchedule} if the value of the field specified by
 * {@code field} is in {@code values}, {@code false} otherwise. If the
 * specified field is not applicable or if a value is out of range then the
 * predicate will return {@code false}./*from  w w  w  . j av  a  2s  . c om*/
 * 
 * @param field the field to check using each value in {@code values} . Must
 *        be non {@code null}.
 * @param values the values to check supplied fixed schedules against. Must be
 *        non {@code null}, must contain one or more elements, and each
 *        element must be >= 0.
 * @return a predicate for determining whether or not to keep instances of
 *         {@link FixedSchedule}. Never {@code null}.
 */
static Predicate<ChronoFixedSchedule> limiter(final TemporalField field, final ImmutableSet<Integer> values) {
    Preconditions.checkNotNull(field, "field required");
    Preconditions.checkNotNull(values, "values required");
    Preconditions.checkArgument(!values.isEmpty(), "values must be non empty");
    for (Integer value : values)
        Preconditions.checkArgument(value >= 0, "each values element must be non negative");

    return new Predicate<ChronoFixedSchedule>() {
        @Override
        public boolean apply(final ChronoFixedSchedule input) {
            Preconditions.checkNotNull(input, "input required");

            Temporal partial = null;
            ValueRange range = null;

            if (input.getStartDate() != null) {
                partial = input.getStartDate();

                if (!partial.isSupported(field))
                    return false;

                range = input.getStartDate().range(field);
            } else if (input.getZonedStartDateTime() != null) {
                partial = input.getZonedStartDateTime().toLocalDateTime();

                if (!partial.isSupported(field))
                    return false;

                range = input.getZonedStartDateTime().range(field);
            } else {
                throw new IllegalStateException("no start date or zoned start date-time");
            }

            for (Long value : Iterables.transform(values, (value) -> value.longValue())) {
                if (!range.isValidValue(value))
                    continue;

                if (partial.get(field) == value)
                    return true;
            }

            return false;
        }
    };
}

From source file:com.facebook.buck.android.CopyNativeLibraries.java

public static void copyNativeLibrary(final ProjectFilesystem filesystem, Path sourceDir,
        final Path destinationDir, ImmutableSet<TargetCpuType> cpuFilters, ImmutableList.Builder<Step> steps) {

    if (cpuFilters.isEmpty()) {
        steps.add(CopyStep.forDirectory(filesystem, sourceDir, destinationDir,
                CopyStep.DirectoryMode.CONTENTS_ONLY));
    } else {/*from  w  ww.  ja v  a 2  s. c  o  m*/
        for (TargetCpuType cpuType : cpuFilters) {
            Optional<String> abiDirectoryComponent = getAbiDirectoryComponent(cpuType);
            Preconditions.checkState(abiDirectoryComponent.isPresent());

            final Path libSourceDir = sourceDir.resolve(abiDirectoryComponent.get());
            Path libDestinationDir = destinationDir.resolve(abiDirectoryComponent.get());

            final MkdirStep mkDirStep = new MkdirStep(filesystem, libDestinationDir);
            final CopyStep copyStep = CopyStep.forDirectory(filesystem, libSourceDir, libDestinationDir,
                    CopyStep.DirectoryMode.CONTENTS_ONLY);
            steps.add(new Step() {
                @Override
                public StepExecutionResult execute(ExecutionContext context) {
                    // TODO(shs96c): Using a projectfilesystem here is almost definitely wrong.
                    // This is because each library may come from different build rules, which may be in
                    // different cells --- this check works by coincidence.
                    if (!filesystem.exists(libSourceDir)) {
                        return StepExecutionResult.SUCCESS;
                    }
                    if (mkDirStep.execute(context).isSuccess() && copyStep.execute(context).isSuccess()) {
                        return StepExecutionResult.SUCCESS;
                    }
                    return StepExecutionResult.ERROR;
                }

                @Override
                public String getShortName() {
                    return "copy_native_libraries";
                }

                @Override
                public String getDescription(ExecutionContext context) {
                    ImmutableList.Builder<String> stringBuilder = ImmutableList.builder();
                    stringBuilder.add(String.format("[ -d %s ]", libSourceDir.toString()));
                    stringBuilder.add(mkDirStep.getDescription(context));
                    stringBuilder.add(copyStep.getDescription(context));
                    return Joiner.on(" && ").join(stringBuilder.build());
                }
            });
        }
    }

    // Rename native files named like "*-disguised-exe" to "lib*.so" so they will be unpacked
    // by the Android package installer.  Then they can be executed like normal binaries
    // on the device.
    steps.add(new AbstractExecutionStep("rename_native_executables") {
        @Override
        public StepExecutionResult execute(ExecutionContext context) {
            final ImmutableSet.Builder<Path> executablesBuilder = ImmutableSet.builder();
            try {
                filesystem.walkRelativeFileTree(destinationDir, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        if (file.toString().endsWith("-disguised-exe")) {
                            executablesBuilder.add(file);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
                for (Path exePath : executablesBuilder.build()) {
                    Path fakeSoPath = Paths.get(MorePaths.pathWithUnixSeparators(exePath)
                            .replaceAll("/([^/]+)-disguised-exe$", "/lib$1.so"));
                    filesystem.move(exePath, fakeSoPath);
                }
            } catch (IOException e) {
                context.logError(e, "Renaming native executables failed.");
                return StepExecutionResult.ERROR;
            }
            return StepExecutionResult.SUCCESS;
        }
    });
}

From source file:com.outerspacecat.icalendar.RecurrencePredicates.java

/**
 * Returns a predicate for determining whether or not to keep instances of
 * {@link FixedSchedule}. The returned predicate will return {@code true} for
 * a given {@link FixedSchedule} if the value of the field specified by
 * {@code field} is in {@code values}, {@code false} otherwise. If the
 * specified field is not applicable or if a value is out of range then the
 * predicate will return {@code false}./*from  www  .ja va2  s. c o  m*/
 * 
 * @param field the field to check using each value in {@code values} . Must
 *        be non {@code null}.
 * @param values the values to check supplied fixed schedules against. Must be
 *        non {@code null}, must contain one or more elements. Elements may be
 *        be negative, but must be non zero.
 * @return a predicate for determining whether or not to keep instances of
 *         {@link FixedSchedule}. Never {@code null}.
 */
static Predicate<ChronoFixedSchedule> signedLimiter(final TemporalField field,
        final ImmutableSet<Integer> values) {
    Preconditions.checkNotNull(field, "field required");
    Preconditions.checkNotNull(values, "values required");
    Preconditions.checkArgument(!values.isEmpty(), "values must be non empty");
    for (Integer value : values)
        Preconditions.checkArgument(value != 0, "each values element must be non zero");

    return new Predicate<ChronoFixedSchedule>() {
        @Override
        public boolean apply(final ChronoFixedSchedule input) {
            Preconditions.checkNotNull(input, "input required");

            Temporal partial = null;
            ValueRange range = null;

            if (input.getStartDate() != null) {
                partial = input.getStartDate();

                if (!partial.isSupported(field))
                    return true;

                range = input.getStartDate().range(field);
            } else if (input.getZonedStartDateTime() != null) {
                partial = input.getZonedStartDateTime().toLocalDateTime();

                if (!partial.isSupported(field))
                    return true;

                range = input.getZonedStartDateTime().range(field);
            } else {
                throw new IllegalStateException("no start date or zoned start date-time");
            }

            for (Long value : Iterables.transform(values, (value) -> value.longValue())) {
                if (value < 0)
                    value = range.getMaximum() + value + 1;

                if (!range.isValidValue(value))
                    continue;

                if (partial.get(field) == value)
                    return true;
            }

            return false;
        }
    };
}

From source file:com.facebook.buck.artifact_cache.ArtifactCaches.java

private static ArtifactCache newInstanceInternal(ArtifactCacheBuckConfig buckConfig, BuckEventBus buckEventBus,
        ProjectFilesystem projectFilesystem, Optional<String> wifiSsid,
        ListeningExecutorService httpWriteExecutorService, boolean distributedBuildModeEnabled) {
    ImmutableSet<ArtifactCacheBuckConfig.ArtifactCacheMode> modes = buckConfig.getArtifactCacheModes();
    if (modes.isEmpty()) {
        return new NoopArtifactCache();
    }/*from  www  .j a v  a2  s. c  o  m*/
    ImmutableList.Builder<ArtifactCache> builder = ImmutableList.builder();
    for (ArtifactCacheBuckConfig.ArtifactCacheMode mode : modes) {
        switch (mode) {
        case dir:
            builder.add(createDirArtifactCache(Optional.of(buckEventBus), buckConfig.getDirCache(),
                    projectFilesystem));
            break;
        case http:
            initializeDistributedCaches(buckConfig, buckEventBus, projectFilesystem, wifiSsid,
                    httpWriteExecutorService, builder, distributedBuildModeEnabled, HTTP_PROTOCOL);
            break;

        case thrift_over_http:
            initializeDistributedCaches(buckConfig, buckEventBus, projectFilesystem, wifiSsid,
                    httpWriteExecutorService, builder, distributedBuildModeEnabled, THRIFT_PROTOCOL);
            break;
        }
    }
    ImmutableList<ArtifactCache> artifactCaches = builder.build();
    ArtifactCache result;

    if (artifactCaches.size() == 1) {
        // Don't bother wrapping a single artifact cache in MultiArtifactCache.
        result = artifactCaches.get(0);
    } else {
        result = new MultiArtifactCache(artifactCaches);
    }

    // Always support reading two-level cache stores (in case we performed any in the past).
    result = new TwoLevelArtifactCacheDecorator(result, projectFilesystem, buckEventBus,
            buckConfig.getTwoLevelCachingEnabled(), buckConfig.getTwoLevelCachingMinimumSize(),
            buckConfig.getTwoLevelCachingMaximumSize());

    return result;
}

From source file:com.google.caliper.runner.instrument.InstrumentModule.java

@Provides
static ImmutableSet<InstrumentedMethod> provideInstrumentedMethods(CaliperOptions options,
        BenchmarkClassModel benchmarkClass, ImmutableSet<Instrument> instruments)
        throws InvalidBenchmarkException {
    ImmutableSet.Builder<InstrumentedMethod> builder = ImmutableSet.builder();
    ImmutableSet<String> benchmarkMethodNames = options.benchmarkMethodNames();
    Set<String> unusedBenchmarkNames = new HashSet<String>(benchmarkMethodNames);
    for (Instrument instrument : instruments) {
        for (MethodModel method : findAllBenchmarkMethods(benchmarkClass, instrument)) {
            if (benchmarkMethodNames.isEmpty() || benchmarkMethodNames.contains(method.name())) {
                builder.add(instrument.createInstrumentedMethod(method));
                unusedBenchmarkNames.remove(method.name());
            }/*from w  w w  .j a  v  a  2  s  .  c  om*/
        }
    }
    if (!unusedBenchmarkNames.isEmpty()) {
        throw new InvalidBenchmarkException("Invalid benchmark method(s) specified in options: %s",
                unusedBenchmarkNames);
    }
    return builder.build();
}

From source file:google.registry.rde.DomainResourceToXjcConverter.java

/** Converts {@link DomainResource} to {@link XjcRdeDomain}. */
static XjcRdeDomain convertDomain(DomainResource model, RdeMode mode) {
    XjcRdeDomain bean = new XjcRdeDomain();

    // o  A <name> element that contains the fully qualified name of the
    //    domain name object.
    bean.setName(model.getFullyQualifiedDomainName());

    // o  A <roid> element that contains the repository object identifier
    //    assigned to the domain name object when it was created.
    bean.setRoid(model.getRepoId());//  w w w  .j  a  v  a2 s  .  c  om

    // o  An OPTIONAL <uName> element that contains the name of the domain
    //    name in Unicode character set.  It MUST be provided if available.
    bean.setUName(Idn.toUnicode(model.getFullyQualifiedDomainName()));

    // o  An OPTIONAL <idnTableId> element that references the IDN Table
    //    used for the IDN.  This corresponds to the "id" attribute of the
    //    <idnTableRef> element.  This element MUST be present if the domain
    //    name is an IDN.
    //   We have to add some code to determine the IDN table id at creation
    //    time, then either save it somewhere, or else re-derive it here.
    bean.setIdnTableId(model.getIdnTableName());

    // o  An OPTIONAL <originalName> element is used to indicate that the
    //    domain name is an IDN variant.  This element contains the domain
    //    name used to generate the IDN variant.
    //   Not relevant for now. We may do some bundling of variants in the
    //    future, but right now we're going to be doing blocking - which
    //    means we won't canonicalize the IDN name at the present time.
    // bean.setOriginalName(...);

    // o  A <clID> element that contains the identifier of the sponsoring
    //    registrar.
    bean.setClID(model.getCurrentSponsorClientId());

    // o  A <crRr> element that contains the identifier of the registrar
    //    that created the domain name object.  An OPTIONAL client attribute
    //    is used to specify the client that performed the operation.
    bean.setCrRr(RdeAdapter.convertRr(model.getCreationClientId(), null));

    // o  An OPTIONAL <crDate> element that contains the date and time of
    //    the domain name object creation.  This element MUST be present if
    //    the domain name has been allocated.
    bean.setCrDate(model.getCreationTime());

    // o  An OPTIONAL <exDate> element that contains the date and time
    //    identifying the end (expiration) of the domain name object's
    //    registration period.  This element MUST be present if the domain
    //    name has been allocated.
    bean.setExDate(model.getRegistrationExpirationTime());

    // o  An OPTIONAL <upDate> element that contains the date and time of
    //    the most recent domain-name-object modification.  This element
    //    MUST NOT be present if the domain name object has never been
    //    modified.
    bean.setUpDate(model.getLastEppUpdateTime());

    // o  An OPTIONAL <upRr> element that contains the identifier of the
    //    registrar that last updated the domain name object.  This element
    //    MUST NOT be present if the domain has never been modified.  An
    //    OPTIONAL client attribute is used to specify the client that
    //    performed the operation.
    bean.setUpRr(RdeAdapter.convertRr(model.getLastEppUpdateClientId(), null));

    // o  An OPTIONAL <trDate> element that contains the date and time of
    //    the most recent domain object successful transfer.  This element
    //    MUST NOT be present if the domain name object has never been
    //    transfered.
    bean.setTrDate(model.getLastTransferTime());

    // o  One or more <status> elements that contain the current status
    //    descriptors associated with the domain name.
    for (StatusValue status : model.getStatusValues()) {
        bean.getStatuses().add(convertStatusValue(status));
    }

    // o  An OPTIONAL <ns> element that contains the fully qualified names
    //    of the delegated host objects or host attributes (name servers)
    //    associated with the domain name object.  See Section 1.1 of
    //    [RFC5731] for a description of the elements used to specify host
    //    objects or host attributes.
    //   We don't support host attributes, only host objects. The RFC says
    //    you have to support one or the other, but not both. The gist of
    //    it is that with host attributes, you inline the nameserver data
    //    on each domain; with host objects, you normalize the nameserver
    //    data to a separate EPP object.
    ImmutableSet<String> linkedNameserverHostNames = model.loadNameserverFullyQualifiedHostNames();
    if (!linkedNameserverHostNames.isEmpty()) {
        XjcDomainNsType nameservers = new XjcDomainNsType();
        for (String hostName : linkedNameserverHostNames) {
            nameservers.getHostObjs().add(hostName);
        }
        bean.setNs(nameservers);
    }

    switch (mode) {
    case FULL:
        // o  Zero or more OPTIONAL <rgpStatus> element to represent
        //    "pendingDelete" sub-statuses, including "redemptionPeriod",
        //    "pendingRestore", and "pendingDelete", that a domain name can be
        //    in as a result of grace period processing as specified in
        //    [RFC3915].
        for (GracePeriodStatus status : model.getGracePeriodStatuses()) {
            bean.getRgpStatuses().add(convertGracePeriodStatus(status));
        }

        // o  An OPTIONAL <registrant> element that contain the identifier for
        //    the human or organizational social information object associated
        //    as the holder of the domain name object.
        Key<ContactResource> registrant = model.getRegistrant();
        if (registrant != null) {
            bean.setRegistrant(ofy().load().key(registrant).now().getContactId());
        }

        // o  Zero or more OPTIONAL <contact> elements that contain identifiers
        //    for the human or organizational social information objects
        //    associated with the domain name object.
        for (DesignatedContact contact : model.getContacts()) {
            bean.getContacts().add(convertDesignatedContact(contact));
        }

        // o  An OPTIONAL <secDNS> element that contains the public key
        //    information associated with Domain Name System security (DNSSEC)
        //    extensions for the domain name as specified in [RFC5910].
        //   We don't set keyData because we use dsData. The RFCs offer us a
        //    choice between the two, similar to hostAttr vs. hostObj above.
        //   We're not going to support maxSigLife since it seems to be
        //    completely useless.
        if (!model.getDsData().isEmpty()) {
            XjcSecdnsDsOrKeyType secdns = new XjcSecdnsDsOrKeyType();
            for (DelegationSignerData ds : model.getDsData()) {
                secdns.getDsDatas().add(convertDelegationSignerData(ds));
            }
            bean.setSecDNS(secdns);
        }

        // o  An OPTIONAL <trnData> element that contains the following child
        //    elements related to the last transfer request of the domain name
        //    object.  This element MUST NOT be present if a transfer request
        //    for the domain name has never been created.
        //
        //    *  A <trStatus> element that contains the state of the most recent
        //       transfer request.
        //
        //    *  A <reRr> element that contains the identifier of the registrar
        //       that requested the domain name object transfer.  An OPTIONAL
        //       client attribute is used to specify the client that performed
        //       the operation.
        //
        //    *  A <reDate> element that contains the date and time that the
        //       transfer was requested.
        //
        //    *  An <acRr> element that contains the identifier of the registrar
        //       that SHOULD act upon a PENDING transfer request.  For all other
        //       status types, the value identifies the registrar that took the
        //       indicated action.  An OPTIONAL client attribute is used to
        //       specify the client that performed the operation.
        //
        //    *  An <acDate> element that contains the date and time of a
        //       required or completed response.  For a PENDING request, the
        //       value identifies the date and time by which a response is
        //       required before an automated response action will be taken by
        //       the registry.  For all other status types, the value identifies
        //       the date and time when the request was completed.
        //
        //    *  An OPTIONAL <exDate> element that contains the end of the
        //       domain name object's validity period (expiry date) if the
        //       transfer caused or causes a change in the validity period.
        if (model.getTransferData() != TransferData.EMPTY) {
            // Temporary check to make sure that there really was a transfer. A bug caused spurious
            // empty transfer records to get generated for deleted domains.
            // TODO(b/33289763): remove the hasGainingAndLosingRegistrars check in February 2017
            if (hasGainingAndLosingRegistrars(model)) {
                bean.setTrnData(
                        convertTransferData(model.getTransferData(), model.getRegistrationExpirationTime()));
            }
        }

        break;
    case THIN:
        break;
    }

    return bean;
}

From source file:com.facebook.buck.util.zip.Zip.java

/** Walks the file tree rooted in baseDirectory to create zip entries */
public static void walkBaseDirectoryToCreateEntries(ProjectFilesystem filesystem,
        Map<String, Pair<CustomZipEntry, Optional<Path>>> entries, Path baseDir, ImmutableSet<Path> paths,
        boolean junkPaths, ZipCompressionLevel compressionLevel) throws IOException {
    // Since filesystem traversals can be non-deterministic, sort the entries we find into
    // a tree map before writing them out.
    FileVisitor<Path> pathFileVisitor = new SimpleFileVisitor<Path>() {
        private boolean isSkipFile(Path file) {
            return !paths.isEmpty() && !paths.contains(file);
        }/*from  w w w  .  ja va 2 s. c om*/

        private String getEntryName(Path path) {
            Path relativePath = junkPaths ? path.getFileName() : baseDir.relativize(path);
            return MorePaths.pathWithUnixSeparators(relativePath);
        }

        private CustomZipEntry getZipEntry(String entryName, Path path, BasicFileAttributes attr)
                throws IOException {
            boolean isDirectory = filesystem.isDirectory(path);
            if (isDirectory) {
                entryName += "/";
            }

            CustomZipEntry entry = new CustomZipEntry(entryName);
            // We want deterministic ZIPs, so avoid mtimes.
            entry.setFakeTime();
            entry.setCompressionLevel(
                    isDirectory ? ZipCompressionLevel.NONE.getValue() : compressionLevel.getValue());
            // If we're using STORED files, we must manually set the CRC, size, and compressed size.
            if (entry.getMethod() == ZipEntry.STORED && !isDirectory) {
                entry.setSize(attr.size());
                entry.setCompressedSize(attr.size());
                entry.setCrc(new ByteSource() {
                    @Override
                    public InputStream openStream() throws IOException {
                        return filesystem.newFileInputStream(path);
                    }
                }.hash(Hashing.crc32()).padToLong());
            }

            long externalAttributes = filesystem.getFileAttributesForZipEntry(path);
            LOG.verbose("Setting mode for entry %s path %s to 0x%08X", entryName, path, externalAttributes);
            entry.setExternalAttributes(externalAttributes);
            return entry;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (!isSkipFile(file)) {
                CustomZipEntry entry = getZipEntry(getEntryName(file), file, attrs);
                entries.put(entry.getName(), new Pair<>(entry, Optional.of(file)));
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if (!dir.equals(baseDir) && !isSkipFile(dir)) {
                CustomZipEntry entry = getZipEntry(getEntryName(dir), dir, attrs);
                entries.put(entry.getName(), new Pair<>(entry, Optional.empty()));
            }
            return FileVisitResult.CONTINUE;
        }
    };
    filesystem.walkRelativeFileTree(baseDir, pathFileVisitor);
}

From source file:com.outerspacecat.icalendar.RecurrenceFunctions.java

/**
 * Returns a function for transforming instances of {@link FixedSchedule} into
 * zero or more instances. Used to apply BYDAY values to a YEARLY recurrence.
 * <p>//from w w  w  . ja  va 2s . c o m
 * May not work for all chronologies.
 * 
 * @param byDay the values to alter supplied fixed schedules with. Must be non
 *        {@code null} and must contain one or more elements.
 * @return a function for transforming instances of {@link FixedSchedule} into
 *         zero or more instances. Never {@code null}.
 */
static Function<ChronoFixedSchedule, List<ChronoFixedSchedule>> yearlyByDayExpander(
        final ImmutableSet<DayOfWeekOccurrence> byDay) {
    Preconditions.checkNotNull(byDay, "byDay required");
    Preconditions.checkArgument(!byDay.isEmpty(), "byDay must be non empty");

    return new Function<ChronoFixedSchedule, List<ChronoFixedSchedule>>() {
        @Override
        public List<ChronoFixedSchedule> apply(final ChronoFixedSchedule obj) {
            Preconditions.checkNotNull(obj, "obj required");

            List<ChronoFixedSchedule> ret = new ArrayList<ChronoFixedSchedule>();

            int daysInYear = (int) (obj.getDateOfStart().range(ChronoField.DAY_OF_YEAR).getMaximum());

            for (int dayOfYear = 1; dayOfYear <= daysInYear; ++dayOfYear) {
                ChronoLocalDate adjustedStart = obj.getDateOfStart().with(ChronoField.DAY_OF_YEAR, dayOfYear);

                DayOfWeek dayOfWeek = DayOfWeek.of(adjustedStart.get(ChronoField.DAY_OF_WEEK));

                int numericPrefix = dayOfYear / 7 + (dayOfYear % 7 == 0 ? 0 : 1);

                int dayOfWeekOccurrencesInYear = (int) (numericPrefix + ((daysInYear - dayOfYear) / 7));

                if (byDay.contains(new DayOfWeekOccurrence(Optional.absent(), dayOfWeek))
                        || byDay.contains(
                                new DayOfWeekOccurrence(Optional.fromNullable(numericPrefix), dayOfWeek))
                        || byDay.contains(new DayOfWeekOccurrence(
                                Optional.fromNullable(numericPrefix - dayOfWeekOccurrencesInYear - 1),
                                dayOfWeek)))
                    ret.add(obj.adjustDateOfStart(adjustedStart));
            }

            return ret;
        }
    };
}

From source file:com.outerspacecat.icalendar.RecurrenceFunctions.java

/**
 * Returns a function for transforming instances of {@link FixedSchedule} into
 * zero or more instances. Used to apply BYDAY values to a MONTHLY recurrence.
 * <p>//  w w w  .j a  va 2  s .  co m
 * May not work for all chronologies.
 * 
 * @param byDay the values to alter supplied fixed schedules with. Must be non
 *        {@code null} and must contain one or more elements.
 * @return a function for transforming instances of {@link FixedSchedule} into
 *         zero or more instances. Never {@code null}.
 */
static Function<ChronoFixedSchedule, List<ChronoFixedSchedule>> monthlyByDayExpander(
        final ImmutableSet<DayOfWeekOccurrence> byDay) {
    Preconditions.checkNotNull(byDay, "byDay required");
    Preconditions.checkArgument(!byDay.isEmpty(), "byDay must be non empty");

    return new Function<ChronoFixedSchedule, List<ChronoFixedSchedule>>() {
        @Override
        public List<ChronoFixedSchedule> apply(final ChronoFixedSchedule obj) {
            Preconditions.checkNotNull(obj, "obj required");

            List<ChronoFixedSchedule> ret = new ArrayList<ChronoFixedSchedule>();

            long daysInMonth = obj.getDateOfStart().range(ChronoField.DAY_OF_MONTH).getMaximum();

            for (int dayOfMonth = 1; dayOfMonth <= daysInMonth; ++dayOfMonth) {
                ChronoLocalDate adjustedStart = obj.getDateOfStart().with(ChronoField.DAY_OF_MONTH, dayOfMonth);

                DayOfWeek dayOfWeek = DayOfWeek.of(adjustedStart.get(ChronoField.DAY_OF_WEEK));

                int numericPrefix = dayOfMonth / 7 + (dayOfMonth % 7 == 0 ? 0 : 1);

                int dayOfWeekOccurrencesInMonth = (int) (numericPrefix + ((daysInMonth - dayOfMonth) / 7));

                if (byDay.contains(new DayOfWeekOccurrence(Optional.absent(), dayOfWeek))
                        || byDay.contains(
                                new DayOfWeekOccurrence(Optional.fromNullable(numericPrefix), dayOfWeek))
                        || byDay.contains(new DayOfWeekOccurrence(
                                Optional.fromNullable(numericPrefix - dayOfWeekOccurrencesInMonth - 1),
                                dayOfWeek)))
                    ret.add(obj.adjustDateOfStart(adjustedStart));

            }

            return ret;
        }
    };
}