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.erlide.engine.internal.model.erlang.ModelInternalUtils.java

@Override
public String getExternalModulePath(final IErlElementLocator model, final IErlModule module) {
    final List<String> result = Lists.newArrayList();
    IErlElement element = module;/*w ww .j  av  a 2s.  c  o  m*/
    while (element != model) {
        if (element instanceof IErlExternal) {
            final IErlExternal external = (IErlExternal) element;
            result.add(external.getName());
        } else {
            result.add(element.getName());
        }
        element = (IErlElement) element.getParent();
    }
    return Joiner.on(ModelInternalUtils.DELIMITER).join(Lists.reverse(result));
}

From source file:de.l3s.archivepig.enrich.Response.java

@Override
public void enrich(Tuple data, Tuple enrichment, Object... params) throws Exception {
    long size = get(data, "_record.size");
    long offset = get(data, "_record.offset");
    String filename = get(data, "_record.filename");
    String cdxFile = get(data, "_record.cdxFile");

    if (size < 0 || offset < 0)
        return;/*from   ww w.ja va  2  s . c o  m*/

    FileSystem fs = FileSystem.get(UDFContext.getUDFContext().getJobConf());

    Deque<String> cdxSegments = new ArrayDeque<String>(Lists.reverse(list(cdxFile.split("\\/"))));
    cdxSegments.pop(); // remove filename
    String pathExtension = "";
    Path path = new Path(ArchiveLoader.dataPath(), pathExtension + filename);
    while (!fs.exists(path)) {
        if (cdxSegments.isEmpty()) {
            enrichment.append(new HashMap<String, String>());
            enrichment.append(new HashMap<String, String>());
            enrichment.append(null);
            return;
        }
        String cdxSegment = cdxSegments.pop();
        if (cdxSegment.endsWith(".har"))
            cdxSegment = cdxSegment.substring(0, cdxSegment.length() - 4);
        pathExtension = cdxSegment + "/" + pathExtension;
        path = new Path(ArchiveLoader.dataPath(), pathExtension + filename);
    }
    FSDataInputStream fsin = fs.open(path);
    fsin.seek(offset);
    InputStream in = fsin;

    ByteArrayOutputStream recordOutput = new ByteArrayOutputStream();
    try {
        try (BoundedInputStream boundedIn = new BoundedInputStream(in, size);
                ArchiveReader reader = ArchiveReaderFactory.get(filename, boundedIn, false);) {
            ArchiveRecord record;
            record = reader.get();

            ArchiveRecordHeader header = record.getHeader();
            enrichment.append(header.getHeaderFields());

            record.dump(recordOutput);
        } catch (Exception e) {
            return;
        } finally {
            in.close();
            recordOutput.close();
        }
    } catch (Exception e) {
        return;
    }

    try (InputStream httpResponse = new ByteArrayInputStream(recordOutput.toByteArray())) {
        // ALL COMMENTS ARE NEW VERSION VARIANTS FOR HTTP-CORE 4.3, currently in use 4.2.5
        //        SessionInputBufferImpl sessionInputBuffer = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), 2048);
        //        sessionInputBuffer.bind(httpResponse);
        //        DefaultHttpResponseParserFactory responseParserFactory = new DefaultHttpResponseParserFactory();
        //        HttpMessageParser<HttpResponse> responseParser = responseParserFactory.create(sessionInputBuffer, MessageConstraints.DEFAULT);
        //        HttpResponse response = responseParser.parse();
        //        Header[] httpHeaders = response.getAllHeaders();

        HttpResponseParser parser = new HttpResponseParser();
        HttpResponse response = parser.parse(httpResponse);
        HttpHeaders httpHeaders = response.getHeaders();

        Map<String, String> httpHeadersMap = new HashMap<String, String>();
        for (HttpHeader httpHeader : httpHeaders) {
            httpHeadersMap.put(httpHeader.getName(), httpHeader.getValue());
        }
        enrichment.append(httpHeadersMap);

        //        byte[] payload = new byte[sessionInputBuffer.length()];
        //        sessionInputBuffer.read(payload);

        byte[] payload = IOUtils.toByteArray(response);

        enrichment.append(payload);

        //        HttpEntity entity = new ByteArrayEntity(payload);
        //        output.append(entity == null ? null : EntityUtils.toString(entity));
    } catch (Exception ignored) {
    }
}

From source file:com.android.tools.idea.wizard.model.demo.npw.steps.ConfigureProjectStep.java

public ConfigureProjectStep(@NotNull ProjectModel model) {
    super(model, "Configure Project");

    myProjectLocationText = new TextProperty(myProjectLocationLabel);
    myAppNameText = new TextProperty(myAppNameTextField);
    myPackageText = new TextProperty(myPackageLabel);
    myDomaninText = new TextProperty(myDomainTextfield);

    myBindings.bind(myProjectLocationText, new StringExpression(myAppNameText) {
        @NotNull/*www  . ja v  a  2 s.  c  o m*/
        @Override
        public String get() {
            return String.format("/usr/local/demopath/code/%s",
                    CharMatcher.WHITESPACE.removeFrom(myAppNameText.get()));
        }
    });

    myBindings.bind(myPackageText, new StringExpression(myDomaninText, myAppNameText) {
        @NotNull
        @Override
        public String get() {
            List<String> parts = Splitter.on('.').omitEmptyStrings().splitToList(myDomaninText.get());
            parts = Lists.newArrayList(Lists.reverse(parts));
            if (!myAppNameText.get().isEmpty()) {
                parts.add(CharMatcher.WHITESPACE.removeFrom(myAppNameText.get()).toLowerCase());
            }
            return Joiner.on('.').join(parts);
        }
    });

    myAppNameTextField.setText("Application");
    myDomainTextfield.setText("example.com");
}

From source file:org.lightjason.agentspeak.action.builtin.collection.list.CReverse.java

@Nonnull
@Override//w  w  w.j  av a 2s. c  om
public final IFuzzyValue<Boolean> execute(final boolean p_parallel, @Nonnull final IContext p_context,
        @Nonnull final List<ITerm> p_argument, @Nonnull final List<ITerm> p_return) {
    // all arguments are list references
    p_return.addAll(Lists.reverse(CCommon.flatten(p_argument).collect(Collectors.toList())));
    return CFuzzyValue.from(true);
}

From source file:grakn.core.graql.reasoner.plan.ResolutionQueryPlan.java

private static QueryList refinePlan(QueryList queries) {
    QueryList plan = new QueryList();
    Stack<ReasonerQueryImpl> queryStack = new Stack<>();

    Lists.reverse(prioritise(queries)).forEach(queryStack::push);
    while (!plan.containsAll(queries)) {
        ReasonerQueryImpl query = queryStack.pop();

        QuerySet candidates = queries.getCandidates(query, plan);

        if (!candidates.isEmpty() || queries.size() - plan.size() == 1) {
            plan.add(query);/*www .  j  a  va  2s.c o m*/
            Lists.reverse(prioritise(candidates)).forEach(queryStack::push);
        }
    }

    return plan;
}

From source file:org.eclipse.emf.ecore.xcore.lib.XcoreEListExtensions.java

/**
 * Provides a reverse view of the given list which is especially useful for traversing a list backwards in a for-each loop.
 *
 * @param list the list whose elements should be viewed in reverse. May not be <code>null</code>.
 * @return a list with the same elements as the given list, in reverse order.
 *///w  w w  .j a va 2 s .  c om
@Pure
public static <T> EList<T> reverseView(EList<T> list) {
    return ECollections.asEList(Lists.reverse(list));
}

From source file:dao.reporting.ReportingDao.java

/**
 * Get the list of ancestors of a reporting category
 * /*from   ww  w  .j  av  a  2  s .  c  o m*/
 * The first element of the list is the root node, and the last is the
 * concerned node.
 * 
 * @param id
 *            the reporting category id
 */
public static List<ReportingCategory> getReportingCategoryAncestors(Long id) {
    ReportingCategory leaf = getReportingCategoryById(id);
    List<ReportingCategory> ancestors = new ArrayList<>();
    findReportingCategoryAncestors(ancestors, leaf);
    return Lists.reverse(ancestors);
}

From source file:org.atteo.moonshine.tests.MoonshineRunner.java

@Override
protected List<TestRule> classRules() {
    @SuppressWarnings("unchecked")
    Set<Class<?>> ancestorSet = (Set<Class<?>>) TypeToken.of(getTestClass().getJavaClass()).getTypes()
            .rawTypes();//from  www.j a v a  2 s .  c  o  m
    List<Class<?>> ancestors = Lists.reverse(new ArrayList<>(ancestorSet));

    final List<String> configPaths = new ArrayList<>();
    List<MoonshineConfigurator> configurators = new ArrayList<>();
    AtomicBoolean loadTestConfigXml = new AtomicBoolean(true);

    for (Class<?> ancestor : ancestors) {
        analyseAncestor(ancestor, configPaths, configurators, loadTestConfigXml);
    }

    analyseIterationConfigs(configPaths, configurators);

    moonshineRule = new MoonshineRule(configurators, configPaths.toArray(new String[configPaths.size()]));
    moonshineRule.setLoadTestConfigXml(loadTestConfigXml.get());

    List<TestRule> rules = super.classRules();
    if (requestPerClass) {
        rules.add(new RequestRule());
    }

    rules.add(moonshineRule);
    return rules;
}

From source file:org.fcrepo.kernel.impl.rdf.impl.PrefixingIdentifierTranslator.java

private void setTranslationChain() {

    for (final Converter<String, String> t : minimalTranslationChain) {
        forward = forward.andThen(t);//from www  .ja v a 2  s.c o m
    }
    for (final Converter<String, String> t : Lists.reverse(minimalTranslationChain)) {
        reverse = reverse.andThen(t.reverse());
    }
}

From source file:org.pantsbuild.args4j.Parser.java

/**
 * Parses command line arguments and populates the given {@code option} bean with the values if
 * the parse is successful./*from w  w w . j  a v a  2 s  .co  m*/
 *
 * @param options The options bean to populate with the parsed command line options.
 * @param args The command line arguments to parse.
 * @return The result of the parse.
 */
public static Result parse(Object options, String... args) {
    OptionHandlerRegistry.getRegistry().registerHandler(boolean.class, BooleanOptionHandler.class);
    OptionHandlerRegistry.getRegistry().registerHandler(Boolean.class, BooleanOptionHandler.class);

    ParserProperties parserProperties = ParserProperties.defaults()
            // The @ syntax here is global, @argfile alone is a file one or more options in it.
            // The jar-tool traditionally accepted limited @argfile switch values, ie: -f=@argfile,
            // and the contents of the argfile was the single option's value.
            // As such we turn off args4j @ syntax explicitly and implement a custom OptionHandler
            // to retain the traditional jar-tool @ semantics.
            .withAtSyntax(false).withOptionValueDelimiter("=").withShowDefaults(true);

    // Args4j expects positional arguments come 1st whereas pants traditionally expects them to come
    // last.  Fixup the order to suit Args4j if needed.
    // NB: This only works because we set the option value delimiter to non-whitespace above!
    List<String> arguments = Lists.newArrayList(args);
    if (arguments.size() > 1) {
        List<String> positionalArgs = Lists.newArrayList();
        Iterator<String> reverseArgIterator = Lists.reverse(arguments).iterator();
        while (reverseArgIterator.hasNext()) {
            String arg = reverseArgIterator.next();
            if (!arg.startsWith("-")) {
                reverseArgIterator.remove();
                positionalArgs.add(arg);
            } else {
                break;
            }
        }
        arguments.addAll(0, Lists.reverse(positionalArgs));
    }

    CmdLineParser cmdLineParser = new CmdLineParser(options, parserProperties);
    try {
        cmdLineParser.parseArgument(arguments);
        return Result.success(cmdLineParser);
    } catch (CmdLineException e) {
        return Result.failure(cmdLineParser, "Invalid command line:\n\t%s", e.getLocalizedMessage());
    } catch (InvalidCmdLineArgumentException e) {
        return Result.failure(cmdLineParser, "Invalid command line parameter:\n\t%s", e.getMessage());
    }
}