Search in sources :

Example 71 with Objects

use of java.util.Objects in project cas by apereo.

the class SamlRegisteredServiceMetadataResolverCacheLoader method load.

@Override
@Synchronized
@SneakyThrows
public ChainingMetadataResolver load(final SamlRegisteredService service) {
    final ChainingMetadataResolver metadataResolver = new ChainingMetadataResolver();
    final List<MetadataResolver> metadataResolvers = new ArrayList<>();
    final Collection<SamlRegisteredServiceMetadataResolver> availableResolvers = this.metadataResolutionPlan.getRegisteredMetadataResolvers();
    availableResolvers.stream().filter(Objects::nonNull).filter(r -> r.supports(service)).map(r -> r.resolve(service)).forEach(metadataResolvers::addAll);
    if (metadataResolvers.isEmpty()) {
        throw new SamlException("No metadata resolvers could be configured for service " + service.getName() + " with metadata location " + service.getMetadataLocation());
    }
    metadataResolver.setId(ChainingMetadataResolver.class.getCanonicalName());
    metadataResolver.setResolvers(metadataResolvers);
    metadataResolver.initialize();
    LOGGER.debug("Metadata resolvers active for this request are [{}]", metadataResolver);
    return metadataResolver;
}
Also used : Synchronized(lombok.Synchronized) CacheLoader(com.github.benmanes.caffeine.cache.CacheLoader) SneakyThrows(lombok.SneakyThrows) HttpClient(org.apereo.cas.util.http.HttpClient) Collection(java.util.Collection) SamlRegisteredServiceMetadataResolutionPlan(org.apereo.cas.support.saml.services.idp.metadata.plan.SamlRegisteredServiceMetadataResolutionPlan) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) ArrayList(java.util.ArrayList) OpenSamlConfigBean(org.apereo.cas.support.saml.OpenSamlConfigBean) SamlRegisteredServiceMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.resolver.SamlRegisteredServiceMetadataResolver) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) SamlException(org.apereo.cas.support.saml.SamlException) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) AllArgsConstructor(lombok.AllArgsConstructor) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) SamlRegisteredServiceMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.resolver.SamlRegisteredServiceMetadataResolver) ArrayList(java.util.ArrayList) SamlException(org.apereo.cas.support.saml.SamlException) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) SamlRegisteredServiceMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.resolver.SamlRegisteredServiceMetadataResolver) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) Synchronized(lombok.Synchronized) SneakyThrows(lombok.SneakyThrows)

Example 72 with Objects

use of java.util.Objects in project cas by apereo.

the class CasServerProfileRegistrar method locateSubtypesByReflection.

private Object locateSubtypesByReflection(final Function<Class, Object> mapper, final Collector collector, final Class parentType, final Predicate filter, final String packageNamespace) {
    final Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(packageNamespace)).setScanners(new SubTypesScanner(false)));
    final Set<Class<?>> subTypes = (Set) reflections.getSubTypesOf(parentType);
    return subTypes.stream().filter(c -> !Modifier.isInterface(c.getModifiers()) && !Modifier.isAbstract(c.getModifiers()) && filter.test(c)).map(mapper).filter(Objects::nonNull).collect(collector);
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) Setter(lombok.Setter) RequiredArgsConstructor(lombok.RequiredArgsConstructor) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) Reflections(org.reflections.Reflections) Function(java.util.function.Function) AbstractRegisteredService(org.apereo.cas.services.AbstractRegisteredService) Pair(org.apache.commons.lang3.tuple.Pair) Clients(org.pac4j.core.client.Clients) Client(org.pac4j.core.client.Client) Map(java.util.Map) Predicates(com.google.common.base.Predicates) Collector(java.util.stream.Collector) MultifactorAuthenticationUtils(org.apereo.cas.authentication.MultifactorAuthenticationUtils) IndirectClient(org.pac4j.core.client.IndirectClient) VariegatedMultifactorAuthenticationProvider(org.apereo.cas.services.VariegatedMultifactorAuthenticationProvider) ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) LinkedHashSet(java.util.LinkedHashSet) ServicesManager(org.apereo.cas.services.ServicesManager) MultifactorAuthenticationProvider(org.apereo.cas.services.MultifactorAuthenticationProvider) Predicate(java.util.function.Predicate) Set(java.util.Set) ApplicationContext(org.springframework.context.ApplicationContext) Collectors(java.util.stream.Collectors) AbstractMultifactorAuthenticationProvider(org.apereo.cas.authentication.AbstractMultifactorAuthenticationProvider) RegisteredService(org.apereo.cas.services.RegisteredService) ClasspathHelper(org.reflections.util.ClasspathHelper) SubTypesScanner(org.reflections.scanners.SubTypesScanner) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) Modifier(java.lang.reflect.Modifier) ApplicationContextAware(org.springframework.context.ApplicationContextAware) ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) SubTypesScanner(org.reflections.scanners.SubTypesScanner) Reflections(org.reflections.Reflections)

Example 73 with Objects

use of java.util.Objects in project MantaroBot by Mantaro.

the class MantaroShard method updateStatus.

/**
 * Updates Mantaro's "splash".
 * Splashes are random gags like "now seen in theaters!" that show on Mantaro's status.
 * This has been on Mantaro since 2016, so it's part of its "personality" as a bot.
 */
public void updateStatus() {
    Runnable changeStatus = () -> {
        // insert $CURRENT_YEAR meme here
        if (DateUtils.isSameDay(christmas, Calendar.getInstance())) {
            getJDA().getPresence().setGame(Game.playing(String.format("%shelp | %s | [%d]", config().get().prefix[0], "Merry Christmas!", getId())));
            return;
        } else if (DateUtils.isSameDay(newYear, Calendar.getInstance())) {
            getJDA().getPresence().setGame(Game.playing(String.format("%shelp | %s | [%d]", config().get().prefix[0], "Happy New Year!", getId())));
            return;
        }
        AtomicInteger users = new AtomicInteger(0), guilds = new AtomicInteger(0);
        if (MantaroBot.getInstance() != null) {
            Arrays.stream(MantaroBot.getInstance().getShardedMantaro().getShards()).filter(Objects::nonNull).map(MantaroShard::getJDA).forEach(jda -> {
                users.addAndGet((int) jda.getUserCache().size());
                guilds.addAndGet((int) jda.getGuildCache().size());
            });
        }
        String newStatus = new JSONObject(Utils.wgetResty(config.apiTwoUrl + "/mantaroapi/splashes/random", null)).getString("splash").replace("%ramgb%", String.valueOf(((long) (Runtime.getRuntime().maxMemory() * 1.2D)) >> 30L)).replace("%usercount%", users.toString()).replace("%guildcount%", guilds.toString()).replace("%shardcount%", String.valueOf(getTotalShards())).replace("%prettyusercount%", pretty(users.get())).replace("%prettyguildcount%", pretty(guilds.get()));
        getJDA().getPresence().setGame(Game.playing(String.format("%shelp | %s | [%d]", config().get().prefix[0], newStatus, getId())));
        log.debug("Changed status to: " + newStatus);
    };
    changeStatus.run();
    Async.task("Splash Thread", changeStatus, 10, TimeUnit.MINUTES);
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) LoginException(javax.security.auth.login.LoginException) Arrays(java.util.Arrays) Getter(lombok.Getter) Async(br.com.brjdevs.java.utils.async.Async) Utils(net.kodehawa.mantarobot.utils.Utils) LoggerFactory(org.slf4j.LoggerFactory) VoiceChannelListener(net.kodehawa.mantarobot.commands.music.listener.VoiceChannelListener) ICommandProcessor(net.kodehawa.mantarobot.core.processor.core.ICommandProcessor) MantaroBot(net.kodehawa.mantarobot.MantaroBot) RateLimitedException(net.dv8tion.jda.core.exceptions.RateLimitedException) JSONObject(org.json.JSONObject) Calendar(java.util.Calendar) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JDA(net.dv8tion.jda.core.JDA) Delegate(lombok.experimental.Delegate) Config(net.kodehawa.mantarobot.data.Config) CommandListener(net.kodehawa.mantarobot.core.listeners.command.CommandListener) MantaroData.config(net.kodehawa.mantarobot.data.MantaroData.config) Logger(org.slf4j.Logger) Utils.pretty(net.kodehawa.mantarobot.utils.Utils.pretty) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) BirthdayTask(net.kodehawa.mantarobot.commands.utils.birthday.BirthdayTask) java.util.concurrent(java.util.concurrent) Game(net.dv8tion.jda.core.entities.Game) JDABuilder(net.dv8tion.jda.core.JDABuilder) SessionController(net.dv8tion.jda.core.utils.SessionController) MantaroListener(net.kodehawa.mantarobot.core.listeners.MantaroListener) AccountType(net.dv8tion.jda.core.AccountType) ReactionOperations(net.kodehawa.mantarobot.core.listeners.operations.ReactionOperations) DateUtils(org.apache.commons.lang3.time.DateUtils) MantaroEventManager(net.kodehawa.mantarobot.core.MantaroEventManager) Objects(java.util.Objects) SessionControllerAdapter(net.dv8tion.jda.core.utils.SessionControllerAdapter) MantaroData(net.kodehawa.mantarobot.data.MantaroData) NativeAudioSendFactory(com.sedmelluq.discord.lavaplayer.jdaudp.NativeAudioSendFactory) JSONObject(org.json.JSONObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 74 with Objects

use of java.util.Objects in project cas by apereo.

the class BaseResourceU2FDeviceRepository method getRegisteredDevices.

@Override
public Collection<DeviceRegistration> getRegisteredDevices(final String username) {
    try {
        final Map<String, List<U2FDeviceRegistration>> devices = readDevicesFromResource();
        if (!devices.isEmpty()) {
            final List<U2FDeviceRegistration> devs = devices.get(MAP_KEY_SERVICES);
            final LocalDate expirationDate = LocalDate.now().minus(this.expirationTime, DateTimeUtils.toChronoUnit(this.expirationTimeUnit));
            LOGGER.debug("Filtering devices for [{}] based on device expiration date [{}]", username, expirationDate);
            final List<U2FDeviceRegistration> list = devs.stream().filter(d -> d.getUsername().equals(username) && (d.getCreatedDate().isAfter(expirationDate))).collect(Collectors.toList());
            LOGGER.debug("There are [{}] device(s) remaining in repository for [{}]", list.size(), username);
            return list.stream().map(r -> {
                try {
                    return DeviceRegistration.fromJson(r.getRecord());
                } catch (final Exception e) {
                    LOGGER.error(e.getMessage(), e);
                }
                return null;
            }).filter(Objects::nonNull).collect(Collectors.toList());
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return new ArrayList<>(0);
}
Also used : LoadingCache(com.github.benmanes.caffeine.cache.LoadingCache) SneakyThrows(lombok.SneakyThrows) DateTimeUtils(org.apereo.cas.util.DateTimeUtils) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) DeviceRegistration(com.yubico.u2f.data.DeviceRegistration) ArrayList(java.util.ArrayList) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) AuthenticationFailedException(javax.mail.AuthenticationFailedException) LocalDate(java.time.LocalDate) Map(java.util.Map) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) LocalDate(java.time.LocalDate) AuthenticationFailedException(javax.mail.AuthenticationFailedException)

Example 75 with Objects

use of java.util.Objects in project AgriCraft by AgriCraft.

the class MutateStrategy method executeStrategy.

@Override
public Optional<AgriSeed> executeStrategy(IAgriCrop crop, Random rand) {
    // Validate the parameters.
    Objects.requireNonNull(crop, "You cannot execute a mutation on a null crop!");
    Objects.requireNonNull(rand, "The random passed to a mutation strategy should not be null!");
    // Fetch all neighboring crop instances.
    final List<IAgriCrop> neighbors = WorldHelper.getTileNeighbors(crop.getCropWorld(), crop.getCropPos(), IAgriCrop.class);
    // Determine all possible parents.
    final List<IAgriPlant> parents = neighbors.stream().filter(IAgriCrop::isMature).map(IAgriCrop::getSeed).filter(Objects::nonNull).map(AgriSeed::getPlant).collect(Collectors.toList());
    // If we have less than two parents, might as well as abort.
    if (parents.size() < 2) {
        return Optional.empty();
    }
    // Determine the list of possible cross-over mutations.
    final List<IAgriMutation> mutations = AgriApi.getMutationRegistry().stream().filter(m -> m.areParentsIn(parents)).filter(m -> crop.isFertile(m.getChild())).collect(Collectors.toList());
    // If we didn't find any valid mutations, might as well as abort.
    if (mutations.isEmpty()) {
        return Optional.empty();
    }
    // Choose a random index in the list.
    final int index = rand.nextInt(mutations.size());
    // Fetch the chosen mutation from the list.
    final IAgriMutation mutation = mutations.get(index);
    // Determine if we should actually go through with this.
    if (mutation.getChance() <= rand.nextDouble()) {
        return Optional.empty();
    }
    // Calculate the stat associated with the new plant.
    Optional<IAgriStat> stat = AgriApi.getStatCalculatorRegistry().valueOf(mutation.getChild()).map(c -> c.calculateMutationStats(mutation, neighbors));
    // Return the mutation result.
    return stat.map(s -> new AgriSeed(mutation.getChild(), s));
}
Also used : IAgriPlant(com.infinityraider.agricraft.api.v1.plant.IAgriPlant) IAgriCrop(com.infinityraider.agricraft.api.v1.crop.IAgriCrop) IAgriCrossStrategy(com.infinityraider.agricraft.api.v1.mutation.IAgriCrossStrategy) AgriApi(com.infinityraider.agricraft.api.v1.AgriApi) Random(java.util.Random) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) AgriCraftConfig(com.infinityraider.agricraft.reference.AgriCraftConfig) AgriSeed(com.infinityraider.agricraft.api.v1.seed.AgriSeed) IAgriMutation(com.infinityraider.agricraft.api.v1.mutation.IAgriMutation) WorldHelper(com.infinityraider.infinitylib.utility.WorldHelper) Optional(java.util.Optional) IAgriStat(com.infinityraider.agricraft.api.v1.stat.IAgriStat) IAgriPlant(com.infinityraider.agricraft.api.v1.plant.IAgriPlant) IAgriStat(com.infinityraider.agricraft.api.v1.stat.IAgriStat) IAgriCrop(com.infinityraider.agricraft.api.v1.crop.IAgriCrop) Objects(java.util.Objects) IAgriMutation(com.infinityraider.agricraft.api.v1.mutation.IAgriMutation) AgriSeed(com.infinityraider.agricraft.api.v1.seed.AgriSeed)

Aggregations

Objects (java.util.Objects)83 List (java.util.List)45 Map (java.util.Map)37 Collectors (java.util.stream.Collectors)32 ArrayList (java.util.ArrayList)30 Set (java.util.Set)30 IOException (java.io.IOException)22 HashMap (java.util.HashMap)21 Optional (java.util.Optional)19 Collections (java.util.Collections)18 LoggerFactory (org.slf4j.LoggerFactory)17 Stream (java.util.stream.Stream)16 Logger (org.slf4j.Logger)16 HashSet (java.util.HashSet)14 Collection (java.util.Collection)13 InputStream (java.io.InputStream)12 ImmutableSet (com.google.common.collect.ImmutableSet)10 Result (ddf.catalog.data.Result)9 TimeUnit (java.util.concurrent.TimeUnit)9 Metacard (ddf.catalog.data.Metacard)8