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

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

Introduction

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

Prototype

public static <T> T get(Iterable<T> iterable, int position) 

Source Link

Document

Returns the element at the specified position in an iterable.

Usage

From source file:org.obm.xml.AcceptDifferentNamespaceXMLUnit.java

private static String getNodeNameWithoutNamespace(String nodeName) {
    Iterable<String> splitedName = Splitter.on(':').omitEmptyStrings().split(nodeName);
    if (Iterables.size(splitedName) == 2) {
        nodeName = Iterables.get(splitedName, 1);
    } else {//  ww  w. j  av a 2 s  . com
        throw new IllegalArgumentException("The node name is illegal : " + nodeName);
    }
    return nodeName;
}

From source file:org.asoem.greyfish.core.actions.FemaleLikeMating.java

@Override
protected ImmutableACLMessage.Builder<A> createCFP(final AgentContext<A> context) {
    final int sensedMatesCount = Iterables.size(sensedMates);
    assert (sensedMatesCount > 0); // see #evaluateCondition(Simulation)

    final A receiver = Iterables.get(sensedMates, RandomGenerators.rng().nextInt(sensedMatesCount));
    sensedMates = ImmutableList.of();/*from   ww w .j ava 2 s.  com*/

    return ImmutableACLMessage.<A>builder().sender(context.agent()).performative(ACLPerformative.CFP)
            .ontology(ontology)
            // Choose randomly one receiver. Adding evaluates possible candidates as receivers will decrease the performance in high density populations!
            .addReceiver(receiver);
}

From source file:co.cask.cdap.internal.app.runtime.webapp.ServePathGenerator.java

private String findPath(String hostHeader, String path, String query) {
    // First try firstPathPart/src/restPath
    Iterable<String> pathParts = Splitter.on('/').limit(2).split(path);
    String servePath;/*www. j  a  v a  2s .  c  o  m*/
    if (Iterables.size(pathParts) > 1) {
        String part1 = Iterables.get(pathParts, 1);
        if (part1.startsWith(GATEWAY_PATH_V3) || part1.equals("status")) {
            return constructPath(part1, query);
        }

        servePath = String.format("%s/%s/%s%s%s", baseDir, hostHeader, Iterables.get(pathParts, 0), SRC_PATH,
                Iterables.get(pathParts, 1));
        if (fileExists.apply(servePath)) {
            return servePath;
        }

    } else if (Iterables.size(pathParts) == 1) {
        servePath = String.format("%s/%s/%s%s%s", baseDir, hostHeader, Iterables.get(pathParts, 0), SRC_PATH,
                "index.html");
        if (fileExists.apply(servePath)) {
            return servePath;
        }
    }

    // Next try src/path
    if (path.startsWith(GATEWAY_PATH_V3) || path.equals("status")) {
        return constructPath(path, query);
    }

    path = path.isEmpty() ? "index.html" : path;
    servePath = String.format("%s/%s%s%s", baseDir, hostHeader, SRC_PATH, path);
    if (fileExists.apply(servePath)) {
        return servePath;
    }

    return null;
}

From source file:fr.putnami.pwt.core.model.client.util.ModelUtils.java

public static <A, B> A resolveValue(Object bean, Model<B> model, Path path) {
    if (model == null || path.isEmpty()) {
        return (A) bean;
    }// w w  w .  j a v a 2 s.c  o m

    PathElement firstElement = path.get(0);
    String firstElementName = firstElement.getElementName();
    firstElementName = firstElementName == null ? Path.ROOT_PATH : firstElementName;
    Integer firstElementIndex = firstElement.getIndexKey();

    Object value = bean;
    Model<?> leafModel = model;
    if (leafModel instanceof ModelCollection) {
        leafModel = ((ModelCollection<?>) model).getLeafModel();
    }

    if (leafModel != null && !Path.ROOT_PATH.equals(firstElementName)) {
        value = leafModel.get(bean, firstElementName);
    }

    if (firstElementIndex != null && value instanceof Collection) {
        Collection<?> collection = (Collection<?>) value;
        if (collection.size() > firstElement.getIndexKey()) {
            value = Iterables.get(collection, firstElementIndex);
        } else {
            value = null;
        }
    }

    if (path.size() == 1) {
        return (A) value;
    }
    if (!Path.ROOT_PATH.equals(firstElementName)) {
        leafModel = leafModel.getProperty(firstElementName).getModel();
    }
    return ModelUtils.resolveValue(value, leafModel, path.subPath(1));
}

From source file:com.yahoo.yqlplus.engine.internal.tasks.GraphPlanner.java

/**
 * Plan a graph of tasks using the terminal step as a starting point. Discover all of the used steps from those roots, and then return the starting task.
 *///  w  ww .  ja  v  a2s  . c o  m
public ForkTask plan(Step root) {
    Map<Step, Node> nodes = Maps.newIdentityHashMap();

    discover(root, nodes);

    for (Map.Entry<Step, Node> e : nodes.entrySet()) {
        for (Step dep : e.getValue().inputs) {
            nodes.get(dep).deps.add(e.getKey());
        }
    }

    for (Map.Entry<Step, Node> e : nodes.entrySet()) {
        if (e.getValue().inputs.isEmpty()) {
            populateAvailable(e.getValue(), Sets.<Value>newIdentityHashSet(), nodes);
        }
    }

    boolean modified = true;
    List<Step> keys = Lists.newArrayList();
    while (modified) {
        modified = false;
        // we plan to modify the map, so copy the set of keys before iteration
        keys.clear();
        keys.addAll(nodes.keySet());
        for (Step key : keys) {
            Node node = nodes.get(key);
            if (node == null) {
                continue;
            }
            if (node.deps.size() == 1) {
                // if we are the only input to that dep...
                Step dep = Iterables.get(node.deps, 0);
                if (dep.getInputs().size() == 1) {
                    // then merge into that
                    Node target = nodes.get(dep);
                    node.todo.addAll(target.todo);
                    target.todo = node.todo;
                    target.inputs.remove(key);
                    for (Step p : node.inputs) {
                        nodes.get(p).deps.remove(key);
                        nodes.get(p).deps.add(dep);
                    }
                    target.inputs.addAll(node.inputs);
                    target.available.addAll(node.available);
                    nodes.remove(key);
                    modified = true;
                }
            }
        }
    }

    // so now all remaining nodes have 0 or > 1 deps
    // the 0 deps nodes are "ending" nodes, and the > deps nodes are fork nodes

    // set up the run & end nodes
    ForkTask start = new ForkTask();

    Map<Set<Step>, JoinTask> joinTasks = Maps.newHashMap();

    for (Node n : nodes.values()) {
        n.run = new RunTask(n.todo);
        n.run.setAvailable(n.available);
        if (n.inputs.size() > 1) {
            Set<Step> key = ImmutableSet.copyOf(n.inputs);
            JoinTask join = joinTasks.get(key);
            if (join == null) {
                join = new JoinTask();
                joinTasks.put(key, join);
                join.setAvailable(Sets.<Value>newIdentityHashSet());
            }
            join.addNext(n.run);
            join.getAvailable().addAll(n.available);
            n.next = join;
        } else {
            n.next = n.run;
        }
    }

    for (Node n : nodes.values()) {
        if (n.inputs.isEmpty()) {
            start.addNext(n.next);
        }
        for (Step dep : n.deps) {
            Node node = nodes.get(dep);
            if (node.next instanceof JoinTask) {
                ((JoinTask) node.next).getPriors().add(n.run);
            }
            n.run.addNext(node.next);
        }
    }

    return start;
}

From source file:org.jbb.board.web.forum.controller.AcpForumController.java

@RequestMapping(method = RequestMethod.GET)
public String forumGet(@RequestParam(value = "id", required = false) Long forumId, Model model) {
    ForumForm form = new ForumForm();

    List<ForumCategory> allCategories = boardService.getForumCategories();
    List<ForumCategoryRow> categoryDtos = allCategories.stream().map(this::mapToForumCategoryDto)
            .collect(Collectors.toList());
    model.addAttribute("availableCategories", categoryDtos);

    if (forumId == null) {
        model.addAttribute(EDIT_POSSIBLE, permissionService.checkPermission(CAN_ADD_FORUMS));
        form.setCategoryId(Iterables.get(allCategories, 0).getId());
    } else {//from  www  . j a  va2  s. c o m
        model.addAttribute(EDIT_POSSIBLE, permissionService.checkPermission(CAN_MODIFY_FORUMS));
        Forum forum = forumService.getForum(forumId);
        form.setId(forum.getId());
        form.setName(forum.getName());
        form.setDescription(forum.getDescription());
        form.setClosed(forum.isClosed());

        ForumCategory category = forumCategoryService.getCategoryWithForum(forum);
        form.setCategoryId(category.getId());
    }

    if (!model.containsAttribute(FORUM_FORM)) {
        model.addAttribute(FORUM_FORM, form);
    }
    return VIEW_NAME;
}

From source file:org.apache.whirr.service.chef.ChefClusterActionHandler.java

private static Predicate<String> isFirstChefRoleIn(final Iterable<String> roles) {
    return new Predicate<String>() {
        @Override/*  w  w w. jav a  2 s  . com*/
        public boolean apply(String arg0) {
            return Iterables
                    .get(Iterables.filter(roles, Predicates.containsPattern("^" + CHEF_ROLE_PREFIX + arg0)), 0)
                    .equals(CHEF_ROLE_PREFIX + arg0);
        }

        @Override
        public String toString() {
            return "isFirstChefRoleIn(" + roles + ")";

        }
    };
}

From source file:org.dcache.resilience.util.RandomSelectionStrategy.java

@Override
public String apply(Collection<String> collection) {
    if (collection.isEmpty()) {
        return null;
    }/*from   ww w  .j a va 2s  .c om*/

    return Iterables.get(collection, random.nextInt(collection.size()));
}

From source file:org.richfaces.webapp.PushServletContainerInitializer.java

/**
 * If Atmosphere is on classpath and {@link PushFilter} wasn't registered in current {@link ServletContext},
 *
 * the {@link PushServlet} will be registered automatically.
 */// ww w .ja  v a  2 s .com
@Override
public void onStartup(Set<Class<?>> clasess, ServletContext servletContext) throws ServletException {
    if (Boolean.valueOf(servletContext.getInitParameter(SKIP_SERVLET_REGISTRATION_PARAM))) {
        return;
    }

    if (!isAtmospherePresent()) {
        return;
    }

    if (hasFilterMapping(PushFilter.class, servletContext)) {
        return;
    }

    try {
        String pushHandlerMapping;

        ServletRegistration servletRegistration = getServletRegistration(PushServlet.class, servletContext);
        if (servletRegistration == null) {
            registerPushServlet(servletContext);
            pushHandlerMapping = PUSH_CONTEXT_DEFAULT_MAPPING;
        } else {
            pushHandlerMapping = Iterables.get(servletRegistration.getMappings(), 0);
        }

        servletContext.setAttribute(PushContextFactoryImpl.PUSH_HANDLER_MAPPING_ATTRIBUTE, pushHandlerMapping);
    } catch (Exception e) {
        servletContext.log(MessageFormat.format("Caught exception when registering RichFaces Push Servlet: {0]",
                e.getMessage()), e);
    }
}

From source file:org.jclouds.gogrid.compute.strategy.GoGridAddNodeWithTagStrategy.java

@Override
public NodeMetadata addNodeWithTag(String tag, String name, Template template) {
    Server addedServer = null;// ww w  . ja  v  a2  s  . co  m
    boolean notStarted = true;
    int numOfRetries = 20;
    // lock-free consumption of a shared resource: IP address pool
    while (notStarted) { // TODO: replace with Predicate-based thread
        // collision avoidance for
        // simplicity
        Set<Ip> availableIps = client.getIpServices().getIpList(new GetIpListOptions().onlyUnassigned()
                .onlyWithType(IpType.PUBLIC).inDatacenter(template.getLocation().getId()));
        if (availableIps.size() == 0)
            throw new RuntimeException("No public IPs available on this identity.");
        int ipIndex = new SecureRandom().nextInt(availableIps.size());
        Ip availableIp = Iterables.get(availableIps, ipIndex);
        try {
            addedServer = addServer(name, template, availableIp);
            notStarted = false;
        } catch (Exception e) {
            if (--numOfRetries == 0)
                Throwables.propagate(e);
            notStarted = true;
        }
    }
    if (template.getOptions().shouldBlockUntilRunning()) {
        serverLatestJobCompleted.apply(addedServer);
        client.getServerServices().power(addedServer.getName(), PowerCommand.START);
        serverLatestJobCompletedShort.apply(addedServer);
        addedServer = Iterables
                .getOnlyElement(client.getServerServices().getServersByName(addedServer.getName()));
    }
    return serverToNodeMetadata.apply(addedServer);
}