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

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

Introduction

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

Prototype

public static <T> T getLast(Iterable<T> iterable) 

Source Link

Document

Returns the last element of iterable .

Usage

From source file:com.google.security.zynamics.binnavi.Database.PostgreSQL.Savers.PostgreSQLEdgeSaver.java

/**
 * Writes the data from the edge objects to the edges table.
 * //from w w  w.  j a va2 s .  c  o m
 * @param connection Connection to a PostgreSQL database.
 * @param edges The edges to write.
 * 
 * @throws SQLException Thrown if storing the edges failed.
 */
private static void fillEdgesTable(final CConnection connection, final List<INaviEdge> edges)
        throws SQLException {

    final String query = "INSERT INTO " + CTableNames.EDGES_TABLE
            + "(source_node_id, target_node_id, x1, y1, x2, y2, type, "
            + "color, visible, selected, comment_id) VALUES " + "( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";

    final PreparedStatement preparedStatement = connection.getConnection().prepareStatement(query,
            PreparedStatement.RETURN_GENERATED_KEYS);

    try {
        for (final INaviEdge edge : edges) {
            preparedStatement.setInt(1, edge.getSource().getId());
            preparedStatement.setInt(2, edge.getTarget().getId());
            preparedStatement.setDouble(3, edge.getX1());
            preparedStatement.setDouble(4, edge.getY1());
            preparedStatement.setDouble(5, edge.getX2());
            preparedStatement.setDouble(6, edge.getY2());
            preparedStatement.setObject(7, edge.getType().toString().toLowerCase(), Types.OTHER);
            preparedStatement.setInt(8, edge.getColor().getRGB());
            preparedStatement.setBoolean(9, edge.isVisible());
            preparedStatement.setBoolean(10, edge.isSelected());
            if (edge.getLocalComment() == null) {
                preparedStatement.setNull(11, Types.INTEGER);
            } else {
                preparedStatement.setInt(11, Iterables.getLast(edge.getLocalComment()).getId());
            }

            preparedStatement.addBatch();
        }
        preparedStatement.executeBatch();

        final ResultSet resultSet = preparedStatement.getGeneratedKeys();

        for (final INaviEdge edge : edges) {
            if (resultSet.next()) {
                edge.setId(resultSet.getInt(1));
            } else {
                throw new IllegalStateException(
                        "Error: The number of keys generated does not match the number of edges");
            }
        }
    } catch (final SQLException exception) {
        CUtilityFunctions.logException(exception);
        CUtilityFunctions.logException(exception.getNextException());
    } finally {
        preparedStatement.close();
    }
}

From source file:com.google.devtools.build.lib.syntax.UserDefinedFunction.java

@Override
public Object call(Object[] arguments, FuncallExpression ast, Environment env)
        throws EvalException, InterruptedException {
    if (!env.mutability().isMutable()) {
        throw new EvalException(getLocation(), "Trying to call in frozen environment");
    }//w  w w. j  a  v a 2 s.com
    if (env.getStackTrace().contains(this)) {
        throw new EvalException(getLocation(),
                String.format("Recursion was detected when calling '%s' from '%s'", getName(),
                        Iterables.getLast(env.getStackTrace()).getName()));
    }

    Profiler.instance().startTask(ProfilerTask.SKYLARK_USER_FN, getName());
    try {
        env.enterScope(this, ast, definitionGlobals);
        ImmutableList<String> names = signature.getSignature().getNames();

        // Registering the functions's arguments as variables in the local Environment
        int i = 0;
        for (String name : names) {
            env.update(name, arguments[i++]);
        }

        try {
            for (Statement stmt : statements) {
                if (stmt instanceof ReturnStatement) {
                    // Performance optimization.
                    // Executing the statement would throw an exception, which is slow.
                    return ((ReturnStatement) stmt).getReturnExpression().eval(env);
                } else {
                    stmt.exec(env);
                }
            }
        } catch (ReturnStatement.ReturnException e) {
            return e.getValue();
        }
        return Runtime.NONE;
    } finally {
        Profiler.instance().completeTask(ProfilerTask.SKYLARK_USER_FN);
        env.exitScope();
    }
}

From source file:org.jclouds.vcloud.functions.OrgNameAndCatalogNameToEndpoint.java

@SuppressWarnings("unchecked")
public URI apply(Object from) {
    Iterable<Object> orgCatalog = (Iterable<Object>) checkNotNull(from, "args");
    Object org = Iterables.get(orgCatalog, 0);
    Object catalog = Iterables.get(orgCatalog, 1);
    if (org == null && catalog == null)
        return defaultUri;
    else if (org == null)
        org = defaultOrg;/*from w  ww  . j a va2s . c o  m*/

    try {
        Map<String, ReferenceType> catalogs = checkNotNull(orgMap.get().get(org)).getCatalogs();
        return catalog == null ? Iterables.getLast(catalogs.values()).getHref()
                : catalogs.get(catalog).getHref();
    } catch (NullPointerException e) {
        throw new NoSuchElementException(org + "/" + catalog + " not found in " + orgMap.get());
    }
}

From source file:org.jclouds.vcloud.functions.OrgNameAndVDCNameToEndpoint.java

@SuppressWarnings("unchecked")
public URI apply(Object from) {
    Iterable<Object> orgVdc = (Iterable<Object>) checkNotNull(from, "args");
    Object org = Iterables.get(orgVdc, 0);
    Object vdc = Iterables.get(orgVdc, 1);
    if (org == null && vdc == null)
        return defaultUri;
    else if (org == null)
        org = defaultOrg;/*  w  w  w  .  j  a v  a2  s  . c  om*/

    try {
        Map<String, ReferenceType> vdcs = checkNotNull(orgNameToVDCEndpoint.get().get(org)).getVDCs();
        return vdc == null ? Iterables.getLast(vdcs.values()).getHref() : vdcs.get(vdc).getHref();
    } catch (NullPointerException e) {
        throw new NoSuchElementException(org + "/" + vdc + " not found in " + orgNameToVDCEndpoint.get());
    }
}

From source file:com.google.devtools.build.lib.query2.engine.RegexFilterExpression.java

@Override
public <T> void eval(final QueryEnvironment<T> env, VariableContext<T> context, QueryExpression expression,
        final List<Argument> args, Callback<T> callback) throws QueryException, InterruptedException {
    final Pattern compiledPattern;
    try {//w w w  . ja v  a 2s .  co  m
        compiledPattern = Pattern.compile(getPattern(args));
    } catch (IllegalArgumentException e) {
        throw new QueryException(expression, "illegal pattern regexp in '" + this + "': " + e.getMessage());
    }

    // Note that Patttern#matcher is thread-safe and so this Predicate can safely be used
    // concurrently.
    final Predicate<T> matchFilter = new Predicate<T>() {
        @Override
        public boolean apply(T target) {
            for (String str : getFilterStrings(env, args, target)) {
                if ((str != null) && compiledPattern.matcher(str).find()) {
                    return true;
                }
            }
            return false;
        }
    };

    env.eval(Iterables.getLast(args).getExpression(), context, filteredCallback(callback, matchFilter));
}

From source file:org.killbill.billing.plugin.adyen.api.ExpiredPaymentPolicy.java

public PaymentTransactionInfoPlugin latestTransaction(
        final List<PaymentTransactionInfoPlugin> paymentTransactions) {
    return Iterables.getLast(paymentTransactions);
}

From source file:com.lyncode.jtwig.tree.tags.Filter.java

@Override
public void render(RenderStream renderStream, JtwigContext context) throws RenderException {
    RenderStream local = new RenderStream(new ByteArrayOutputStream());
    content.render(local, context);/*from   w  w  w.  j a v  a 2  s. co m*/
    Expression constant = new Constant<>(local.getOuputStream().toString());

    this.expressions.get(0).addArgument(0, constant);

    try {
        renderStream.write(Iterables.getLast(this.expressions).calculate(context).toString().getBytes());
    } catch (IOException | CalculateException e) {
        throw new RenderException(e);
    }
}

From source file:org.eclipse.tracecompass.lttng2.ust.core.analysis.debuginfo.UstDebugInfoSourceAspect.java

/**
 * Get the source callsite (the full {@link TmfCallsite} information) from a
 * binary callsite./*from w  ww.  j  a v  a  2s . c  om*/
 *
 * @param trace
 *            The trace, which may contain trace-specific configuration
 * @param bc
 *            The binary callsite
 * @return The source callsite, which sould include file name, function name
 *         and line number
 */
public static @Nullable SourceCallsite getSourceCallsite(LttngUstTrace trace, BinaryCallsite bc) {
    Iterable<SourceCallsite> callsites = FileOffsetMapper
            .getCallsiteFromOffset(new File(bc.getBinaryFilePath()), bc.getBuildId(), bc.getOffset());

    if (callsites == null || Iterables.isEmpty(callsites)) {
        return null;
    }
    /*
     * TMF only supports the notion of one callsite per event at the moment.
     * We will take the "deepest" one in the stack, which should refer to
     * the initial, non-inlined location.
     */
    SourceCallsite callsite = Iterables.getLast(callsites);

    /*
     * Apply the path prefix again, this time on the path given from
     * addr2line. If applicable.
     */
    String pathPrefix = trace.getSymbolProviderConfig().getActualRootDirPath();
    if (pathPrefix.isEmpty()) {
        return callsite;
    }

    String fullFileName = (pathPrefix + callsite.getFileName());
    return new SourceCallsite(fullFileName, callsite.getFunctionName(), callsite.getLineNumber());
}

From source file:com.android.tools.idea.editors.theme.attributes.editors.ColorRendererEditor.java

@Override
protected void updateComponent(@NotNull ThemeEditorContext context, @NotNull ResourceComponent component,
        @NotNull EditedStyleItem item) {
    ResourceResolver resourceResolver = context.getResourceResolver();
    assert resourceResolver != null;

    final List<Color> colors = ResourceHelper.resolveMultipleColors(resourceResolver, item.getSelectedValue(),
            context.getProject());/*from w  w w. ja v a2  s.  c  o  m*/
    SwatchComponent.SwatchIcon icon;
    if (colors.isEmpty()) {
        icon = SwatchComponent.WARNING_ICON;
    } else {
        icon = new SwatchComponent.ColorIcon(Iterables.getLast(colors));
        icon.setIsStack(colors.size() > 1);
    }
    component.setSwatchIcon(icon);
    component.setNameText(item.getQualifiedName());
    component.setValueText(item.getValue());

    if (!colors.isEmpty()) {
        Color color = Iterables.getLast(colors);
        String attributeName = item.getName();
        ImmutableMap<String, Color> contrastColorsWithDescription = ColorUtils
                .getContrastColorsWithDescription(context, attributeName);
        component.setWarning(ColorUtils.getContrastWarningMessage(contrastColorsWithDescription, color,
                ColorUtils.isBackgroundAttribute(attributeName)));
    } else {
        component.setWarning(null);
    }
}

From source file:org.jclouds.trmk.vcloud_0_8.suppliers.OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault.java

@Override
public ReferenceType apply(Iterable<ReferenceType> referenceTypes) {
    checkNotNull(referenceTypes, "referenceTypes");
    checkArgument(Iterables.size(referenceTypes) > 0,
            "No referenceTypes corresponding to configuration key %s present", configurationKey);
    if (Iterables.size(referenceTypes) == 1)
        return Iterables.getLast(referenceTypes);
    String namingPattern = valueOfConfigurationKeyOrNull.apply(configurationKey);
    if (namingPattern != null) {
        return findReferenceTypeWithNameMatchingPattern(referenceTypes, namingPattern);
    } else {//w  w w  .j a  v  a2s.  c  o  m
        return defaultReferenceType(referenceTypes);
    }
}