Example usage for com.google.common.collect Iterables getFirst

List of usage examples for com.google.common.collect Iterables getFirst

Introduction

In this page you can find the example usage for com.google.common.collect Iterables getFirst.

Prototype

@Nullable
public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) 

Source Link

Document

Returns the first element in iterable or defaultValue if the iterable is empty.

Usage

From source file:me.lucko.luckperms.common.commands.impl.user.UserDemote.java

@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List<String> args, String label)
        throws CommandException {
    if (ArgumentPermissions.checkModifyPerms(plugin, sender, getPermission().get(), user)) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return CommandResult.NO_PERMISSION;
    }/*from  w  w  w  .  j av a 2 s  .c  om*/

    final String trackName = args.get(0).toLowerCase();
    if (!DataConstraints.TRACK_NAME_TEST.test(trackName)) {
        Message.TRACK_INVALID_ENTRY.send(sender, trackName);
        return CommandResult.INVALID_ARGS;
    }

    if (!plugin.getStorage().loadTrack(trackName).join()) {
        Message.DOES_NOT_EXIST.send(sender, trackName);
        return CommandResult.INVALID_ARGS;
    }

    Track track = plugin.getTrackManager().getIfLoaded(trackName);
    if (track == null) {
        Message.DOES_NOT_EXIST.send(sender, trackName);
        return CommandResult.LOADING_ERROR;
    }

    if (track.getSize() <= 1) {
        Message.TRACK_EMPTY.send(sender, track.getName());
        return CommandResult.STATE_ERROR;
    }

    boolean silent = args.remove("-s");
    MutableContextSet context = ArgumentUtils.handleContext(1, args, plugin);

    if (ArgumentPermissions.checkContext(plugin, sender, getPermission().get(), context)) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return CommandResult.NO_PERMISSION;
    }

    // Load applicable groups
    Set<Node> nodes = user.getEnduringNodes().values().stream().filter(Node::isGroupNode)
            .filter(Node::getValuePrimitive)
            .filter(node -> node.getFullContexts().makeImmutable().equals(context.makeImmutable()))
            .collect(Collectors.toSet());

    nodes.removeIf(g -> !track.containsGroup(g.getGroupName()));

    if (nodes.isEmpty()) {
        Message.USER_TRACK_ERROR_NOT_CONTAIN_GROUP.send(sender, user.getFriendlyName(), track.getName());
        return CommandResult.FAILURE;
    }

    if (nodes.size() != 1) {
        Message.TRACK_AMBIGUOUS_CALL.send(sender, user.getFriendlyName());
        return CommandResult.FAILURE;
    }

    final Node oldNode = Iterables.getFirst(nodes, null);
    final String old = oldNode.getGroupName();
    final String previous;
    try {
        previous = track.getPrevious(old);
    } catch (IllegalArgumentException e) {
        Message.TRACK_DOES_NOT_CONTAIN.send(sender, track.getName(), old);
        return CommandResult.STATE_ERROR;
    }

    if (ArgumentPermissions.checkArguments(plugin, sender, getPermission().get(), track.getName(),
            oldNode.getGroupName())) {
        Message.COMMAND_NO_PERMISSION.send(sender);
        return CommandResult.NO_PERMISSION;
    }

    if (previous == null) {
        user.unsetPermission(oldNode);
        Message.USER_DEMOTE_ENDOFTRACK.send(sender, track.getName(), user.getFriendlyName(), old);

        ExtendedLogEntry.build().actor(sender).acted(user).action("demote", track.getName(), context).build()
                .submit(plugin, sender);

        save(user, sender, plugin);
        plugin.getApiProvider().getEventFactory().handleUserDemote(user, track, old, null);
        return CommandResult.SUCCESS;
    }

    if (!plugin.getStorage().loadGroup(previous).join()) {
        Message.USER_DEMOTE_ERROR_MALFORMED.send(sender, previous);
        return CommandResult.STATE_ERROR;
    }

    Group previousGroup = plugin.getGroupManager().getIfLoaded(previous);
    if (previousGroup == null) {
        Message.USER_DEMOTE_ERROR_MALFORMED.send(sender, previous);
        return CommandResult.LOADING_ERROR;
    }

    user.unsetPermission(oldNode);
    user.setPermission(
            NodeFactory.newBuilder("group." + previousGroup.getName()).withExtraContext(context).build());

    if (context.isEmpty() && user.getPrimaryGroup().getStoredValue().orElse("default").equalsIgnoreCase(old)) {
        user.getPrimaryGroup().setStoredValue(previousGroup.getName());
    }

    Message.USER_DEMOTE_SUCCESS.send(sender, track.getName(), old, previousGroup.getFriendlyName(),
            CommandUtils.contextSetToString(context));
    if (!silent) {
        Message.EMPTY.send(sender,
                CommandUtils.listToArrowSep(track.getGroups(), previousGroup.getFriendlyName(), old, true));
    }

    ExtendedLogEntry.build().actor(sender).acted(user).action("demote", track.getName(), context).build()
            .submit(plugin, sender);

    save(user, sender, plugin);
    plugin.getApiProvider().getEventFactory().handleUserDemote(user, track, old, previousGroup.getName());
    return CommandResult.SUCCESS;
}

From source file:com.synflow.models.util.EcoreHelper.java

/**
 * Loads the resource that corresponds to the given file, and returns the first object in its
 * contents that matches the given class, or <code>null</code> otherwise.
 * //from   www  .  j  a  v a  2  s . com
 * @param set
 *            a resource set
 * @param file
 *            a file whose extension is registered within EMF
 * @param cls
 *            a class
 * @return an EObject matching the given class, or <code>null</code>
 */
public static <T extends EObject> T getEObject(ResourceSet set, IFile file, Class<T> cls) {
    return Iterables.getFirst(getEObjects(set, file, cls), null);
}

From source file:fr.aliacom.obm.common.user.UserEmails.java

public String getPrimaryAddress() {
    return Iterables.getFirst(addresses, null);
}

From source file:com.kolich.blog.components.cache.EntryShadowCache.java

/**
 * Returns all cached content that was committed to the repo before (older, prior to) the given
 * commit, not including the commit itself.
 *//*from ww w. jav  a 2 s.co  m*/
public synchronized final PagedContent<Entry> getAllBefore(@Nullable final String commit,
        @Nullable final Integer limit) {
    final PagedContent<Entry> result;
    final Collection<Entry> shadow = shadowCache_.get(commit);
    final String firstCommit = Iterables.getFirst(shadowCache_.keySet(), null);
    if (shadow.isEmpty()) {
        result = new PagedContent<>(ImmutableList.of(), firstCommit, shadowCache_.keySet().size());
    } else {
        final List<Entry> before = ImmutableList.copyOf(shadow);
        final int endIndex = (limit != null && limit > 0 && limit <= before.size()) ? limit : before.size();
        final List<Entry> sublist = before.subList(0, endIndex);
        result = new PagedContent<>(sublist, firstCommit, before.size() - sublist.size());
    }
    return result;
}

From source file:org.apache.beam.runners.flink.translation.functions.FlinkPartialReduceFunction.java

@Override
public void combine(Iterable<WindowedValue<KV<K, InputT>>> elements,
        Collector<WindowedValue<KV<K, AccumT>>> out) throws Exception {

    PipelineOptions options = serializedOptions.getPipelineOptions();

    FlinkSideInputReader sideInputReader = new FlinkSideInputReader(sideInputs, getRuntimeContext());

    PerKeyCombineFnRunner<K, InputT, AccumT, ?> combineFnRunner = PerKeyCombineFnRunners.create(combineFn);

    @SuppressWarnings("unchecked")
    OutputTimeFn<? super BoundedWindow> outputTimeFn = (OutputTimeFn<? super BoundedWindow>) windowingStrategy
            .getOutputTimeFn();//www .  j av a  2  s .co m

    // get all elements so that we can sort them, has to fit into
    // memory
    // this seems very unprudent, but correct, for now
    ArrayList<WindowedValue<KV<K, InputT>>> sortedInput = Lists.newArrayList();
    for (WindowedValue<KV<K, InputT>> inputValue : elements) {
        for (WindowedValue<KV<K, InputT>> exploded : inputValue.explodeWindows()) {
            sortedInput.add(exploded);
        }
    }
    Collections.sort(sortedInput, new Comparator<WindowedValue<KV<K, InputT>>>() {
        @Override
        public int compare(WindowedValue<KV<K, InputT>> o1, WindowedValue<KV<K, InputT>> o2) {
            return Iterables.getOnlyElement(o1.getWindows()).maxTimestamp()
                    .compareTo(Iterables.getOnlyElement(o2.getWindows()).maxTimestamp());
        }
    });

    // iterate over the elements that are sorted by window timestamp
    //
    final Iterator<WindowedValue<KV<K, InputT>>> iterator = sortedInput.iterator();

    // create accumulator using the first elements key
    WindowedValue<KV<K, InputT>> currentValue = iterator.next();
    K key = currentValue.getValue().getKey();
    BoundedWindow currentWindow = Iterables.getFirst(currentValue.getWindows(), null);
    InputT firstValue = currentValue.getValue().getValue();
    AccumT accumulator = combineFnRunner.createAccumulator(key, options, sideInputReader,
            currentValue.getWindows());
    accumulator = combineFnRunner.addInput(key, accumulator, firstValue, options, sideInputReader,
            currentValue.getWindows());

    // we use this to keep track of the timestamps assigned by the OutputTimeFn
    Instant windowTimestamp = outputTimeFn.assignOutputTime(currentValue.getTimestamp(), currentWindow);

    while (iterator.hasNext()) {
        WindowedValue<KV<K, InputT>> nextValue = iterator.next();
        BoundedWindow nextWindow = Iterables.getOnlyElement(nextValue.getWindows());

        if (nextWindow.equals(currentWindow)) {
            // continue accumulating
            InputT value = nextValue.getValue().getValue();
            accumulator = combineFnRunner.addInput(key, accumulator, value, options, sideInputReader,
                    currentValue.getWindows());

            windowTimestamp = outputTimeFn.combine(windowTimestamp,
                    outputTimeFn.assignOutputTime(nextValue.getTimestamp(), currentWindow));

        } else {
            // emit the value that we currently have
            out.collect(WindowedValue.of(KV.of(key, accumulator), windowTimestamp, currentWindow,
                    PaneInfo.NO_FIRING));

            currentWindow = nextWindow;
            currentValue = nextValue;
            InputT value = nextValue.getValue().getValue();
            accumulator = combineFnRunner.createAccumulator(key, options, sideInputReader,
                    currentValue.getWindows());
            accumulator = combineFnRunner.addInput(key, accumulator, value, options, sideInputReader,
                    currentValue.getWindows());
            windowTimestamp = outputTimeFn.assignOutputTime(nextValue.getTimestamp(), currentWindow);
        }
    }

    // emit the final accumulator
    out.collect(WindowedValue.of(KV.of(key, accumulator), windowTimestamp, currentWindow, PaneInfo.NO_FIRING));
}

From source file:org.apache.beam.runners.flink.translation.functions.FlinkReduceFunction.java

@Override
public void reduce(Iterable<WindowedValue<KV<K, AccumT>>> elements,
        Collector<WindowedValue<KV<K, OutputT>>> out) throws Exception {

    PipelineOptions options = serializedOptions.getPipelineOptions();

    FlinkSideInputReader sideInputReader = new FlinkSideInputReader(sideInputs, getRuntimeContext());

    PerKeyCombineFnRunner<K, ?, AccumT, OutputT> combineFnRunner = PerKeyCombineFnRunners.create(combineFn);

    @SuppressWarnings("unchecked")
    OutputTimeFn<? super BoundedWindow> outputTimeFn = (OutputTimeFn<? super BoundedWindow>) windowingStrategy
            .getOutputTimeFn();/*from  ww w .  j  av a2s  .  c om*/

    // get all elements so that we can sort them, has to fit into
    // memory
    // this seems very unprudent, but correct, for now
    ArrayList<WindowedValue<KV<K, AccumT>>> sortedInput = Lists.newArrayList();
    for (WindowedValue<KV<K, AccumT>> inputValue : elements) {
        for (WindowedValue<KV<K, AccumT>> exploded : inputValue.explodeWindows()) {
            sortedInput.add(exploded);
        }
    }
    Collections.sort(sortedInput, new Comparator<WindowedValue<KV<K, AccumT>>>() {
        @Override
        public int compare(WindowedValue<KV<K, AccumT>> o1, WindowedValue<KV<K, AccumT>> o2) {
            return Iterables.getOnlyElement(o1.getWindows()).maxTimestamp()
                    .compareTo(Iterables.getOnlyElement(o2.getWindows()).maxTimestamp());
        }
    });

    // iterate over the elements that are sorted by window timestamp
    //
    final Iterator<WindowedValue<KV<K, AccumT>>> iterator = sortedInput.iterator();

    // get the first accumulator
    WindowedValue<KV<K, AccumT>> currentValue = iterator.next();
    K key = currentValue.getValue().getKey();
    BoundedWindow currentWindow = Iterables.getFirst(currentValue.getWindows(), null);
    AccumT accumulator = currentValue.getValue().getValue();

    // we use this to keep track of the timestamps assigned by the OutputTimeFn,
    // in FlinkPartialReduceFunction we already merge the timestamps assigned
    // to individual elements, here we just merge them
    List<Instant> windowTimestamps = new ArrayList<>();
    windowTimestamps.add(currentValue.getTimestamp());

    while (iterator.hasNext()) {
        WindowedValue<KV<K, AccumT>> nextValue = iterator.next();
        BoundedWindow nextWindow = Iterables.getOnlyElement(nextValue.getWindows());

        if (nextWindow.equals(currentWindow)) {
            // continue accumulating
            accumulator = combineFnRunner.mergeAccumulators(key,
                    ImmutableList.of(accumulator, nextValue.getValue().getValue()), options, sideInputReader,
                    currentValue.getWindows());

            windowTimestamps.add(nextValue.getTimestamp());
        } else {
            // emit the value that we currently have
            out.collect(WindowedValue.of(
                    KV.of(key,
                            combineFnRunner.extractOutput(key, accumulator, options, sideInputReader,
                                    currentValue.getWindows())),
                    outputTimeFn.merge(currentWindow, windowTimestamps), currentWindow, PaneInfo.NO_FIRING));

            windowTimestamps.clear();

            currentWindow = nextWindow;
            currentValue = nextValue;
            accumulator = nextValue.getValue().getValue();
            windowTimestamps.add(nextValue.getTimestamp());
        }

    }

    // emit the final accumulator
    out.collect(WindowedValue.of(
            KV.of(key,
                    combineFnRunner.extractOutput(key, accumulator, options, sideInputReader,
                            currentValue.getWindows())),
            outputTimeFn.merge(currentWindow, windowTimestamps), currentWindow, PaneInfo.NO_FIRING));
}

From source file:com.github.radium226.github.maven.GitHubService.java

public InputStream downloadFileContent(String filePath, GHRepository repository, String tagName)
        throws TransferFailedException {
    try {/*from  ww  w .ja v a 2  s . c o  m*/
        GHTag tag = Iterables.getFirst(Iterables.filter(repository.listTags(), new Predicate<GHTag>() {

            @Override
            public boolean apply(GHTag tag) {
                return tagName.equals(tag.getName());
            }

        }), null);
        return downloadFileContent(filePath, repository, tag);
    } catch (IOException e) {
        throw new TransferFailedException("I don't know why it's so complicated... ", e);
    }
}

From source file:com.b2international.snowowl.snomed.api.impl.ClassificationRunIndex.java

public void trimIndex(int maximumResultsToKeep) throws IOException {
    final Query query = Fields.newQuery().field(FIELD_CLASS, ClassificationRun.class.getSimpleName())
            .matchAll();/* ww w  .  j  a va  2  s  . com*/

    // Sort by decreasing document order
    final Sort sort = new Sort(new SortField(null, Type.DOC, true));

    final ClassificationRun lastRunToKeep = Iterables
            .getFirst(search(query, ClassificationRun.class, sort, maximumResultsToKeep - 1, 1), null);
    if (lastRunToKeep == null) {
        return;
    }

    final Date lastCreationDate = lastRunToKeep.getCreationDate();
    final Query trimmingQuery = LongPoint.newRangeQuery(FIELD_CREATION_DATE, Long.MIN_VALUE,
            lastCreationDate.getTime());
    writer.deleteDocuments(trimmingQuery);
    commit();
}

From source file:com.eucalyptus.auth.login.HmacCredentials.java

public HmacCredentials(final String correlationId, final HmacUtils.SignatureVariant variant,
        final Map<String, List<String>> parameters, final Map<String, List<String>> headers, final String verb,
        final String servicePath, final String body) throws AuthenticationException {
    super(correlationId, variant.getSignature(headerLookup(headers), parameterLookup(parameters)));
    final Function<String, List<String>> headerLookup = headerLookup(headers);
    final Function<String, List<String>> parameterLookup = parameterLookup(parameters);
    this.variant = variant;
    this.parameters = parameters;
    this.headers = headers;
    this.verb = verb;
    this.servicePath = servicePath;
    this.body = body;
    this.headerHost = Iterables
            .getFirst(Objects.firstNonNull(headers.get("host"), Collections.<String>emptyList()), null);
    this.headerPort = "" + 8773;
    if (headerHost != null && headerHost.contains(":")) {
        String[] hostTokens = this.headerHost.split(":");
        this.headerHost = hostTokens[0];
        if (hostTokens.length > 1 && hostTokens[1] != null && !"".equals(hostTokens[1])) {
            this.headerPort = hostTokens[1];
        }//w  w  w  .j a v a  2 s .  c om
    }
    this.queryId = variant.getAccessKeyId(headerLookup, parameterLookup);
    this.securityToken = variant.getSecurityToken(headerLookup, parameterLookup);
    this.signatureMethod = variant.getSignatureMethod(headerLookup, parameterLookup);
}

From source file:com.googlecode.blaisemath.graph.OptimizedGraph.java

/**
 * Return the node adjacent to a leaf//from   w  ww  .  j  av a  2  s.c  o m
 * @param leaf leaf to check
 * @return adjacent node
 * @throws IllegalArgumentException if node is not a leaf
 */
public V getNeighborOfLeaf(V leaf) {
    checkArgument(leafNodes.contains(leaf));
    V res = Iterables.getFirst(neighbors.get(leaf), null);
    checkState(res != null);
    return res;
}