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.hbs.neo4j.importers.CsvImporter.java

private Iterable<String> getAndValidateHeader(String headerString, int minSize, String... keys) {
    boolean isHeaderValid = true;
    Iterable<String> header = Splitter.on(SEPARATOR).trimResults().split(headerString);
    if (Iterables.size(header) < minSize) {
        isHeaderValid = false;/*from  w w  w.ja v a  2s .c o  m*/
    } else {
        for (int i = 0; i < keys.length; i++) {
            if (keys[i].compareTo(Iterables.get(header, i)) != 0) {
                isHeaderValid = false;
            }
        }
    }
    if (!isHeaderValid) {
        StringBuilder exMsg = new StringBuilder("Invalid Header for CSV file.");
        exMsg.append(" Header have to start with \"");
        for (int i = 0; i < keys.length; i++) {
            exMsg.append(keys[i]).append(SEPARATOR);
        }
        exMsg.append(" followed by a list proprerty names separated by tabs.");
        throw new IllegalArgumentException(exMsg.toString());
    }
    return header;
}

From source file:org.jclouds.nodepool.internal.EagerNodePoolComputeServiceAdapter.java

@Override
public NodeWithInitialCredentials createNodeWithGroupEncodedIntoName(String group, String name,
        Template template) {//from  w w w  . j  ava2s  .c  o m
    int count = 1;
    synchronized (this) {
        TemplateOptions options = template.getOptions().clone();

        // if no user is provided we set the pool's user
        if (options.getLoginUser() == null) {
            options.overrideLoginCredentials(LoginCredentials
                    .fromCredentials(checkNotNull(initialCredentialsBuilder.build().getAdminCredentials())));
        }

        logger.info(">> assigning pool node to frontend group %s", group);
        Set<NodeMetadata> backendNodes = getBackendNodes();
        checkState(!backendNodes.isEmpty());
        Set<NodeMetadata> frontendNodes = metadataStore.loadAll(backendNodes);
        checkState(frontendNodes.size() + count <= maxSize,
                "cannot add more nodes to pool [requested: %s, current: %s, max: %s]", count,
                frontendNodes.size(), maxSize);

        SetView<NodeMetadata> availableNodes = Sets.difference(backendNodes, frontendNodes);

        if (availableNodes.size() < 1) {
            if (backendNodes.size() < maxSize && backendNodes.size() + count <= maxSize) {
                logger.info(
                        ">> all pool nodes are assigned, requiring additional nodes [requested: %s, current: %s, next: %s, max: %s]",
                        count, frontendNodes.size(), frontendNodes.size() + 1, maxSize);
                addToPool(count);
                // update backend and available sets, no need to update frontend
                backendNodes = getBackendNodes();
                availableNodes = Sets.difference(backendNodes, frontendNodes);
                logger.info("<< additional nodes added to the pool and ready");
            } else {
                logger.error("maximum pool size reached (%s)", maxSize);
                throw new IllegalStateException(String.format("maximum pool size reached (%s)", maxSize));
            }
        }
        NodeMetadata userNode = Iterables.get(availableNodes, 0);
        NodeMetadata node = metadataStore.store(userNode, options, group);
        logger.info("pool node assigned");
        return new NodeWithInitialCredentials(node);
    }
}

From source file:org.opencommercesearch.feed.CategoryFeed.java

@SuppressWarnings("unchecked")
private void buildHierarchyTokensAux(RepositoryItem category, String groupedString, List<String> placeHolder,
        int depth) {

    Set<RepositoryItem> parentCategories = (Set<RepositoryItem>) category
            .getPropertyValue(CategoryProperty.FIXED_PARENT_CATEGORIES);

    if (parentCategories == null || parentCategories.size() == 0) {
        Set<RepositoryItem> parentCatalogs = (Set<RepositoryItem>) category
                .getPropertyValue(CategoryProperty.PARENT_CATALOGS);
        if (parentCatalogs != null && parentCatalogs.size() > 0) {
            placeHolder.add(/*from  w ww.  j a  v  a2s .  c o m*/
                    depth + "." + Iterables.get(parentCatalogs, 0).getRepositoryId() + "." + groupedString);
        }
    } else {
        for (RepositoryItem parentCategory : parentCategories) {
            if (groupedString.isEmpty()) {
                buildHierarchyTokensAux(parentCategory, category.getItemDisplayName(), placeHolder, depth + 1);
            } else {
                buildHierarchyTokensAux(parentCategory, category.getItemDisplayName() + "." + groupedString,
                        placeHolder, depth + 1);
            }
        }
    }
}

From source file:com.reprezen.kaizen.oasparser.jsonoverlay.coll.CollectionStore.java

private String keyAtIndex(int index) {
    if (index >= 0 && index < overlays.size()) {
        return Iterables.get(overlays.keySet(), index);
    } else {/* ww  w.  j  ava  2  s  .co  m*/
        throw new OverlayException("Index out of bound for collection overlay");
    }
}

From source file:com.b2international.snowowl.datastore.cdo.CDOUtils.java

/**
 * Returns with the revisions for the given CDO IDs on a specified {@link CDOBranchPoint branch point}.
 * @param branchPoint the branch point to get the revisions.
 * @param ids the CDO IDs./*from  w  w  w.java 2  s.  c  o m*/
 * @return a list of CDO revisions.
 */
public static List<CDORevision> getRevisions(final CDOBranchPoint branchPoint, final Collection<CDOID> ids) {

    if (isEmpty(ids)) {
        return emptyList();
    }

    try {

        final CDOID cdoId = Iterables.get(ids, 0);
        StoreThreadLocal.setAccessor(getAccessor(cdoId));

        final List<CDORevision> revisions = newArrayList();
        final Iterator<List<CDOID>> itr = Iterators.partition(ids.iterator(), MAX_REVISION_LIMIT);
        final InternalCDORevisionManager revisionManager = getRevisionManager(cdoId);

        while (itr.hasNext()) {
            //get revisions at once but at most 1,000,000
            revisions.addAll(revisionManager.getRevisions(newArrayList(itr.next()), branchPoint,
                    CDORevision.UNCHUNKED, CDORevision.DEPTH_NONE, true, null));

        }

        return revisions;

    } finally {

        //release resources
        StoreThreadLocal.release();

    }

}

From source file:io.mycat.config.model.DataHostConfig.java

public String getRandomDataNode() {
    int index = (int) (Math.random() * dataNodes.size());
    return Iterables.get(dataNodes, index);
}

From source file:org.dspace.app.xmlui.aspect.submission.submit.CCLicenseStep.java

public void addBody(Body body)
        throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException {
    // Build the url to and from creative commons
    Item item = submission.getItem();/*from w w  w . j  av  a  2 s .c  o m*/
    Collection collection = submission.getCollection();
    String actionURL = contextPath + "/handle/" + collection.getHandle() + "/submit/" + knot.getId()
            + ".continue";
    Request request = ObjectModelHelper.getRequest(objectModel);
    boolean https = request.isSecure();
    String server = request.getServerName();
    int port = request.getServerPort();
    String exitURL = (https) ? "https://" : "http://";
    exitURL += server;
    if (!(port == 80 || port == 443))
        exitURL += ":" + port;

    exitURL += actionURL + "?submission-continue=" + knot.getId() + "&cc_license_url=[license_url]";
    Division div = body.addInteractiveDivision("submit-cclicense", actionURL, Division.METHOD_POST,
            "primary submission");
    div.setHead(T_submission_head);
    addSubmissionProgressList(div);
    CCLookup cclookup = new CCLookup();
    HttpSession session = request.getSession();

    // output the license selection options
    String selectedLicense = request.getParameter("licenseclass_chooser");
    List list = div.addList("licenseclasslist", List.TYPE_FORM);
    list.addItem(T_info1);
    list.setHead(T_head);
    list.addItem().addHidden("button_required");
    Select selectList = list.addItem().addSelect("licenseclass_chooser");
    selectList.setLabel(T_license);
    selectList.setEvtBehavior("submitOnChange");
    if (cclookup.getLicenses(ccLocale).size() == 1) {
        CCLicense cclicense = Iterables.get(cclookup.getLicenses(ccLocale), 0);
        selectList.addOption(cclicense.getLicenseId(), cclicense.getLicenseName());
        selectList.setOptionSelected(cclicense.getLicenseId());
        selectedLicense = cclicense.getLicenseId();
    } else {
        Iterator<CCLicense> iterator = cclookup.getLicenses(ccLocale).iterator();
        // build select List - first choice always 'choose a license', last always 'No license'
        selectList.addOption(T_select_change.getKey(), T_select_change);
        if (T_select_change.getKey().equals(selectedLicense)) {
            selectList.setOptionSelected(T_select_change.getKey());
        }
        while (iterator.hasNext()) {
            CCLicense cclicense = iterator.next();
            selectList.addOption(cclicense.getLicenseId(), cclicense.getLicenseName());
            if (selectedLicense != null && selectedLicense.equals(cclicense.getLicenseId())) {
                selectList.setOptionSelected(cclicense.getLicenseId());
            }
        }
    }

    if (ConfigurationManager.getBooleanProperty("cc.license.allow_no_license", false)) {
        selectList.addOption(T_no_license.getKey(), T_no_license);
        if (T_no_license.getKey().equals(selectedLicense)) {
            selectList.setOptionSelected(T_no_license.getKey());
        }
    }
    if (selectedLicense != null) {
        // output the license fields chooser for the license class type
        if (cclookup.getLicenseFields(selectedLicense, ccLocale) == null) {
            // do nothing
        } else {
            Iterator outerIterator = cclookup.getLicenseFields(selectedLicense, ccLocale).iterator();
            while (outerIterator.hasNext()) {
                CCLicenseField cclicensefield = (CCLicenseField) outerIterator.next();
                if (cclicensefield.getId().equals("jurisdiction"))
                    continue;
                List edit = div.addList("selectlist", List.TYPE_SIMPLE, "horizontalVanilla");
                if (cclicensefield.getId().equals("derivatives")) {
                    edit.addItem(message("xmlui.Submission.submit.CCLicenseStep.custom_question.derivatives"));
                } else {
                    edit.addItem(cclicensefield.getLabel());
                }
                edit.addItem().addFigure(contextPath + "/themes/Reference/images/information.png",
                        "javascript:void(0)", cclicensefield.getDescription(), "information");
                List subList = div.addList("sublist", List.TYPE_SIMPLE, "horizontalVanilla");
                Radio radio = subList.addItem().addRadio(cclicensefield.getId() + "_chooser");
                radio.setRequired();
                Iterator fieldMapIterator = cclicensefield.getEnum().entrySet().iterator();
                while (fieldMapIterator.hasNext()) {
                    Map.Entry pairs = (Map.Entry) fieldMapIterator.next();
                    String key = (String) pairs.getKey();
                    String value = (String) pairs.getValue();
                    radio.addOption(key, value);
                }
                div.addSimpleHTMLFragment(true, "&#160;");
            }
        }
    }
    Division statusDivision = div.addDivision("statusDivision");
    List statusList = statusDivision.addList("statusList", List.TYPE_FORM);
    String licenseUri = creativeCommonsService.getCCField("uri").ccItemValue(item);
    if (licenseUri != null) {
        statusList.addItem().addXref(licenseUri, licenseUri);
    } else {
        if (session.getAttribute("isFieldRequired") != null
                && session.getAttribute("isFieldRequired").equals("TRUE")
                && session.getAttribute("ccError") != null) {
            statusList.addItem().addHighlight("error")
                    .addContent(T_ccws_error.parameterize((String) session.getAttribute("ccError")));
            session.removeAttribute("ccError");
            session.removeAttribute("isFieldRequired");
        } else if (session.getAttribute("inProgress") != null
                && ((String) session.getAttribute("inProgress")).equals("TRUE")) {
            statusList.addItem().addHighlight("italic").addContent(T_save_changes);
        }
    }
    addControlButtons(statusList);

}

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

public static Set<String> getServingHostNames(InputSupplier<? extends InputStream> inputSupplier)
        throws Exception {
    try (JarInputStream jarInput = new JarInputStream(inputSupplier.getInput())) {
        Set<String> hostNames = Sets.newHashSet();
        JarEntry jarEntry;/*w  ww. j  ava 2  s.com*/
        String webappDir = Constants.Webapp.WEBAPP_DIR + "/";
        while ((jarEntry = jarInput.getNextJarEntry()) != null) {
            if (!jarEntry.isDirectory() && jarEntry.getName().startsWith(webappDir)
                    && jarEntry.getName().contains(ServePathGenerator.SRC_PATH)) {
                // Format is - webapp/host:port/[path/]src/files
                String webappHostName = Iterables.get(Splitter.on("/src/").split(jarEntry.getName()), 0);
                String hostName = Iterables.get(Splitter.on('/').limit(2).split(webappHostName), 1);

                hostNames.add(hostName);
            }
        }

        Set<String> registerNames = Sets.newHashSetWithExpectedSize(hostNames.size());
        for (String hostName : hostNames) {
            if (hostName.equals(ServePathGenerator.DEFAULT_DIR_NAME)) {
                LOG.warn("Not registering default service name; default service needs to have a routable path");
                continue;
            } else if (hostName.startsWith(DEFAULT_DIR_NAME_COLON)) {
                LOG.warn("Not registering default service name with explicit port - {}", hostName);
                continue;
            }

            registerNames.add(Networks.normalizeWebappDiscoveryName(hostName));
        }

        return registerNames;
    }
}

From source file:com.abiquo.api.handlers.RESTHandler.java

protected void createRESTBuilder(final MessageContext context, final LinkBuilders linksProcessor) {
    ServletContext servletContext = context.getAttribute(ServletContext.class);
    Map<String, IRESTBuilder> beans = WebApplicationContextUtils.getWebApplicationContext(servletContext)
            .getBeansOfType(IRESTBuilder.class);

    IRESTBuilder builder = Iterables.get(beans.values(), 0);
    context.setAttribute(REST_BUILDER_INTERFACE, builder.injectProcessor(linksProcessor));
}

From source file:org.apache.brooklyn.location.multi.MultiLocation.java

@SuppressWarnings("unchecked")
protected MachineProvisioningLocation<T> firstSubLoc() {
    return (MachineProvisioningLocation<T>) Iterables.get(getSubLocations(), 0);
}