下面列出了java.util.Collection#add ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void testMixedSetsAndUpdates() throws Exception {
Collection<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
Collection<String> keys = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
String key = "k" + i;
futures.add(client.set(key, 10, key));
futures.add(client.add(key, 10, "a" + i));
keys.add(key);
}
Map<String, Object> m = client.getBulk(keys);
assertEquals(100, m.size());
for (Map.Entry<String, Object> me : m.entrySet()) {
assertEquals(me.getKey(), me.getValue());
}
for (Iterator<Future<Boolean>> i = futures.iterator(); i.hasNext();) {
assertTrue(i.next().get());
assertFalse(i.next().get());
}
}
private Object readCollection(final TypeInformation<?> type, final VPackSlice source) {
if (!source.isArray()) {
throw new MappingException(
String.format("Can't read collection type %s from VPack type %s!", type, source.getType()));
}
final TypeInformation<?> componentType = getNonNullComponentType(type);
final Class<?> collectionType = Iterable.class.equals(type.getType()) ? Collection.class : type.getType();
final Collection<Object> collection = CollectionFactory.createCollection(collectionType,
componentType.getType(), source.getLength());
final Iterator<VPackSlice> iterator = source.arrayIterator();
while (iterator.hasNext()) {
final VPackSlice elem = iterator.next();
collection.add(readInternal(componentType, elem));
}
return collection;
}
@Test
public void testEpsilon() {
LinearObjectiveFunction f =
new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17));
constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7));
constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints),
GoalType.MAXIMIZE, new NonNegativeConstraint(false));
Assert.assertEquals(1.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(1.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(0.0, solution.getPoint()[2], 0.0);
Assert.assertEquals(15.0, solution.getValue(), 0.0);
}
public static void validateInstanceGroups(Collection<HostGroup> hostGroups, Collection<InstanceGroup> instanceGroups) {
if (!instanceGroups.isEmpty()) {
Collection<String> instanceGroupNames = new HashSet<>();
for (HostGroup hostGroup : hostGroups) {
String instanceGroupName = hostGroup.getInstanceGroup().getGroupName();
if (instanceGroupNames.contains(instanceGroupName)) {
throw new BlueprintValidationException(String.format(
"Instance group '%s' is assigned to more than one hostgroup.", instanceGroupName));
}
instanceGroupNames.add(instanceGroupName);
}
if (instanceGroups.size() < hostGroups.size()) {
throw new BlueprintValidationException("Each host group must have an instance group");
}
}
}
/**
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
public int drainTo(Collection<? super E> c, int maxElements) {
if (c == null)
throw new NullPointerException();
if (c == this)
throw new IllegalArgumentException();
if (maxElements <= 0)
return 0;
final ReentrantLock lock = this.lock;
lock.lock();
try {
int n = Math.min(maxElements, count);
for (int i = 0; i < n; i++) {
c.add(first.item); // In this order, in case add() throws.
unlinkFirst();
}
return n;
} finally {
lock.unlock();
}
}
@Test(expected=NoFeasibleSolutionException.class)
public void testMath290LEQ() throws OptimizationException {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.LEQ, -1.0));
SimplexSolver solver = new SimplexSolver();
solver.optimize(f, constraints, GoalType.MINIMIZE, true);
}
@Override
@GraphTransaction
public EntityMutationResponse deleteByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes)
throws AtlasBaseException {
if (MapUtils.isEmpty(uniqAttributes)) {
throw new AtlasBaseException(AtlasErrorCode.INSTANCE_BY_UNIQUE_ATTRIBUTE_NOT_FOUND, uniqAttributes.toString());
}
final AtlasVertex vertex = AtlasGraphUtilsV1.findByUniqueAttributes(entityType, uniqAttributes);
Collection<AtlasVertex> deletionCandidates = new ArrayList<>();
if (vertex != null) {
deletionCandidates.add(vertex);
} else {
if (LOG.isDebugEnabled()) {
// Entity does not exist - treat as non-error, since the caller
// wanted to delete the entity and it's already gone.
LOG.debug("Deletion request ignored for non-existent entity with uniqueAttributes " + uniqAttributes);
}
}
EntityMutationResponse ret = deleteVertices(deletionCandidates);
// Notify the change listeners
entityChangeNotifier.onEntitiesMutated(ret, false);
return ret;
}
private Collection<InsertValuesSegment> createInsertValuesSegments(final Collection<AssignmentValuesContext> assignmentValuesContexts) {
Collection<InsertValuesSegment> result = new LinkedList<>();
for (AssignmentValuesContext each : assignmentValuesContexts) {
result.add((InsertValuesSegment) visit(each));
}
return result;
}
@Override
public Collection<TinkerGraphRouteSensorInjectMatch> evaluate() {
final Collection<TinkerGraphRouteSensorInjectMatch> matches = new ArrayList<>();
final Collection<Vertex> routes = driver.getVertices(ModelConstants.ROUTE);
for (final Vertex route : routes) {
final Iterable<Edge> edges = () -> route.edges(Direction.OUT, ModelConstants.REQUIRES);
for (final Edge requires : edges) {
final Vertex sensor = requires.inVertex();
matches.add(new TinkerGraphRouteSensorInjectMatch(route, sensor));
}
}
return matches;
}
public Collection<SONConnection> getRuntimeConnections(SON net) {
Collection<SONConnection> result = new HashSet<>();
Collection<Node> nodes = getNodes(net);
for (Node node : nodes) {
Collection<SONConnection> connections = net.getSONConnections((MathNode) node);
for (SONConnection con : connections) {
if (con.getFirst() != node && nodes.contains(con.getFirst())) {
result.add(con);
} else if (con.getSecond() != node && nodes.contains(con.getSecond())) {
result.add(con);
}
}
}
return result;
}
final <T> boolean repeat(
Parser<? extends T> parser, int n, Collection<T> collection) {
for (int i = 0; i < n; i++) {
if (!parser.apply(this)) return false;
collection.add(parser.getReturn(this));
}
return true;
}
private Collection<Element> getTypesExtendingOrImplementing(Set<? extends Element> allTypes, Element baseType) {
Collection<Element> result = new LinkedHashSet<>();
result.add(baseType);
addTypesExtendingOrImplementing(allTypes, baseType.asType(), result);
logClass("Sub types: " + result, qualifiedNameOf(baseType));
return result;
}
private void putMsg(MessageExt msg) {
Collection<Object> msgQueue = null;
String key = getKey(msg.getQueueId(), msg.getStoreHost().toString());
if (!msgs.containsKey(key)) {
msgQueue = new ArrayList<Object>();
} else {
msgQueue = msgs.get(key);
}
msgQueue.add(new String(msg.getBody()));
msgs.put(key, msgQueue);
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
Collection<Object[]> params = Lists.newArrayListWithCapacity(2);
params.add(new Object[]{true});
params.add(new Object[]{false});
return params;
}
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final RangeShardingValue<Integer> shardingValue) {
Collection<String> result = new HashSet<>(2);
for (int i = shardingValue.getValueRange().lowerEndpoint(); i <= shardingValue.getValueRange().upperEndpoint(); i++) {
for (String each : availableTargetNames) {
if (each.endsWith(String.valueOf(i % 2))) {
result.add(each);
}
}
}
return result;
}
static protected DocumentCollection getCollectionDefinitionWithRangeRangeIndex() {
PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition();
ArrayList<String> paths = new ArrayList<>();
paths.add("/mypk");
partitionKeyDef.setPaths(paths);
IndexingPolicy indexingPolicy = new IndexingPolicy();
Collection<IncludedPath> includedPaths = new ArrayList<>();
IncludedPath includedPath = new IncludedPath();
includedPath.setPath("/*");
Collection<Index> indexes = new ArrayList<>();
Index stringIndex = Index.Range(DataType.String);
stringIndex.set("precision", -1);
indexes.add(stringIndex);
Index numberIndex = Index.Range(DataType.Number);
numberIndex.set("precision", -1);
indexes.add(numberIndex);
includedPath.setIndexes(indexes);
includedPaths.add(includedPath);
indexingPolicy.setIncludedPaths(includedPaths);
DocumentCollection collectionDefinition = new DocumentCollection();
collectionDefinition.setIndexingPolicy(indexingPolicy);
collectionDefinition.setId(UUID.randomUUID().toString());
collectionDefinition.setPartitionKey(partitionKeyDef);
return collectionDefinition;
}
@Override
protected Collection<InnerPlan> getNestedPlans(MapReduceOper op) {
Collection<InnerPlan> plans = new LinkedList<InnerPlan>();
plans.add(new InnerPlan(op.mapPlan, op.combinePlan, op.reducePlan));
return plans;
}
/**
* Generate the required select tag.
*
* @exception JspException if a JSP exception has occurred
*/
@Override
public int doEndTag() throws JspException {
// original value; used to detect changes
Set value = new HashSet();
// already selected objects
Collection selectedObjs = java.util.Collections.EMPTY_LIST;
if (selected_name == null)
value.add("-1"); // equals choosing "-- unspecified --"
else {
selectedObjs = InteractionELSupport
.extendedGetValue(selected_name, pageContext);
// create collection to store in
Iterator it = selectedObjs.iterator();
while (it.hasNext())
value.add(((TMObjectIF) it.next()).getObjectId());
if (value.isEmpty())
value.add(null); // this is how empty sets look to ProcessServlet
}
// multiselect is a special case; if nothing's selected there, then
// null is the value we get, not -1; see bug #1252
if ((type.equals("multiselect") || type.equals("scrolling")) && selected_name == null)
value = java.util.Collections.singleton(null);
boolean readonly = TagUtils.isComponentReadOnly(pageContext, this.readonly);
VelocityContext vc = TagUtils.getVelocityContext(pageContext);
// register action data and produce input field name
if (action_name != null && !readonly) {
// retrieve the action group
String group_name = TagUtils.getActionGroup(pageContext);
if (group_name == null)
throw new JspException("list tag has no action group available.");
String name = TagUtils.registerData(pageContext, action_name, group_name,
params, value);
if (!(type.equals("multiselect") || type.equals("scrolling"))&& !unspecified.equals("none"))
vc.put("unspecified", unspecified);
vc.put("name", name);
}
if (id != null) vc.put("id", id);
vc.put("readonly", readonly);
if (klass != null) vc.put("class", klass);
vc.put("type", type);
// retrieve the elements
Collection elements = new ArrayList();
// since collection_name is a required attribute no extra validation needed
NavigatorPageIF contextTag = FrameworkUtils.getContextTag(pageContext);
if (contextTag == null)
throw new JspException("List tag found no logic:context ancestor tag");
Collection tmObjs = InteractionELSupport.extendedGetValue(collection_name,
pageContext);
Iterator iter = tmObjs.iterator();
while (iter.hasNext()) {
Object obj = iter.next();
if (!(obj instanceof TMObjectIF))
throw new JspException("Collection in variable " + collection_name +
"contained non-topic map object: " + obj);
TMObjectIF tmObj = (TMObjectIF) obj;
elements.add(new NameIdContainer(tmObj.getObjectId(),
Stringificator.toString(contextTag, tmObj),
selectedObjs.contains(tmObj)));
}
vc.put("elements", elements);
// all variables are now set, proceed with outputting
TagUtils.processWithVelocity(pageContext, TEMPLATE_FILE, pageContext.getOut(), vc);
// Continue processing this page
return EVAL_BODY_INCLUDE;
}
private void establishSessionWithPolicies()
{
Cluster.Builder clusterBuilder = Cluster.builder();
String[] seedNodesSplit = seedNodesStr.split(";");
Collection<InetAddress> allSeeds = new ArrayList<>();
Set<String> allKnownPorts = new HashSet<>();
for (String seedNode : seedNodesSplit) {
String[] nodeAndPort = seedNode.split(":");
if (nodeAndPort.length > 1) {
allKnownPorts.add(nodeAndPort[1]);
}
try {
allSeeds.add(InetAddress.getByName(nodeAndPort[0]));
} catch (UnknownHostException e) {
LOG.error(" Error while trying to initialize the seed brokers for the cassandra cluster " + e.getMessage(), e);
}
}
clusterBuilder = clusterBuilder.addContactPoints(allSeeds);
clusterBuilder
.withClusterName(clusterName)
// We can fail if all of the nodes die in the local DC
.withLoadBalancingPolicy(loadBalancingPolicy)
// Want Strong consistency
.withRetryPolicy(retryPolicy)
// Tolerate some nodes down
.withQueryOptions(queryOptions)
// Keep establishing connections after detecting a node down
.withReconnectionPolicy(reconnectionPolicy);
// Finally initialize the cluster info
if (allKnownPorts.size() > 0) {
int shortlistedPort = Integer.parseInt(allKnownPorts.iterator().next());
clusterBuilder = clusterBuilder.withPort(shortlistedPort);
}
cluster = clusterBuilder.build();
Metadata metadata = cluster.getMetadata();
LOG.info("Connected to cluster: \n" + metadata.getClusterName());
for (Host host : metadata.getAllHosts()) {
LOG.info(String.format("Datacenter: %s; Host: %s; Rack: %s\n",
host.getDatacenter(), host.getAddress(), host.getRack()));
}
session = cluster.connect(keyspaceName);
}
/**
* Transforms a collection of one data type into another.
* @param from a collection of data to be transformed.
* @param to a collection to contain the transformed data.
* @param transformer transforms the data.
*/
public static <T1, T2> void transform(Collection<T1> from,Collection<T2> to,Transformer<T1,T2> transformer) {
for(T1 instance : from) {
to.add(transformer.transform(instance));
}
}