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:org.apache.brooklyn.util.core.task.DynamicTasks.java

/** As {@link #drain(Duration, boolean)} waiting forever and throwing the first error 
 * (excluding errors in inessential tasks),
 * then returning the last task in the queue (which is guaranteed to have finished without error,
 * if this method returns without throwing) */
public static Task<?> waitForLast() {
    drain(null, true);//from  ww  w  . jav  a  2s.c  o  m
    // this call to last is safe, as the above guarantees everything will have run
    // (on errors the above will throw so we won't come here)
    List<Task<?>> q = DynamicTasks.getTaskQueuingContext().getQueue();
    return q.isEmpty() ? null : Iterables.getLast(q);
}

From source file:com.google.security.zynamics.binnavi.Database.MockClasses.MockSqlProvider.java

private ArrayList<IComment> getCommentInternally(final Integer commentId) {
    for (final ArrayList<IComment> commentList : comments.values()) {
        if (!commentList.isEmpty() && Iterables.getLast(commentList).getId().equals(commentId)) {
            return commentList;
        }/*from www. ja va2s.co m*/
    }
    return null;
}

From source file:com.comphenix.protocol.ProtocolLib.java

/**
 * Retrieve a error reporter that may be filtered by the configuration.
 * @return The new default error reporter.
 *///  w  w w .  j  av  a2s. c om
private ErrorReporter getFilteredReporter(ErrorReporter reporter) {
    return new DelegatedErrorReporter(reporter) {
        private int lastModCount = -1;
        private Set<String> reports = Sets.newHashSet();

        @Override
        protected Report filterReport(Object sender, Report report, boolean detailed) {
            try {
                String canonicalName = ReportType.getReportName(sender, report.getType());
                String reportName = Iterables.getLast(Splitter.on("#").split(canonicalName)).toUpperCase();

                if (config != null && config.getModificationCount() != lastModCount) {
                    // Update our cached set again
                    reports = Sets.newHashSet(config.getSuppressedReports());
                    lastModCount = config.getModificationCount();
                }

                // Cancel reports either on the full canonical name, or just the report name
                if (reports.contains(canonicalName) || reports.contains(reportName))
                    return null;

            } catch (Exception e) {
                // Only report this with a minor message
                logger.warning("Error filtering reports: " + e.toString());
            }
            // Don't filter anything
            return report;
        }
    };
}

From source file:org.opendaylight.netvirt.openstack.netvirt.sfc.standalone.openflow13.NetvirtSfcStandaloneOF13Provider.java

private void processAclEntry(Ace entry, Bridges bridges, boolean write) {
    Matches matches = entry.getMatches();
    if (matches == null) {
        LOG.warn("processAclEntry: matches not found");
        return;//  w  w w  . ja  va2s .co m
    }

    RenderedServicePath rsp = getRenderedServicePath(entry);
    if (rsp == null) {
        LOG.warn("Failed to get renderedServicePatch for entry: {}", entry);
        return;
    }

    LOG.info("processAclEntry: RSP: {}", rsp);
    List<RenderedServicePathHop> pathHopList = rsp.getRenderedServicePathHop();
    if (pathHopList.isEmpty()) {
        LOG.warn("Service Path = {} has empty hops!!", rsp.getName());
        return;
    }

    for (Bridge bridge : bridges.getBridge()) {
        if (bridge.getDirection().getIntValue() == 0) {
            Node bridgeNode = getBridgeNode(bridge.getName());
            if (bridgeNode == null) {
                LOG.debug("processAclEntry: bridge {} not yet configured. Skip processing !!",
                        bridge.getName());
                continue;
            }

            long tunnelOfPort = southbound.getOFPort(bridgeNode, CLIENT_GPE_PORT_NAME);
            if (tunnelOfPort == 0L) {
                LOG.error("programAclEntry: Could not identify tunnel port {} -> OF ({}) on {}",
                        CLIENT_GPE_PORT_NAME, tunnelOfPort, bridgeNode);
                return;
            }

            long localOfPort = southbound.getOFPort(bridgeNode, CLIENT_PORT_NAME);
            if (localOfPort == 0L) {
                LOG.error("programAclEntry: Could not identify local port {} -> OF ({}) on {}",
                        CLIENT_PORT_NAME, localOfPort, bridgeNode);
                return;
            }

            // Find the first Hop within an RSP.
            // The classifier flow needs to send all matched traffic to this first hop SFF.
            RenderedServicePathFirstHop firstRspHop = SfcProviderRenderedPathAPI
                    .readRenderedServicePathFirstHop(new RspName(rsp.getName()));

            LOG.debug("First Hop IPAddress = {}, Port = {}", firstRspHop.getIp().getIpv4Address().getValue(),
                    firstRspHop.getPort().getValue());

            NshUtils nshHeader = new NshUtils();
            // C1 is the normal overlay dest ip and c2 is the vnid
            // Hardcoded for now, netvirt integration will have those values
            nshHeader.setNshMetaC1(NshUtils.convertIpAddressToLong(new Ipv4Address(TUNNEL_DST)));
            nshHeader.setNshMetaC2(Long.parseLong(TUNNEL_VNID));
            nshHeader.setNshNsp(rsp.getPathId());

            RenderedServicePathHop firstHop = pathHopList.get(0);
            nshHeader.setNshNsi(firstHop.getServiceIndex());
            nshHeader.setNshTunIpDst(firstRspHop.getIp().getIpv4Address());
            nshHeader.setNshTunUdpPort(firstRspHop.getPort());
            LOG.debug("The Nsh Header = {}", nshHeader);

            handleLocalInPort(southbound.getDataPathId(bridgeNode), rsp.getPathId().toString(), localOfPort,
                    TABLE_0_CLASSIFIER, TABLE_3_INGR_ACL, matches, true);

            handleSfcClassiferFlows(southbound.getDataPathId(bridgeNode), TABLE_3_INGR_ACL, entry.getRuleName(),
                    matches, nshHeader, tunnelOfPort, true);
        } else {
            Node bridgeNode = getBridgeNode(bridge.getName());
            if (bridgeNode == null) {
                LOG.debug("processAclEntry: bridge {} not yet configured. Skip processing !!",
                        bridge.getName());
                continue;
            }

            long tunnelOfPort = southbound.getOFPort(bridgeNode, SERVER_GPE_PORT_NAME);
            if (tunnelOfPort == 0L) {
                LOG.error("programAclEntry: Could not identify tunnel port {} -> OF ({}) on {}",
                        SERVER_GPE_PORT_NAME, tunnelOfPort, bridgeNode);
                return;
            }

            long localOfPort = southbound.getOFPort(bridgeNode, SERVER_PORT_NAME);
            if (localOfPort == 0L) {
                LOG.error("programAclEntry: Could not identify local port {} -> OF ({}) on {}",
                        SERVER_PORT_NAME, localOfPort, bridgeNode);
                return;
            }

            RenderedServicePathHop lastRspHop = Iterables.getLast(rsp.getRenderedServicePathHop());

            LOG.debug("programAclEntry: Last Hop #: {}, nsi: {}", lastRspHop.getHopNumber().intValue(),
                    lastRspHop.getServiceIndex().intValue() - 1);

            NshUtils nshHeader = new NshUtils();
            nshHeader.setNshNsp(rsp.getPathId());
            nshHeader.setNshNsi((short) (lastRspHop.getServiceIndex().intValue() - 1));
            nshHeader.setNshMetaC2(Long.parseLong(TUNNEL_VNID));
            LOG.debug("programAclEntry: The Nsh Header = {}", nshHeader);

            //handleLocalEgressPort(southbound.getDataPathId(bridgeNode), rsp.getPathId().toString(), localOfPort,
            //        TABLE_0_CLASSIFIER, TABLE_3_INGR_ACL, true);

            handleEgressSfcClassiferFlows(southbound.getDataPathId(bridgeNode), TABLE_0_CLASSIFIER,
                    entry.getRuleName(), matches, nshHeader, tunnelOfPort, localOfPort, true);
        }
    }
}

From source file:org.apache.stratos.cloud.controller.iaases.AWSEC2Iaas.java

@Override
public synchronized String associateAddress(NodeMetadata node) {

    IaasProvider iaasInfo = getIaasProvider();

    ComputeServiceContext context = iaasInfo.getComputeService().getContext();

    ElasticIPAddressApi elasticIPAddressApi = context.unwrapApi(AWSEC2Api.class).getElasticIPAddressApi().get();
    String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);

    String ip = null;//from   ww w. j av  a 2s.  c om

    // first try to find an unassigned IP.
    ArrayList<PublicIpInstanceIdPair> unassignedIps = Lists
            .newArrayList(Iterables.filter(elasticIPAddressApi.describeAddressesInRegion(region, new String[0]),
                    new Predicate<PublicIpInstanceIdPair>() {

                        @Override
                        public boolean apply(PublicIpInstanceIdPair arg0) {
                            return arg0.getInstanceId() == null;
                        }

                    }));

    if (!unassignedIps.isEmpty()) {
        // try to prevent multiple parallel launches from choosing the same
        // ip.
        Collections.shuffle(unassignedIps);
        ip = Iterables.getLast(unassignedIps).getPublicIp();
    }

    // if no unassigned IP is available, we'll try to allocate an IP.
    if (ip == null || ip.isEmpty()) {
        try {
            ip = elasticIPAddressApi.allocateAddressInRegion(region);
            log.info("Allocated ip [" + ip + "]");

        } catch (Exception e) {
            String msg = "Failed to allocate an IP address. All IP addresses are in use.";
            log.error(msg, e);
            throw new CloudControllerException(msg, e);
        }
    }

    String id = node.getProviderId();

    // wait till the fixed IP address gets assigned - this is needed before
    // we associate a
    // public IP

    while (node.getPrivateAddresses() == null) {
        CloudControllerUtil.sleep(1000);
    }

    int retries = 0;
    while (retries < 12 && !associatePublicIp(elasticIPAddressApi, region, ip, id)) {

        // wait for 5s
        CloudControllerUtil.sleep(5000);
        retries++;
    }

    log.debug("Successfully associated an IP address " + ip + " for node with id: " + node.getId());

    return ip;

}

From source file:com.github.rinde.logistics.pdptw.mas.comm.RtSolverBidder.java

@SuppressWarnings({ "null", "unused" })
void reauction() {
    if (!reauctionsEnabled || assignedParcels.isEmpty()) {
        return;//ww  w  . j ava  2s.  com
    }
    LOGGER.trace("{} Considering a reauction, assignedParcels: {}.", decorator, assignedParcels.size());
    final ImmutableList<Parcel> currentRoute = ImmutableList.copyOf(((Truck) vehicle.get()).getRoute());
    final GlobalStateObject state = solverHandle.get()
            .getCurrentState(SolveArgs.create().noCurrentRoutes().useParcels(assignedParcels));
    final StatisticsDTO stats = Solvers.computeStats(state, ImmutableList.of(currentRoute));

    final Parcel lastReceivedParcel = Iterables.getLast(assignedParcels);

    if (!reauctioning.get()) {
        // find all swappable parcels, a parcel can be swapped if it is not yet in
        // cargo (it must occur twice in route for that)
        // TODO filter out parcels that will be visited within several seconds
        // (length of auction)
        final Multiset<Parcel> routeMultiset = LinkedHashMultiset.create(currentRoute);
        final Set<Parcel> swappableParcels = new LinkedHashSet<>();
        for (final Parcel ap : assignedParcels) {
            if (!pdpModel.get().getParcelState(ap).isPickedUp()
                    && !pdpModel.get().getParcelState(ap).isTransitionState()
                    && !state.getVehicles().get(0).getDestination().asSet().contains(ap)
                    && !ap.equals(lastReceivedParcel)) {
                swappableParcels.add(ap);
            }
        }

        final double baseline = objectiveFunction.computeCost(stats);
        double lowestCost = baseline;
        @Nullable
        Parcel toSwap = null;

        LOGGER.trace("Compute cost of swapping");
        for (final Parcel sp : swappableParcels) {
            final List<Parcel> newRoute = new ArrayList<>();
            newRoute.addAll(currentRoute);
            newRoute.removeAll(Collections.singleton(sp));
            final double cost = objectiveFunction
                    .computeCost(Solvers.computeStats(state, ImmutableList.of(ImmutableList.copyOf(newRoute))));
            if (cost < lowestCost) {
                lowestCost = cost;
                toSwap = sp;
            }
        }

        // we have found the most expensive parcel in the route, that is, removing
        // this parcel from the route will yield the greatest cost reduction.
        if (toSwap != null && !reauctioning.get() && !toSwap.equals(lastReceivedParcel)) {

            final Auctioneer<DoubleBid> auct = parcelAuctioneers.get(toSwap);
            if (auct.getLastUnsuccessTime() > 0
                    && state.getTime() - auct.getLastUnsuccessTime() <= reauctionCooldownPeriod) {
                LOGGER.trace("Not reauctioning, was unsuccessful too recently");
                return;
            }

            // try to reauction
            reauctioning.set(true);
            LOGGER.trace("Found most expensive parcel for reauction: {}.", toSwap);

            final double bidValue = bidFunction.computeBidValue(currentRoute.size(), lowestCost - baseline);
            final DoubleBid initialBid = DoubleBid.create(state.getTime(), decorator, toSwap, bidValue);

            auct.auctionParcel(decorator, state.getTime(), initialBid, new Listener() {
                @Override
                public void handleEvent(Event e) {
                    reauctioning.set(false);
                }
            });
        }
    }
}

From source file:org.sosy_lab.cpachecker.cpa.bam.BAMTransferRelationWithFixPointForRecursion.java

@Override
protected Collection<AbstractState> analyseBlockAndExpand(final AbstractState initialState,
        final Precision pPrecision, final Block outerSubtree, final AbstractState reducedInitialState,
        final Precision reducedInitialPrecision)
        throws CPAException, InterruptedException, CPATransferException {

    final CFANode node = currentBlock.getCallNode();
    final Collection<AbstractState> resultStates;

    if (!(node instanceof FunctionEntryNode) || isHeadOfMainFunction(node)) {
        // block is a loop-block
        // or we are at the start of the main-block, we do not need the rebuilding-part for main,
        // so we use a simplified version of function-handling and handle it like a loop-block
        resultStates = super.analyseBlockAndExpand(initialState, pPrecision, outerSubtree, reducedInitialState,
                reducedInitialPrecision);

    } else {// w ww.  j  ava 2  s.  c  o m
        // function-entry and old block --> begin new block
        // TODO match only recursive function, not all functions

        resultStates = analyseBlockAndExpandForRecursion(initialState, pPrecision, node, outerSubtree,
                reducedInitialState, reducedInitialPrecision);

        // current location is "before" the function-return-edge.
    }

    if (recursionSeen) {
        // we are returning from an recursive call.
        // if we would need to do further analysis for recursion later (fixpoint-analysis!),
        // we need to know, where to update the reachedset --> store initialState for later usage
        potentialRecursionUpdateStates.put(initialState, Iterables.getLast(stack));
    }

    return resultStates;
}

From source file:com.google.api.explorer.client.FullView.java

@Override
public void setContext(ExplorerContext context) {
    presenter.setContext(context);/*from w  ww . ja  va2  s  .c  o  m*/

    // Fill in the entry list widget, only the collections that have entries will be shown
    drillDownNav.setVisible(context.isEntryListVisible());
    drillDownNav.clear();

    if (context.isEntryListVisible()) {
        populateHistoryItems("", context.getHistoryItems(), drillDownNav);
        populateServiceEntries(sortServices(context.getServicesList()), drillDownNav,
                context.getServiceTagProcessor());
        populateServiceMethods(context.getService(), context.getMethods(), drillDownNav);
    }

    // Fill in the detail pane.
    detailPane.setVisible(context.isHistoryItemVisible() || context.isMethodFormVisible());
    detailPane.clear();

    if (context.isHistoryItemVisible()) {
        HistoryItem item = Iterables.getOnlyElement(context.getHistoryItems());
        EmbeddedHistoryItemView view = generateHistoryItemView(item);

        detailPane.add(view);
    } else if (context.isMethodFormVisible()) {
        ApiMethod method = context.getMethod();

        // Wrap the callback given by the context so that we may also be notified when a request is
        // finished. Pass through events to the original callback.
        CallbackWrapper cbWrapper = new CallbackWrapper();
        cbWrapper.delegate = context.getRequestFinishedCallback();
        cbWrapper.methodName = method.getId();

        // Create the view of the request editor and the single history item.
        EmbeddedView view = new EmbeddedView(authManager, context.getService(), method,
                context.getMethodParameters(), cbWrapper, HIDE_AUTH, analytics);

        cbWrapper.localView = view;

        // If this context came bundled with a history item, that means the navigation references a
        // previous executed request, and we should show the result.
        List<HistoryItem> historyItems = context.getHistoryItems();
        if (!historyItems.isEmpty()) {
            view.showHistoryItem(generateHistoryItemView(Iterables.getLast(historyItems)));
        }

        detailPane.add(view);
    }

    // Show the search results.
    searchResults.setVisible(context.isSearchResultsVisible());
    searchResults.clear();
    searchErrorPanel.setVisible(false);
    if (context.isSearchResultsVisible()) {
        populateSearchResults(context.getSearchResults(), context.getServiceTagProcessor());
    }

    // Show the auth panel.
    authViewPlaceholder.setVisible(context.isAuthVisible());
    authViewPlaceholder.clear();
    if (context.isAuthVisible()) {
        showAuth(context.getService(), context.getMethod());
    }

    // Show the documentation link.
    docsContainer.setVisible(context.isDocsLinkVisible());
    docsContainer.clear();
    if (context.isDocsLinkVisible()) {
        showDocumentationLink("the " + context.getService().displayTitle(),
                context.getService().getDocumentationLink());
    }

    // Show the title.
    boolean showContentTitle = context.getContentTitles() != null;
    if (showContentTitle) {
        generateBreadcrumbs(detailTitleContainer, context.getContentTitles());
    }

    // Show the detail header.
    detailHeader.setVisible(showContentTitle || context.isAuthVisible());

    // Show the back button.
    backButton.setVisible(context.getParentUrl() != null);

    // Highlight the navigation item which was the root of our navigation.
    highlightNavigationItem(context.getRootNavigationItem());
}

From source file:org.jetbrains.jet.plugin.parameterInfo.JetFunctionParameterInfoHandler.java

private static boolean isIndexValid(List<ValueParameterDescriptor> valueParameters, int index) {
    // Index is within range of parameters or last parameter is vararg
    return index < valueParameters.size() || (valueParameters.size() > 0
            && Iterables.getLast(valueParameters).getVarargElementType() != null);
}

From source file:com.google.security.zynamics.binnavi.disassembly.CommentManager.java

/**
 * This function provides the append comment functionality for any given Implementation of a
 * {@link CommentingStrategy}. It uses the methods of the interface to only have one algorithm
 * with different objects that can be commented.
 *
 * @param strategy The {@link CommentingStrategy} which holds the function forwarders.
 * @param commentText The commenting text to append.
 *
 * @return The generated comment.//from  ww w .j  a  v  a  2 s. com
 *
 * @throws CouldntSaveDataException if the comment could not be stored in the database.
 * @throws CouldntLoadDataException if the list of comments now associated with the commented
 *         object could not be loaded from the database.
 */
private synchronized List<IComment> appendComment(final CommentingStrategy strategy, final String commentText)
        throws CouldntSaveDataException, CouldntLoadDataException {

    final IUser user = CUserManager.get(provider).getCurrentActiveUser();

    final List<IComment> currentComments = new ArrayList<IComment>();

    if (strategy.isStored()) {
        currentComments.addAll(strategy.appendComment(commentText, user.getUserId()));
    } else {
        currentComments.addAll(strategy.getComments() == null ? new ArrayList<IComment>()
                : Lists.newArrayList(strategy.getComments()));
        final IComment parent = currentComments.isEmpty() ? null : Iterables.getLast(currentComments);
        final IComment newComment = new CComment(null, user, parent, commentText);
        currentComments.add(newComment);
    }

    strategy.saveComments(currentComments);
    for (final IComment comment : currentComments) {
        commentIdToComment.put(comment.getId(), comment);
    }

    for (final CommentListener listener : listeners) {
        try {
            strategy.sendAppendedCommentNotifcation(listener, Iterables.getLast(currentComments));
        } catch (final Exception exception) {
            CUtilityFunctions.logException(exception);
        }
    }
    return currentComments;
}