Example usage for java.util Set iterator

List of usage examples for java.util Set iterator

Introduction

In this page you can find the example usage for java.util Set iterator.

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this set.

Usage

From source file:com.datatorrent.contrib.kafka.KafkaMetadataUtil.java

/**
 * @param brokerSet//www .java2s  .  co  m
 * @param topic
 * @return TopicMetadata for this specific topic via the brokerList<br>
 * null if topic is not found
 */
public static TopicMetadata getTopicMetadata(Set<String> brokerSet, String topic) {
    SimpleConsumer mdConsumer = null;
    if (brokerSet == null || brokerSet == null || brokerSet.size() == 0) {
        return null;
    }
    try {
        for (Iterator<String> iterator = brokerSet.iterator(); iterator.hasNext();) {
            String broker = iterator.next();
            logger.debug("Try to get Metadata for topic {} broker {}", topic, broker);
            try {
                mdConsumer = new SimpleConsumer(broker.split(":")[0], Integer.parseInt(broker.split(":")[1]),
                        timeout, bufferSize, mdClientId);

                List<String> topics = new ArrayList<String>(1);
                topics.add(topic);
                kafka.javaapi.TopicMetadataRequest req = new kafka.javaapi.TopicMetadataRequest(topics);
                TopicMetadataResponse resp = mdConsumer.send(req);
                List<TopicMetadata> metaData = resp.topicsMetadata();
                for (TopicMetadata item : metaData) {
                    // There is at most 1 topic for this method
                    return item;
                }
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Wrong format for broker url, should be \"broker1:port1\"");
            } catch (Exception e) {
                logger.warn("Broker {} is unavailable or in bad state!", broker);
                // skip and try next broker
            }
        }

        return null;
    } finally {
        if (mdConsumer != null) {
            mdConsumer.close();
        }
    }
}

From source file:com.github.nakamurakj.validator.BeanValidator.java

/**
 * javax.validation????Bean?Validation?//from   w ww  .  j a  va 2 s  .  c  om
 *
 * @param bean ?Bean
 * @return {@code ValidateMessage}?
 * @throws IllegalArgumentException 
 */
public static <T> List<ValidateMessage<T>> validateBean(final T bean) throws IllegalArgumentException {
    if (bean == null) {
        throw new IllegalArgumentException("bean is null");
    }

    final Set<ConstraintViolation<T>> constraintViolations = getValidator().validate(bean);
    final int size = constraintViolations.size();
    final List<ValidateMessage<T>> messages = new ArrayList<ValidateMessage<T>>(size);
    if (size > 0) {
        final Iterator<ConstraintViolation<T>> ite = constraintViolations.iterator();
        while (ite.hasNext()) {
            messages.add(new ValidateMessage<T>(ite.next()));
        }
    }
    return messages;
}

From source file:com.elsevier.xml.XQueryProcessor.java

/**
 * Set the namespaces in the XQueryCompiler.
 * //from w ww.j a v a 2 s.  com
 * @param xqueryCompiler
 */
private static void setPrefixNamespaceMappings(XQueryCompiler xqueryCompiler) {

    // Get the mappings
    Set<Entry<String, String>> mappings = NamespaceContextMappings.getMappings();

    // If mappings exist, set the namespaces
    if (mappings != null) {
        synchronized (XQueryProcessor.class) {
            if (mappings != null) {
                Iterator<Entry<String, String>> it = mappings.iterator();
                while (it.hasNext()) {
                    Entry<String, String> entry = it.next();
                    xqueryCompiler.declareNamespace(entry.getKey(), entry.getValue());
                }
            }
        }
    }

}

From source file:com.vmware.admiral.compute.container.volume.VolumeUtil.java

/**
 * Creates additional affinity rules between container descriptions which share
 * local volumes. Each container group should be deployed on a single host.
 *///from ww  w. jav a2s.c  om
public static void applyLocalNamedVolumeConstraints(Collection<ComponentDescription> componentDescriptions) {

    Map<String, ContainerVolumeDescription> volumes = filterDescriptions(ContainerVolumeDescription.class,
            componentDescriptions);

    List<String> localVolumes = volumes.values().stream().filter(v -> DEFAULT_VOLUME_DRIVER.equals(v.driver))
            .map(v -> v.name).collect(Collectors.toList());

    if (localVolumes.isEmpty()) {
        return;
    }

    Map<String, ContainerDescription> containers = filterDescriptions(ContainerDescription.class,
            componentDescriptions);

    // sort containers by local volume: each set is a group of container names
    // that share a particular local volume
    List<Set<String>> localVolumeContainers = localVolumes.stream()
            .map(v -> filterByVolume(v, containers.values())).filter(s -> !s.isEmpty())
            .collect(Collectors.toList());

    if (localVolumeContainers.isEmpty()) {
        return;
    }

    /** Merge sets of containers sharing local volumes
     *
     *  C1  C2  C3  C4  C5  C6
     *   \  /\  /   |    \  /
     *    L1  L2    L3    L4
     *
     *    Input: [C1, C2], [C2, C3], [C4], [C5, C6]
     *    Output: [C1, C2, C3], [C4], [C5, C6]
     */
    localVolumeContainers = mergeSets(localVolumeContainers);

    Map<String, List<ContainerVolumeDescription>> containerToVolumes = containers.values().stream()
            .collect(Collectors.toMap(cd -> cd.name, cd -> filterVolumes(cd, volumes.values())));

    Map<String, Integer> containerToDriverCount = containerToVolumes.entrySet().stream()
            .collect(Collectors.toMap(e -> e.getKey(),
                    e -> e.getValue().stream().map(vd -> vd.driver).collect(Collectors.toSet()).size()));

    for (Set<String> s : localVolumeContainers) {
        if (s.size() > 1) {
            // find the container with highest number of required drivers
            int max = s.stream().map(cn -> containerToDriverCount.get(cn))
                    .max((vc1, vc2) -> Integer.compare(vc1, vc2)).get();
            Set<String> maxDrivers = s.stream().filter(cn -> containerToDriverCount.get(cn) == max)
                    .collect(Collectors.toSet());

            String maxCont = maxDrivers.iterator().next();
            s.remove(maxCont);
            s.stream().forEach(cn -> addAffinity(maxCont, containers.get(cn)));
        }
    }
}

From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java

/**
 * Creates a csv string of answer data from a collection of answers by reading the answer ids and
 * feature vectors/*  ww w  . j a va 2  s.  c  om*/
 * 
 * @param answers the collection of CandidatateAnswers to pull data from
 * @return
 */
public static String getCsvAnswerData(Collection<CandidateAnswer> answers, BaseEgaMetaDataAnswerScorer scorer) {

    // Initialize the csv string used to send the answer data for ranking
    StringBuilder csvStringHeader = new StringBuilder();
    StringBuilder csvString = new StringBuilder();

    // Add the answer data to to the csv string
    boolean addHeader = true;
    for (CandidateAnswer answer : answers) {

        // score the answer to add our own features
        if (scorer != null) {
            // answers come from real-time user, not testing phase of the
            // pipeline
            answer = scorer.scoreCandidateAnswer(null, answer);
        }

        // Add header
        if (addHeader) {
            csvStringHeader.append(RetrieveAndRankConstants.ANSWER_ID_HEADER + ",");
        }
        csvString.append(answer.getAnswerLabel());
        csvString.append(",");

        // Build the csvString by adding the feature vectors
        Set<Entry<String, Double>> fvp = answer.getFeatureValuePairs();
        Iterator<Entry<String, Double>> it = fvp.iterator();
        while (it.hasNext()) {
            Entry<String, Double> entry = (Entry<String, Double>) it.next();
            // ignore the added rank and score fields as they are not needed
            // by ranker
            if (!(entry.getKey().equals(PipelineConstants.FEATURE_SEARCH_RANK)
                    || entry.getKey().equals(PipelineConstants.FEATURE_SEARCH_SCORE))) {
                if (addHeader) {
                    csvStringHeader.append(entry.getKey());
                    csvStringHeader.append(",");
                }
                csvString.append(entry.getValue());
                csvString.append(",");
            }
        }

        // delete last comma of the header then begin a new line
        if (addHeader) {
            csvStringHeader.delete(csvStringHeader.length() - 1, csvStringHeader.length());
            csvStringHeader.append("\n");
        }

        // delete trailing comma then begin a new line
        csvString.delete(csvString.length() - 1, csvString.length());
        csvString.append("\n");
        addHeader = false;
    }

    return csvStringHeader.append(csvString).toString();
}

From source file:com.frostwire.vuze.VuzeDownloadManager.java

private static String calculateDisplayName(DownloadManager dm, Set<DiskManagerFileInfo> noSkippedSet) {
    String displayName = null;/*from  w ww.j  av  a2s  .c  o  m*/

    if (noSkippedSet.size() == 1) {
        displayName = FilenameUtils.getBaseName(noSkippedSet.iterator().next().getFile(false).getName());
    } else {
        displayName = dm.getDisplayName();
    }

    return displayName;
}

From source file:eu.cassandra.csn.gui.CSN.java

/**
 * //w  w  w .j a v a  2s .  com
 * @param clusters
 */
public static void groupCluster() { //Set<Set<MyNode>> clusters
    if (clusters == null)
        return;
    aggrLayout.removeAll();
    Iterator<Set<MyNode>> iter = clusters.iterator();
    while (iter.hasNext()) {
        Set<MyNode> vertices = iter.next();

        Point2D center = aggrLayout.transform(vertices.iterator().next());
        Graph<MyNode, MyLink> subGraph = SparseMultigraph.<MyNode, MyLink>getFactory().create();
        for (MyNode v : vertices) {
            subGraph.addVertex(v);
        }
        //         Layout<MyNode,MyLink> subLayout = new  CircleLayout<MyNode,MyLink>(subGraph);//CircleLayout
        //         subLayout.setInitializer(vv.getGraphLayout());
        //         subLayout.setSize(new Dimension(80,80));
        //         CSN.getAggregateLayout().put(subLayout,center);
        //         vv.repaint();
        //         vv.revalidate();

        Layout<MyNode, MyLink> subLayout = new CircleLayout<MyNode, MyLink>(subGraph); //Menu.getSelectedLayout(subGraph);
        subLayout.setInitializer(vv.getGraphLayout());
        if (subGraph.getVertexCount() > 15)
            subLayout.setSize(new Dimension(160, 160));
        else
            subLayout.setSize(new Dimension(80, 80));

        aggrLayout.put(subLayout, center);

        vv.setGraphLayout(aggrLayout);
        vv.repaint();
    }
    vv.repaint();
}

From source file:com.titilink.camel.rest.util.CommonUtils.java

/**
 * ?/*from  www.ja v a2 s .co m*/
 *
 * @param instance
 * @param <T>
 * @throws OperationException
 */
private static <T> void checkParameter(T instance) throws OperationException {
    Set<RootResponse> errorBoxs = ValidationUtil.validateExtend(instance);

    if (null != errorBoxs) {
        Iterator<RootResponse> iterator = errorBoxs.iterator();
        while (iterator.hasNext()) {
            RootResponse response = (RootResponse) iterator.next();
            throw new OperationException(response.getCode(), response.getMessage());
        }

    }
}

From source file:autocorrelator.apps.SDFGroovy.java

/**
 * Retrieve tag values from sd fields in mol and set them in the groovy binding
 *   so that they can be accessed as variables inside the groovy script.
 * @param args array of command line arguments to be made available to groovy.
 * @param mol molecule object with sd tags.
 * @param inFileds   Set with input variables = tagNames
 * @param outFields  Set with output variable = tagNames
 *///w  w w. j a v a  2s  .  co  m
private static Binding getFieldBindings(OEMolBase mol, Set<String> inFileds, Set<String> outFields) {
    Binding binding = new Binding();

    // set input variables
    Iterator<String> it = inFileds.iterator();
    while (it.hasNext()) {
        String tag = it.next();
        if ("mol".equals(tag))
            binding.setVariable(tag, mol);
        else if ("TITLE".equals(tag))
            binding.setVariable(tag, mol.GetTitle());
        else
            binding.setVariable(tag, oechem.OEGetSDData(mol, tag));
    }

    // set output variables to null
    it = outFields.iterator();
    while (it.hasNext()) {
        String tag = it.next();
        if (inFileds.contains(tag))
            continue; // already in inlist

        binding.setVariable(tag, null);
    }
    return binding;
}

From source file:com.impetus.kundera.persistence.CriteriaQueryTranslator.java

/**
 * Method to translate criteriaQuery into JPQL.
 * //  ww  w.j a  va  2  s.c  o m
 * @param criteriaQuery
 *            criteria query.
 * 
 * @return JPQL string.
 */
static <S> String translate(CriteriaQuery criteriaQuery) {
    QueryBuilder builder = new CriteriaQueryTranslator.QueryBuilder();

    // validate if criteria query is valid

    /**
     * select, from clause is mandatory
     * 
     * multiple from clause not support where clause is optional
     * 
     */

    Selection<S> select = criteriaQuery.getSelection();

    if (select != null) {
        builder.appendSelectClause();

    }

    if (select.getClass().isAssignableFrom(DefaultCompoundSelection.class)
            && ((CompoundSelection) select).isCompoundSelection()) {
        List<Selection<?>> selections = ((CompoundSelection) select).getCompoundSelectionItems();
        builder.appendMultiSelect(selections);
    } else if (select instanceof AggregateExpression) {
        builder.appendAggregate(((AggregateExpression) select).getAggregation());
    } else {
        String alias = select.getAlias();

        if (!StringUtils.isEmpty(alias)) {
            builder.appendAlias(alias);
        }

        Attribute attribute = ((DefaultPath) select).getAttribute();

        if (attribute != null) {
            builder.appendAttribute(attribute);
        }
    }
    Class<? extends S> clazzType = select.getJavaType();

    Set<Root<?>> roots = criteriaQuery.getRoots();

    Root<?> from = roots.iterator().next();

    Class entityClazz = from.getJavaType();

    builder.appendFromClause();

    // select.alias(paramString)
    builder.appendFrom(entityClazz);
    builder.appendAlias(from.getAlias() != null ? from.getAlias() : select.getAlias());
    Predicate where = criteriaQuery.getRestriction(); // this could be null.
    if (where != null) {
        builder.appendWhereClause();
        List<Expression<Boolean>> expressions = where.getExpressions();
        for (Expression expr : expressions) {
            builder.appendWhere(expr, from.getAlias());
        }

    }

    List<Order> orderings = criteriaQuery.getOrderList();

    if (orderings != null) {
        if (!orderings.isEmpty()) {
            builder.appendOrderClause(where == null);
        }

        for (Order order : orderings) {
            builder.appendAlias(from.getAlias() != null ? from.getAlias() : select.getAlias());
            builder.appendOrdering(order);
        }
    }
    return builder.getQuery();

    // check that roots has to be one. multiple clause not yet supported

}