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.gitools.ui.app.heatmap.drawer.header.HierarchicalClusterHeaderDrawer.java

public int getDrawerIndexFromPoint(Point p, int x, int y) {
    if (isHorizontal()) {
        for (AbstractHeatmapDrawer d : drawers) {
            Dimension sz = d.getSize();
            Rectangle box2 = new Rectangle(x, y, sz.width, sz.height);
            if (box2.contains(p)) {
                return drawers.indexOf(d);
            }//from   w  ww. j  av a 2 s.c  o m
            y += sz.height;
        }
    } else {
        for (AbstractHeatmapDrawer d : Lists.reverse(drawers)) {
            Dimension sz = d.getSize();
            Rectangle box2 = new Rectangle(x, y, sz.width, sz.height);
            if (box2.contains(p)) {
                return drawers.indexOf(d);
            }
            x += sz.width;
        }
    }
    return 0;
}

From source file:org.apache.drill.exec.planner.sql.SchemaUtilites.java

/** Utility method to get the schema path as list for given schema instance. */
public static List<String> getSchemaPathAsList(SchemaPlus schema) {
    if (isRootSchema(schema)) {
        return Collections.EMPTY_LIST;
    }/*w  w  w  . j av  a 2s .c o m*/

    List<String> path = Lists.newArrayListWithCapacity(5);
    while (schema != null) {
        final String name = schema.getName();
        if (!Strings.isNullOrEmpty(name)) {
            path.add(schema.getName());
        }
        schema = schema.getParentSchema();
    }

    return Lists.reverse(path);
}

From source file:org.exoplatform.social.extras.feedmash.AbstractFeedmashJob.java

/**
 * Feedmash job. Provides support for fetching the job. Lets subclasses filter
 * and process the matching entries./*from   w  ww. ja va  2  s . co  m*/
 */
@SuppressWarnings("unchecked")
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();

        // read job settings
        init(dataMap);

        // make sure server has finished starting
        if (severIsStarting(dataMap)) {
            return;
        }

        // let subclass do something before proceeding
        beforeJobExecute(dataMap);

        // Read the feed
        SyndFeedInput input = new SyndFeedInput();

        URLConnection urlConnection = null;
        URL url = new URL(feedUrl);
        if (url.getUserInfo() != null) {
            byte[] authEncBytes = Base64.encode(url.getUserInfo().getBytes());
            String authStringEnc = new String(authEncBytes);
            urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        } else if (username != null && password != null) {
            byte[] authEncBytes = Base64.encode((username + ":" + password).getBytes());
            String authStringEnc = new String(authEncBytes);
            urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        } else {
            urlConnection = url.openConnection();
        }

        InputStream is = urlConnection.getInputStream();
        SyndFeed feed = input.build(new XmlReader(is));
        List<SyndEntryImpl> entries = feed.getEntries();

        // process what we are interested in
        for (SyndEntryImpl entry : Lists.reverse(entries)) {
            if (accept(entry)) {
                handle(entry);
            }
        }
    } catch (Exception e) {
        throw new JobExecutionException(e);
    }

}

From source file:com.synflow.cx.internal.instantiation.InstantiationContext.java

/**
 * Returns the full name as an underscore-separated list of names.
 * //from   w w  w  .ja  v a  2  s.  co m
 * @return a string
 */
public String getName() {
    List<String> path = new ArrayList<>();
    Node node = this;
    do {
        path.add((String) node.getContent());
        node = node.getParent();
    } while (node != null);

    return Joiner.on('_').join(Lists.reverse(path));
}

From source file:com.roche.sequencing.bioinformatics.common.stringsequence.alignment.NeedlemanWunschGlobalStringAlignment.java

/**
 * return an alignment pair associated with the global alignment of the reference and query sequences provided.
 * /* w w  w. java2s  .  c o m*/
 * @return
 */
public StringAlignmentPair getAlignmentPair() {
    if (alignment == null) {
        initializeTraceabilityMatrix();
        completeTraceabilityMatrix();

        List<ILetter> alignment1 = new ArrayList<ILetter>();
        List<ILetter> alignment2 = new ArrayList<ILetter>();
        TraceabilityMatrixCell currentCell = getStartingTracebackCell();

        while (!tracebackComplete(currentCell)) {
            if (currentCell.getRowIndex() - currentCell.getSourceCell().getRowIndex() == 1) {
                alignment2.add(querySequence.get(currentCell.getRowIndex() - 1));
            } else {
                alignment2.add(Gap.GAP);
            }

            if (currentCell.getColumnIndex() - currentCell.getSourceCell().getColumnIndex() == 1) {
                alignment1.add(referenceSequence.get(currentCell.getColumnIndex() - 1));
            } else {
                alignment1.add(Gap.GAP);
            }

            currentCell = currentCell.getSourceCell();
        }

        alignment = new StringAlignmentPair(Lists.reverse(alignment1), Lists.reverse(alignment2));
    }

    return alignment;
}

From source file:org.opendaylight.controller.netconf.cli.reader.custom.FilterReader.java

@Override
protected List<Node<?>> readWithContext(final DataSchemaNode schemaNode) throws IOException, ReadingException {
    boolean redSuccessfuly = false;
    Node<?> newNode = null;
    do {//  ww  w.  j a  v  a  2s. c o  m
        console.writeLn("Filter " + schemaNode.getQName().getLocalName());
        console.writeLn("Submit path of the data to retrieve. Use TAB for autocomplete");

        final String rawValue = console.read();

        // FIXME skip should be somewhere in abstractReader
        if (isSkipInput(rawValue) || Strings.isNullOrEmpty(rawValue)) {
            return Collections.emptyList();
        }

        final List<QName> filterPartsQNames = Lists.newArrayList();

        try {
            for (final String part : rawValue.split(SEPARATOR)) {
                final QName qName = IOUtil.qNameFromKeyString(part, mappedModules);
                filterPartsQNames.add(qName);
            }

            Node<?> previous = null;

            for (final QName qName : Lists.reverse(filterPartsQNames)) {
                previous = new CompositeNodeTOImpl(qName, null,
                        previous == null ? Collections.<Node<?>>emptyList()
                                : Collections.<Node<?>>singletonList(previous));
            }

            final Map<QName, String> attributes = Collections.singletonMap(FILTER_TYPE_QNAME,
                    FILTER_TYPE_VALUE_DEFAULT);
            newNode = previous == null ? null
                    : ImmutableCompositeNode.create(schemaNode.getQName(), attributes,
                            Collections.<Node<?>>singletonList(previous));
            redSuccessfuly = true;
        } catch (final ReadingException e) {
            final String message = "Specified filter path isn't correct.";
            LOG.error(message, e);
            console.writeLn(message);
        }
    } while (!redSuccessfuly);
    return Collections.<Node<?>>singletonList(newNode);
}

From source file:com.cloudbees.jenkins.support.impl.SlaveLogs.java

@Override
public void addContents(@NonNull Container container) {
    // expensive remote computation are pooled together and executed later concurrently across all the agents
    List<java.util.concurrent.Callable<List<FileContent>>> tasks = Lists.newArrayList();
    SmartLogFetcher logFetcher = new SmartLogFetcher("cache", new LogFilenameFilter()); // id is awkward because of backward compatibility
    SmartLogFetcher winswLogFetcher = new SmartLogFetcher("winsw", new WinswLogfileFilter());

    for (final Node node : Jenkins.get().getNodes()) {
        if (node.toComputer() instanceof SlaveComputer) {
            container.add(new LogRecordContent("nodes/slave/" + node.getNodeName() + "/jenkins.log") {
                @Override/*from   w w w  .  j  a  v a  2  s. c  o  m*/
                public Iterable<LogRecord> getLogRecords() throws IOException {
                    Computer computer = node.toComputer();
                    if (computer == null) {
                        return Collections.emptyList();
                    } else {
                        try {
                            return Lists.reverse(new ArrayList<>(computer.getLogRecords()));
                        } catch (InterruptedException e) {
                            throw new IOException(e);
                        }
                    }
                }
            });
        }

        addSlaveJulLogRecords(container, tasks, node, logFetcher);
        addWinsStdoutStderrLog(tasks, node, winswLogFetcher);
    }

    // execute all the expensive computations in parallel to speed up the time
    if (!tasks.isEmpty()) {
        ExecutorService service = Executors.newFixedThreadPool(
                Math.max(1, Math.min(Runtime.getRuntime().availableProcessors() * 2, tasks.size())),
                new ExceptionCatchingThreadFactory(new DaemonThreadFactory()));
        try {
            long expiresNanoTime = System.nanoTime()
                    + TimeUnit.SECONDS.toNanos(SupportPlugin.REMOTE_OPERATION_CACHE_TIMEOUT_SEC);
            for (java.util.concurrent.Future<List<FileContent>> r : service.invokeAll(tasks,
                    SupportPlugin.REMOTE_OPERATION_CACHE_TIMEOUT_SEC, TimeUnit.SECONDS)) {
                try {
                    for (FileContent c : r.get(Math.max(1, expiresNanoTime - System.nanoTime()),
                            TimeUnit.NANOSECONDS)) {
                        container.add(c);
                    }
                } catch (ExecutionException e) {
                    LOGGER.log(Level.WARNING, "Could not retrieve some of the remote node extra logs", e);
                } catch (TimeoutException e) {
                    LOGGER.log(Level.WARNING, "Could not retrieve some of the remote node extra logs", e);
                    r.cancel(false);
                }
            }
        } catch (InterruptedException e) {
            LOGGER.log(Level.WARNING, "Could not retrieve some of the remote node extra logs", e);
        } finally {
            service.shutdown();
        }
    }

}

From source file:org.sonar.java.se.checks.ParameterNullnessCheck.java

private static List<SymbolicValue> getArgumentSVs(ProgramState state, Tree syntaxNode, int nbArguments) {
    if (syntaxNode.is(Tree.Kind.METHOD_INVOCATION)) {
        return Lists.reverse(state.peekValues(nbArguments + 1).subList(0, nbArguments));
    }//from   w w w. j  a  v a 2  s  .c o m
    return Lists.reverse(state.peekValues(nbArguments));
}

From source file:com.facebook.presto.sql.gen.SwitchCodeGenerator.java

@Override
public ByteCodeNode generateExpression(Signature signature, ByteCodeGeneratorContext generatorContext,
        Type returnType, List<RowExpression> arguments) {
    // TODO: compile as
    /*/*ww  w.ja  v  a  2s  . c o  m*/
    hashCode = hashCode(<value>)
            
    // all constant expressions before a non-constant
    switch (hashCode) {
        case ...:
            if (<value> == <constant1>) {
               ...
            }
            else if (<value> == <constant2>) {
               ...
            }
            else if (...) {
            }
        case ...:
            ...
    }
            
    if (<value> == <non-constant1>) {
        ...
    }
    else if (<value> == <non-constant2>) {
        ...
    }
    ...
            
    // repeat with next sequence of constant expressions
     */

    Scope scope = generatorContext.getScope();

    // process value, else, and all when clauses
    RowExpression value = arguments.get(0);
    ByteCodeNode valueBytecode = generatorContext.generate(value);
    ByteCodeNode elseValue;

    List<RowExpression> whenClauses;
    RowExpression last = arguments.get(arguments.size() - 1);
    if (last instanceof CallExpression && ((CallExpression) last).getSignature().getName().equals("WHEN")) {
        whenClauses = arguments.subList(1, arguments.size());
        elseValue = new ByteCodeBlock().append(generatorContext.wasNull().set(constantTrue()))
                .pushJavaDefault(returnType.getJavaType());
    } else {
        whenClauses = arguments.subList(1, arguments.size() - 1);
        elseValue = generatorContext.generate(last);
    }

    // determine the type of the value and result
    Class<?> valueType = value.getType().getJavaType();

    // evaluate the value and store it in a variable
    LabelNode nullValue = new LabelNode("nullCondition");
    Variable tempVariable = scope.createTempVariable(valueType);
    ByteCodeBlock block = new ByteCodeBlock().append(valueBytecode)
            .append(ByteCodeUtils.ifWasNullClearPopAndGoto(scope, nullValue, void.class, valueType))
            .putVariable(tempVariable);

    ByteCodeNode getTempVariableNode = VariableInstruction.loadVariable(tempVariable);

    // build the statements
    elseValue = new ByteCodeBlock().visitLabel(nullValue).append(elseValue);
    // reverse list because current if statement builder doesn't support if/else so we need to build the if statements bottom up
    for (RowExpression clause : Lists.reverse(whenClauses)) {
        Preconditions.checkArgument(clause instanceof CallExpression
                && ((CallExpression) clause).getSignature().getName().equals("WHEN"));

        RowExpression operand = ((CallExpression) clause).getArguments().get(0);
        RowExpression result = ((CallExpression) clause).getArguments().get(1);

        // call equals(value, operand)
        Signature equalsFunction = generatorContext.getRegistry().resolveOperator(OperatorType.EQUAL,
                ImmutableList.of(value.getType(), operand.getType()));

        // TODO: what if operand is null? It seems that the call will return "null" (which is cleared below)
        // and the code only does the right thing because the value in the stack for that scenario is
        // Java's default for boolean == false
        // This code should probably be checking for wasNull after the call and "failing" the equality
        // check if wasNull is true
        ByteCodeNode equalsCall = generatorContext.generateCall(equalsFunction.getName(),
                generatorContext.getRegistry().getScalarFunctionImplementation(equalsFunction),
                ImmutableList.of(generatorContext.generate(operand), getTempVariableNode));

        ByteCodeBlock condition = new ByteCodeBlock().append(equalsCall)
                .append(generatorContext.wasNull().set(constantFalse()));

        elseValue = new IfStatement("when").condition(condition).ifTrue(generatorContext.generate(result))
                .ifFalse(elseValue);
    }

    return block.append(elseValue);
}

From source file:org.eclipse.incquery.runtime.localsearch.planner.util.CompilerHelper.java

/**
 * Extracts the operations from a SubPlan into a list of POperations in the order of execution
 * //  w  w  w  .  ja v  a 2  s. c om
 * @param plan the SubPlan from wich the POperations should be extracted
 * @return list of POperations extracted from the <code>plan</code>
 */
public static List<POperation> createOperationsList(SubPlan plan) {
    List<POperation> operationsList = Lists.newArrayList();
    while (plan.getParentPlans().size() > 0) {
        operationsList.add(plan.getOperation());
        SubPlan parentPlan = plan.getParentPlans().get(0);
        plan = parentPlan;
    }
    operationsList.add(plan.getOperation());

    return Lists.reverse(operationsList);
}