Example usage for com.google.common.collect Lists reverse

List of usage examples for com.google.common.collect Lists reverse

Introduction

In this page you can find the example usage for com.google.common.collect Lists reverse.

Prototype

@CheckReturnValue
public static <T> List<T> reverse(List<T> list) 

Source Link

Document

Returns a reversed view of the specified list.

Usage

From source file:org.sosy_lab.cpachecker.cpa.livevar.LiveVariablesTransferRelation.java

@Override
protected LiveVariablesState handleMultiEdge(MultiEdge cfaEdge) throws CPATransferException {
    // as we are using the backwards analysis, we also have to iterate over
    // multiedges in reverse
    for (final CFAEdge innerEdge : Lists.reverse(cfaEdge.getEdges())) {
        edge = innerEdge;/*  www .  jav a  2s  . c  om*/
        state = handleSimpleEdge(innerEdge);
    }
    edge = cfaEdge; // reset edge
    return state;
}

From source file:ch.puzzle.itc.mobiliar.presentation.templateEdit.EditTemplateView.java

/**
 * This is a viewParameter and is called by JSF!
 */// ww w . j  a v  a  2 s.  c  om
public void setTemplateId(Integer templateId) {
    template = templateEditor.getTemplateById(templateId);
    revisionInformations = Lists.reverse(templateEditor.getTemplateRevisions(templateId));
    findSelectedStp();
}

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

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    ImmutableList.Builder<Step> steps = ImmutableList.builder();

    steps.addAll(MakeCleanDirectoryStep.of(BuildCellRelativePath.fromCellRelativePath(
            context.getBuildCellRootPath(), getProjectFilesystem(), getResourceApkPath().getParent())));

    AaptPackageResources.prepareManifestForAapt(context, steps, getProjectFilesystem(), getFinalManifestPath(),
            context.getSourcePathResolver().getAbsolutePath(manifest), manifestEntries);

    Path linkTreePath = BuildTargetPaths.getScratchPath(getProjectFilesystem(), getBuildTarget(),
            "%s/link-tree");

    // Need to reverse the order of the rules because aapt2 allows later resources
    // to override earlier ones, but aapt gives the earlier ones precedence.
    Iterable<Path> compiledResourcePaths = Lists.reverse(compileRules).stream()
            .map(Aapt2Compile::getSourcePathToOutput)
            .map(context.getSourcePathResolver()::getAbsolutePath)::iterator;
    // Make a symlink tree to avoid lots of really long filenames
    // that can exceed the limit on Mac.
    int index = 1;
    ImmutableMap.Builder<Path, Path> symlinkMap = ImmutableMap.builder();
    ImmutableList.Builder<Path> symlinkPaths = ImmutableList.builder();
    for (Path flata : compiledResourcePaths) {
        Path linkPath = Paths.get(String.format("res-%09d.flata", index++));
        symlinkPaths.add(linkPath);/*from  w w w. j a  v  a 2  s  . c  om*/
        symlinkMap.put(linkPath, flata);
    }

    steps.addAll(MakeCleanDirectoryStep.of(BuildCellRelativePath
            .fromCellRelativePath(context.getBuildCellRootPath(), getProjectFilesystem(), linkTreePath)));
    steps.add(new SymlinkTreeStep("aapt", getProjectFilesystem(), linkTreePath, symlinkMap.build()));

    steps.add(new Aapt2LinkStep(context.getSourcePathResolver(), getProjectFilesystem().resolve(linkTreePath),
            symlinkPaths.build(), dependencyResourceApks.stream()
                    .map(context.getSourcePathResolver()::getRelativePath).collect(Collectors.toList())));
    steps.add(ZipScrubberStep.of(getProjectFilesystem().resolve(getResourceApkPath())));

    buildableContext.recordArtifact(getFinalManifestPath());
    buildableContext.recordArtifact(getResourceApkPath());
    buildableContext.recordArtifact(getProguardConfigPath());
    buildableContext.recordArtifact(getRDotTxtPath());
    // Don't really need this, but it's small and might help with debugging.
    buildableContext.recordArtifact(getInitialRDotJavaDir());

    return steps.build();
}

From source file:com.google.template.soy.passes.CheckBadContextualUsagePass.java

private ContentKind getContentKindOfPrintDirectives(PrintNode node) {
    for (PrintDirectiveNode printDirectiveNode : Lists.reverse(node.getChildren())) {
        if (!printDirectiveNode.isSynthetic()) {
            SoyPrintDirective printDirective = printDirectiveNode.getPrintDirective();
            return printDirective instanceof SanitizedContentOperator
                    ? ((SanitizedContentOperator) printDirective).getContentKind()
                    : ContentKind.TEXT;//from   w w  w  .  j  a v a  2s . c o m
        }
    }
    return null;
}

From source file:net.morimekta.gittool.cmd.Status.java

@Override
public void execute(GitTool gt) throws IOException {
    try (Repository repository = gt.getRepository()) {
        RepositoryState state = repository.getRepositoryState();
        if (state != RepositoryState.SAFE) {
            System.out.println(WARN + "Repository not in a safe state" + CLEAR + ": " + state.getDescription());
        }//from   w w  w .j ava  2  s  . c  om

        Git git = new Git(repository);
        String currentBranch = repository.getBranch();
        String diffWithBranch = branch != null ? branch : gt.getDiffbase(currentBranch);

        this.root = gt.getRepositoryRoot().getCanonicalFile().getAbsolutePath();

        Ref currentRef = repository.getRef(gt.refName(currentBranch));
        Ref diffWithRef = repository.getRef(gt.refName(diffWithBranch));
        if (diffWithRef == null) {
            System.out.println(format("No such branch %s%s%s", BOLD, diffWithBranch, CLEAR));
            return;
        }

        ObjectId currentHead = currentRef.getObjectId();
        ObjectId diffWithHead = diffWithRef.getObjectId();

        // RevCommit currentCommit = commitOf(repository, currentHead);

        if (!currentHead.equals(diffWithHead)) {
            String stats = "";
            String diff = gt.isRemote(diffWithBranch) ? format("[->%s%s%s] ", DIM, diffWithBranch, CLEAR)
                    : format("[d:%s%s%s] ", CLR_BASE_BRANCH, diffWithBranch, CLEAR);

            List<RevCommit> localCommits = ImmutableList
                    .copyOf(git.log().addRange(diffWithHead, currentHead).call());
            List<RevCommit> remoteCommits = ImmutableList
                    .copyOf(git.log().addRange(currentHead, diffWithHead).call());

            localCommits = Lists.reverse(localCommits);
            remoteCommits = Lists.reverse(remoteCommits);

            int commits = localCommits.size();
            int missing = remoteCommits.size();

            RevCommit ancestor, local;
            if (remoteCommits.size() > 0) {
                List<RevCommit> sub2 = Lists.reverse(
                        ImmutableList.copyOf(git.log().add(remoteCommits.get(0)).setMaxCount(2).call()));
                ancestor = sub2.get(0);
            } else {
                ancestor = gt.commitOf(repository, diffWithBranch)
                        .orElseThrow(() -> new IOException("No commit on " + diffWithBranch));
            }
            if (localCommits.size() > 0) {
                local = localCommits.get(localCommits.size() - 1);
            } else {
                local = gt.commitOf(repository, currentBranch)
                        .orElseThrow(() -> new IOException("No commit on " + currentBranch));
            }

            if (commits > 0 || missing > 0) {
                if (commits == 0) {
                    stats = format(" [%s-%d%s]", CLR_SUBS, missing, CLEAR);
                } else if (missing == 0) {
                    stats = format(" [%s+%d%s]", CLR_ADDS, commits, CLEAR);
                } else {
                    stats = format(" [%s+%d%s,%s-%d%s]", CLR_ADDS, commits, CLEAR, CLR_SUBS, missing, CLEAR);
                }
            }

            System.out.println(format("Commits on %s%s%s%s since %s -- %s%s%s%s", CLR_UPDATED_BRANCH,
                    currentBranch, CLEAR, stats, date(ancestor), diff, DIM, ancestor.getShortMessage(), CLEAR));

            if (files) {
                ObjectReader reader = repository.newObjectReader();
                CanonicalTreeParser ancestorTreeIter = new CanonicalTreeParser();
                ancestorTreeIter.reset(reader, ancestor.getTree());
                CanonicalTreeParser localTreeIter = new CanonicalTreeParser();
                localTreeIter.reset(reader, local.getTree());

                // finally get the list of changed files
                List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true).setOldTree(ancestorTreeIter)
                        .setNewTree(localTreeIter).call();
                for (DiffEntry entry : diffs) {
                    switch (entry.getChangeType()) {
                    case RENAME:
                        System.out.println(format(" R %s%s%s <- %s%s%s", new Color(YELLOW, DIM),
                                entry.getNewPath(), CLEAR, DIM, path(entry.getOldPath()), CLEAR));
                        break;
                    case MODIFY:
                        System.out.println(format("   %s", path(entry.getOldPath())));
                        break;
                    case ADD:
                        System.out.println(format(" A %s%s%s", GREEN, path(entry.getNewPath()), CLEAR));
                        break;
                    case DELETE:
                        System.out.println(format(" D %s%s%s", YELLOW, path(entry.getOldPath()), CLEAR));
                        break;
                    case COPY:
                        System.out.println(format(" C %s%s%s <- %s%s%s", new Color(YELLOW, DIM),
                                path(entry.getNewPath()), CLEAR, DIM, path(entry.getOldPath()), CLEAR));
                        break;
                    }
                }
            } else {
                for (RevCommit localCommit : localCommits) {
                    System.out.println(format("+ %s%s%s (%s)", GREEN, localCommit.getShortMessage(), CLEAR,
                            date(localCommit)));
                }
                for (RevCommit remoteCommit : remoteCommits) {
                    System.out.println(format("- %s%s%s (%s)", RED, remoteCommit.getShortMessage(), CLEAR,
                            date(remoteCommit)));
                }
            }
        } else {
            RevCommit diffWithCommit = gt.commitOf(repository, diffWithBranch)
                    .orElseThrow(() -> new IOException("No commit in " + diffWithBranch));
            System.out.println(format("No commits on %s%s%s since %s -- %s%s%s", GREEN, currentBranch, CLEAR,
                    date(diffWithCommit), DIM, diffWithCommit.getShortMessage(), CLEAR));
        }

        // Check for staged and unstaged changes.
        if (files) {
            List<DiffEntry> staged = git.diff().setCached(true).call();
            List<DiffEntry> unstaged = git.diff().setCached(false).call();

            if (staged.size() > 0 || unstaged.size() > 0) {
                System.out.println();
                System.out.println(format("%sUncommitted%s changes on %s%s%s:", RED, CLEAR, CLR_UPDATED_BRANCH,
                        currentBranch, CLEAR));

                Map<String, FileStatus> st = unstaged.stream().map(d -> new FileStatus(relative, root, d))
                        .collect(Collectors.toMap(FileStatus::getNewestPath, fs -> fs));
                staged.forEach(d -> {
                    if (d.getNewPath() != null) {
                        if (st.containsKey(d.getNewPath())) {
                            st.get(d.getNewPath()).setStaged(d);
                            return;
                        }
                    }
                    if (d.getOldPath() != null) {
                        if (st.containsKey(d.getOldPath())) {
                            st.get(d.getOldPath()).setStaged(d);
                            return;
                        }
                    }
                    FileStatus fs = new FileStatus(relative, root, null).setStaged(d);

                    st.put(fs.getNewestPath(), fs);
                });

                for (FileStatus fs : new TreeMap<>(st).values()) {
                    System.out.println(fs.statusLine());
                }
            }
        } else {
            List<DiffEntry> staged = git.diff().setShowNameAndStatusOnly(true).setCached(true).call();
            List<DiffEntry> unstaged = git.diff().setShowNameAndStatusOnly(true).setCached(false).call();

            if (staged.size() > 0 || unstaged.size() > 0) {
                System.out.println(
                        format("Uncommitted changes on %s%s%s:", CLR_UPDATED_BRANCH, currentBranch, CLEAR));

                if (staged.size() > 0) {
                    long adds = staged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.ADD)
                            .count();
                    long dels = staged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.DELETE)
                            .count();
                    long mods = staged.size() - adds - dels;

                    System.out.print(format(" - %sStaged files%s   :", new Color(YELLOW, DIM), CLEAR));
                    if (adds > 0) {
                        System.out.print(format(" %s+%d%s", GREEN, adds, CLEAR));
                    }
                    if (dels > 0) {
                        System.out.print(format(" %s-%d%s", RED, dels, CLEAR));
                    }
                    if (mods > 0) {
                        System.out.print(format(" %s/%d%s", DIM, mods, CLEAR));
                    }
                    System.out.println();
                }
                if (unstaged.size() > 0) {
                    long adds = unstaged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.ADD)
                            .count();
                    long dels = unstaged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.DELETE)
                            .count();
                    long mods = unstaged.size() - adds - dels;

                    System.out.print(format(" - %sUnstaged files%s :", YELLOW, CLEAR));
                    if (adds > 0) {
                        System.out.print(format(" %s+%d%s", GREEN, adds, CLEAR));
                    }
                    if (dels > 0) {
                        System.out.print(format(" %s-%d%s", RED, dels, CLEAR));
                    }
                    if (mods > 0) {
                        System.out.print(format(" %s/%d%s", DIM, mods, CLEAR));
                    }
                    System.out.println();
                }
            }
        }
    } catch (GitAPIException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.ejie.uda.jsonI18nEditor.Editor.java

public void importResources(Path dir) {

    Stream<Path> filter;

    try {/*  www .j a v  a 2  s.  c o  m*/
        if (!closeCurrentSession()) {
            return;
        }
        if (Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) {
            reset();
            resourcesDir = dir;
            filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path));

        } else {
            reset();
            // Se ha arrastrado un fichero de 18n individual, se debe de obtener los recursos relacionados con el bundle al que pertenece.
            Pattern.matches(BUNDLE_REGEX, dir.getFileName().toString());
            Pattern regex = Pattern.compile(BUNDLE_REGEX);
            resourcesDir = dir.getParent();
            inputFile = dir;
            Matcher regexMatcher = regex.matcher(dir.getFileName().toString());
            if (regexMatcher.find()) {
                this.bundle = regexMatcher.group(1);
                filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path, this.bundle));
            } else {
                showError(MessageBundle.get("resources.open.error.multiple"));
                return;
            }
            //         Pattern.matches("BUNDLE_REGEX", dir.getFileName().toString());
            //         showError(MessageBundle.get("resources.open.error.multiple"));
            //         return;
        }

        filter.forEach(path -> {
            try {
                Resource resource = Resources.read(path);
                setupResource(resource);
            } catch (Exception e) {
                e.printStackTrace();
                showError(MessageBundle.get("resources.open.error.single", path.toString()));
            }
        });

        List<String> recentDirs = settings.getListProperty("history");
        recentDirs.remove(dir);
        recentDirs.add(dir.toString());
        if (recentDirs.size() > 5) {
            recentDirs.remove(0);
        }
        settings.setProperty("history", recentDirs);
        editorMenu.setRecentItems(Lists.reverse(recentDirs));

        Map<String, String> keys = Maps.newTreeMap();
        resources.forEach(resource -> keys.putAll(resource.getTranslations()));
        //         resources.forEach(resource -> {
        //            
        //            
        //            
        //         });
        List<String> keyList = Lists.newArrayList(keys.keySet());
        translationTree.setModel(new TranslationTreeModel(keyList));

        updateUI();
        //         for (String key : keyList) {
        //            boolean anyEmpty = false;
        //            
        //            for (Resource resource : resources) {
        //               if (StringUtils.isBlank(resource.getTranslation(key))){
        //                  anyEmpty = true;
        //               }
        //            }
        //            
        //            TranslationTreeModel model = (TranslationTreeModel) translationTree.getModel();
        //            TranslationTreeNode node = model.getNodeByKey(key);
        //            
        //            node
        //         }
        //         keyList.stream().filter(key -> {
        //            
        //            resources.stream().filter(resource -> {
        //               return StringUtils.isNotBlank(resource.getTranslation(key));
        //            });
        //            return true;
        //         });
    } catch (IOException e) {
        e.printStackTrace();
        showError(MessageBundle.get("resources.open.error.multiple"));
    }
}

From source file:org.jclouds.cleanup.data.Bean.java

/**
 * @return the fields of this class inherited from superclasses, in descending order (super-first)
 *///from  w  w  w .  j a v a 2 s  .co  m
public List<InstanceField> getSuperFields() {
    List<InstanceField> result = Lists.newArrayList();
    List<Bean> classes = Lists.newArrayList();
    for (Bean current = getSuperClass(); current != null; current = current.getSuperClass()) {
        classes.add(current);
    }
    for (Bean current : Lists.reverse(classes)) {
        result.addAll(current.getInstanceFields());
    }
    return result;
}

From source file:no.ntnu.okse.web.controller.LogController.java

/**
 * Returns the available log levels//from w  ww . j  a  va2s. c  om
 *
 * @return A List of the available log levels
 */
@RequestMapping(value = LOG_LEVELS, method = RequestMethod.GET)
public @ResponseBody List<Object> logLevelsAvailable() {
    List<Object> reverseList = Lists.reverse(Lists.newArrayList(logLevels.keySet()));
    return reverseList;
}

From source file:com.google.devtools.build.lib.analysis.config.ConfigSetting.java

/**
 * For single-value options, returns true iff the option's value matches the expected value.
 *
 * <p>For multi-value List options, returns true iff any of the option's values matches
 * the expected value. This means, e.g. "--tool_tag=foo --tool_tag=bar" would match the
 * expected condition { 'tool_tag': 'bar' }.
 *
 * <p>For multi-value Map options, returns true iff the last instance with the same key as the
 * expected key has the same value. This means, e.g. "--define foo=1 --define bar=2" would
 * match { 'define': 'foo=1' }, but "--define foo=1 --define bar=2 --define foo=3" would not
 * match. Note that the definition of --define states that the last instance takes precedence.
 *///w  w  w  .  j a va  2 s  . c o m
private static boolean optionMatches(BuildConfiguration config, String optionName, Object expectedValue) {
    Object actualValue = config.getOptionValue(optionName);
    if (actualValue == null) {
        return expectedValue == null;

        // Single-value case:
    } else if (!config.allowsMultipleValues(optionName)) {
        return actualValue.equals(expectedValue);
    }

    // Multi-value case:
    Preconditions.checkState(actualValue instanceof List);
    Preconditions.checkState(expectedValue instanceof List);
    List<?> actualList = (List<?>) actualValue;
    List<?> expectedList = (List<?>) expectedValue;

    if (actualList.isEmpty() || expectedList.isEmpty()) {
        return actualList.isEmpty() && expectedList.isEmpty();
    }

    // We're expecting a single value of a multi-value type: the options parser still embeds
    // that single value within a List container. Retrieve it here.
    Object expectedSingleValue = Iterables.getOnlyElement(expectedList);

    // Multi-value map:
    if (actualList.get(0) instanceof Map.Entry) {
        Map.Entry<?, ?> expectedEntry = (Map.Entry<?, ?>) expectedSingleValue;
        for (Map.Entry<?, ?> actualEntry : Lists.reverse((List<Map.Entry<?, ?>>) actualList)) {
            if (actualEntry.getKey().equals(expectedEntry.getKey())) {
                // Found a key match!
                return actualEntry.getValue().equals(expectedEntry.getValue());
            }
        }
        return false; // Never found any matching key.
    }

    // Multi-value list:
    return actualList.contains(expectedSingleValue);
}

From source file:io.github.proxysprojects.mct.inventory.ContainerBase.java

/**
 * Transfers an item stack to slots with the specified slot type ID.
 *
 * @param stack The item stack/*  ww w. ja  v  a 2  s. com*/
 * @param slotTypeID The slot type IDs of the slots to which the stack will be transferred
 * @param reverseDirection Whether or not the stack will be added in reverse direction
 * @return Whether or not the stack was transferred
 */
protected boolean transferStackTo(ItemStack stack, String slotTypeID, boolean reverseDirection) {
    List<Slot> slots = getTypeSlots(slotTypeID);
    if (reverseDirection)
        slots = Lists.reverse(slots);
    return transferStackTo(stack, slots::iterator, reverseDirection);
}