java.util.Collection Java Examples

The following examples show how to use java.util.Collection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: View.java    From codeu_project_2017 with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<Message> getMessages(Uuid conversation, Time start, Time end) {

  final Collection<Message> messages = new ArrayList<>();

  try (final Connection connection = source.connect()) {

    Serializers.INTEGER.write(connection.out(), NetworkCode.GET_MESSAGES_BY_TIME_REQUEST);
    Time.SERIALIZER.write(connection.out(), start);
    Time.SERIALIZER.write(connection.out(), end);

    if (Serializers.INTEGER.read(connection.in()) == NetworkCode.GET_MESSAGES_BY_TIME_RESPONSE) {
      messages.addAll(Serializers.collection(Message.SERIALIZER).read(connection.in()));
    } else {
      LOG.error("Response from server failed.");
    }

  } catch (Exception ex) {
    System.out.println("ERROR: Exception during call on server. Check log for details.");
    LOG.error(ex, "Exception during call on server.");
  }

  return messages;
}
 
Example #2
Source File: IssueExpectations.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Matches the expectations in the added issues matchers against the given issues.
 *
 * @param issues
 *            the issues to match the expectations against
 * @param messages
 *            if this parameter is not <code>null</code>, this method will add an explanatory message for each
 *            mismatch
 * @return <code>true</code> if and only if every expectation was matched against an issue
 */
public boolean matchesAllExpectations(Collection<Issue> issues, List<String> messages) {
	Collection<Issue> issueCopy = new LinkedList<>(issues);
	Collection<IssueMatcher> matcherCopy = new LinkedList<>(issueMatchers);

	performMatching(issueCopy, matcherCopy, messages);
	if (inverted) {
		if (matcherCopy.isEmpty()) {
			explainExpectations(issueMatchers, messages, inverted);
			return false;
		}
	} else {
		if (!matcherCopy.isEmpty()) {
			explainExpectations(matcherCopy, messages, inverted);
			return false;
		}
	}
	return false;
}
 
Example #3
Source File: AccumulatorHelper.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
public static String getResultsFormatted(Map<String, Object> map) {
	StringBuilder builder = new StringBuilder();
	for (Map.Entry<String, Object> entry : map.entrySet()) {
		builder
			.append("- ")
			.append(entry.getKey())
			.append(" (")
			.append(entry.getValue().getClass().getName())
			.append(")");
		if (entry.getValue() instanceof Collection) {
			builder.append(" [").append(((Collection) entry.getValue()).size()).append(" elements]");
		} else {
			builder.append(": ").append(entry.getValue().toString());
		}
		builder.append(System.lineSeparator());
	}
	return builder.toString();
}
 
Example #4
Source File: LuceneQueryBuilder.java    From crate with Apache License 2.0 6 votes vote down vote up
static Query genericFunctionFilter(Function function, Context context) {
    if (function.valueType() != DataTypes.BOOLEAN) {
        raiseUnsupported(function);
    }
    // rewrite references to source lookup instead of using the docValues column store if:
    // - no docValues are available for the related column, currently only on objects defined as `ignored`
    // - docValues value differs from source, currently happening on GeoPoint types as lucene's internal format
    //   results in precision changes (e.g. longitude 11.0 will be 10.999999966)
    function = (Function) DocReferences.toSourceLookup(function,
        r -> r.columnPolicy() == ColumnPolicy.IGNORED
             || r.valueType() == DataTypes.GEO_POINT);

    final InputFactory.Context<? extends LuceneCollectorExpression<?>> ctx = context.docInputFactory.getCtx(context.txnCtx);
    @SuppressWarnings("unchecked")
    final Input<Boolean> condition = (Input<Boolean>) ctx.add(function);
    final Collection<? extends LuceneCollectorExpression<?>> expressions = ctx.expressions();
    final CollectorContext collectorContext = new CollectorContext();
    for (LuceneCollectorExpression<?> expression : expressions) {
        expression.startCollect(collectorContext);
    }
    return new GenericFunctionQuery(function, expressions, condition);
}
 
Example #5
Source File: ArmortypeToken.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public String[] unparse(LoadContext context, EquipmentModifier mod)
{
	Changes<ChangeArmorType> changes = context.getObjectContext().getListChanges(mod, ListKey.ARMORTYPE);
	Collection<ChangeArmorType> added = changes.getAdded();
	if (added == null || added.isEmpty())
	{
		// Zero indicates no Token
		return null;
	}
	TreeSet<String> set = new TreeSet<>();
	for (ChangeArmorType cat : added)
	{
		set.add(cat.getLSTformat());
	}
	return set.toArray(new String[0]);
}
 
Example #6
Source File: AccumuloFeatureStore.java    From accumulo-recipes with Apache License 2.0 6 votes vote down vote up
protected ScannerBase metricScanner(AccumuloFeatureConfig xform, Date start, Date end, String group, Iterable<String> types, String name, TimeUnit timeUnit, Auths auths) {
    checkNotNull(xform);

    try {
        group = defaultString(group);
        timeUnit = (timeUnit == null ? TimeUnit.MINUTES : timeUnit);

        BatchScanner scanner = connector.createBatchScanner(tableName + REVERSE_SUFFIX, auths.getAuths(), config.getMaxQueryThreads());

        Collection<Range> typeRanges = new ArrayList();
        for (String type : types)
            typeRanges.add(buildRange(type, start, end, timeUnit));

        scanner.setRanges(typeRanges);
        scanner.fetchColumn(new Text(combine(timeUnit.toString(), xform.featureName())), new Text(combine(group, name)));

        return scanner;

    } catch (TableNotFoundException e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: DBScanJobRunner.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<ParameterEnum<?>> getParameters() {
  final Collection<ParameterEnum<?>> params = super.getParameters();
  params.addAll(
      Arrays.asList(
          new ParameterEnum<?>[] {
              Partition.PARTITIONER_CLASS,
              Partition.MAX_DISTANCE,
              Partition.MAX_MEMBER_SELECTION,
              Global.BATCH_ID,
              Hull.DATA_TYPE_ID,
              Hull.PROJECTION_CLASS,
              Clustering.MINIMUM_SIZE,
              Partition.GEOMETRIC_DISTANCE_UNIT,
              Partition.DISTANCE_THRESHOLDS}));
  return params;
}
 
Example #8
Source File: MetadataStoreTestBase.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the ability of the MetadataStore to create a new Segment if the Segment already exists.
 */
@Test
public void testCreateSegmentAlreadyExists() {
    final String segmentName = "NewSegment";
    final Map<UUID, Long> originalAttributes = ImmutableMap.of(UUID.randomUUID(), 123L, Attributes.EVENT_COUNT, 1L);
    final Map<UUID, Long> expectedAttributes = Attributes.getCoreNonNullAttributes(originalAttributes);
    final Collection<AttributeUpdate> correctAttributeUpdates =
            originalAttributes.entrySet().stream()
                              .map(e -> new AttributeUpdate(e.getKey(), AttributeUpdateType.Replace, e.getValue()))
                              .collect(Collectors.toList());
    final Map<UUID, Long> badAttributes = Collections.singletonMap(UUID.randomUUID(), 456L);
    final Collection<AttributeUpdate> badAttributeUpdates =
            badAttributes.entrySet().stream()
                         .map(e -> new AttributeUpdate(e.getKey(), AttributeUpdateType.Replace, e.getValue()))
                         .collect(Collectors.toList());

    @Cleanup
    TestContext context = createTestContext();

    // Create a segment.
    context.getMetadataStore().createSegment(segmentName, correctAttributeUpdates, TIMEOUT).join();

    // Try to create it again.
    AssertExtensions.assertSuppliedFutureThrows(
            "createSegment did not fail when Segment already exists.",
            () -> context.getMetadataStore().createSegment(segmentName, badAttributeUpdates, TIMEOUT),
            ex -> ex instanceof StreamSegmentExistsException);

    val si = context.getMetadataStore().getSegmentInfo(segmentName, TIMEOUT).join();
    AssertExtensions.assertMapEquals("Unexpected attributes after failed attempt to recreate correctly created segment",
            expectedAttributes, si.getAttributes());
}
 
Example #9
Source File: ListMultiMap.java    From Ardulink-1 with Apache License 2.0 5 votes vote down vote up
public Map<K, List<V>> asMap() {
	Map<K, List<V>> map = new HashMap<K, List<V>>();
	for (Entry<K, Collection<V>> entry : data.entrySet()) {
		map.put(entry.getKey(), (List<V>) entry.getValue());
	}
	return map;
}
 
Example #10
Source File: OkHostnameVerifier.java    From nv-websocket-client with Apache License 2.0 5 votes vote down vote up
private static List<String> getSubjectAltNames(X509Certificate certificate, int type) {
  List<String> result = new ArrayList<String>();
  try {
    Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames();
    if (subjectAltNames == null) {
      return Collections.emptyList();
    }
    for (Object subjectAltName : subjectAltNames) {
      List<?> entry = (List<?>) subjectAltName;
      if (entry == null || entry.size() < 2) {
        continue;
      }
      Integer altNameType = (Integer) entry.get(0);
      if (altNameType == null) {
        continue;
      }
      if (altNameType == type) {
        String altName = (String) entry.get(1);
        if (altName != null) {
          result.add(altName);
        }
      }
    }
    return result;
  } catch (CertificateParsingException e) {
    return Collections.emptyList();
  }
}
 
Example #11
Source File: ParsedStrategy.java    From robozonky with Apache License 2.0 5 votes vote down vote up
public ParsedStrategy(final DefaultValues defaults, final Collection<PortfolioShare> portfolio,
        final Map<Rating, MoneyRange> investmentSizes,
        final Map<Rating, MoneyRange> purchaseSizes, final FilterSupplier filters) {
    this.defaults = defaults;
    this.portfolio = portfolio.isEmpty() ? Collections.emptyMap()
            : new EnumMap<>(portfolio.stream()
                .collect(Collectors.toMap(PortfolioShare::getRating, Function.identity())));
    this.investmentSizes = investmentSizes.isEmpty() ? Collections.emptyMap() : new EnumMap<>(investmentSizes);
    this.purchaseSizes = purchaseSizes.isEmpty() ? Collections.emptyMap() : new EnumMap<>(purchaseSizes);
    this.filters = filters;
}
 
Example #12
Source File: SplitCanvasHelper.java    From render with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Loops through the specified match pairs and adds any consensus set canvas ids to
 * the tracked data managed here.
 *
 * @param  derivedMatchPairs  collection of derived match pairs.
 */
public void trackSplitCanvases(final Collection<CanvasMatches> derivedMatchPairs) {
    for (final CanvasMatches derivedPair : derivedMatchPairs) {
        final ConsensusSetData setData = derivedPair.getConsensusSetData();
        if (setData != null) {
            trackSplitCanvas(derivedPair.getpGroupId(), setData.getOriginalPId(), derivedPair.getpId());
            trackSplitCanvas(derivedPair.getqGroupId(), setData.getOriginalQId(), derivedPair.getqId());
        }
    }
}
 
Example #13
Source File: SelectionSetServiceImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Collection<AuthenticationTypeVO> handleGetAuthenticationTypes(
		AuthenticationVO auth) throws Exception {
	Collection<AuthenticationTypeVO> result;
	AuthenticationType[] authenticationTypes = AuthenticationType.values();
	if (authenticationTypes != null) {
		result = new ArrayList<AuthenticationTypeVO>(authenticationTypes.length);
		for (int i = 0; i < authenticationTypes.length; i++) {
			result.add(L10nUtil.createAuthenticationTypeVO(Locales.USER, authenticationTypes[i]));
		}
	} else {
		result = new ArrayList<AuthenticationTypeVO>();
	}
	return result;
}
 
Example #14
Source File: InitDestroyAnnotationBeanPostProcessor.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
public LifecycleMetadata(Class<?> targetClass, Collection<LifecycleElement> initMethods,
		Collection<LifecycleElement> destroyMethods) {

	this.targetClass = targetClass;
	this.initMethods = initMethods;
	this.destroyMethods = destroyMethods;
}
 
Example #15
Source File: Filter.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public LogicalPlan pruneOutputsExcept(TableStats tableStats, Collection<Symbol> outputsToKeep) {
    LinkedHashSet<Symbol> toKeep = new LinkedHashSet<>(outputsToKeep);
    SymbolVisitors.intersection(query, source.outputs(), toKeep::add);
    LogicalPlan newSource = source.pruneOutputsExcept(tableStats, toKeep);
    if (newSource == source) {
        return this;
    }
    return new Filter(newSource, query);
}
 
Example #16
Source File: ConsumerProxy.java    From kbear with Apache License 2.0 5 votes vote down vote up
@Override
public Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions) {
    Map<String, Collection<TopicPartition>> map = toMap(partitions);
    return runWithoutConcurrency(() -> {
        Map<TopicPartition, Long> result = new HashMap<>();
        forEach(map::containsKey, (t, c) -> result.putAll(c.getConsumer().endOffsets(map.get(t))));
        return Collections.unmodifiableMap(result);
    });
}
 
Example #17
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void deliverShouldWork() throws Exception {
    Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();

    UnmodifiableIterator<HostAddress> dnsEntries = ImmutableList.of(
        HOST_ADDRESS_1,
        HOST_ADDRESS_2).iterator();
    when(dnsHelper.retrieveHostAddressIterator(MailAddressFixture.JAMES_APACHE_ORG)).thenReturn(dnsEntries);
    when(mailDelivrerToHost.tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class)))
        .thenReturn(ExecutionResult.success());
    ExecutionResult executionResult = testee.deliver(mail);

    verify(mailDelivrerToHost, times(1)).tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class));
    assertThat(executionResult.getExecutionState()).isEqualTo(ExecutionResult.ExecutionState.SUCCESS);
}
 
Example #18
Source File: SimplexSolverTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testDegeneracy() throws OptimizationException {
    LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.7 }, 0 );
    Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
    constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 18.0));
    constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, 10.0));
    constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 8.0));

    SimplexSolver solver = new SimplexSolver();
    RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
    Assert.assertEquals(13.6, solution.getValue(), .0000001);
}
 
Example #19
Source File: ResponseUtil.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public Collection<String> getHeaders(String name) {
    Enumeration<String> values = headers.values(name);
    List<String> result = new ArrayList<>();
    while (values.hasMoreElements()) {
        result.add(values.nextElement());
    }
    return result;
}
 
Example #20
Source File: TimelineCachePluginImpl.java    From tez with Apache License 2.0 5 votes vote down vote up
@Override
public Set<TimelineEntityGroupId> getTimelineEntityGroupId(String entityType,
    NameValuePair primaryFilter,
    Collection<NameValuePair> secondaryFilters) {
  if (!knownEntityTypes.contains(entityType)
      || primaryFilter == null
      || !knownEntityTypes.contains(primaryFilter.getName())
      || summaryEntityTypes.contains(entityType)) {
    return null;
  }
  return convertToTimelineEntityGroupIds(primaryFilter.getName(), primaryFilter.getValue().toString());
}
 
Example #21
Source File: SeqGraph.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Zip up all of the simple linear chains present in this graph.
 *
 * Merges together all pairs of vertices in the graph v1 -> v2 into a single vertex v' containing v1 + v2 sequence
 *
 * Only works on vertices where v1's only outgoing edge is to v2 and v2's only incoming edge is from v1.
 *
 * If such a pair of vertices is found, they are merged and the graph is update.  Otherwise nothing is changed.
 *
 * @return true if any such pair of vertices could be found, false otherwise
 */
public boolean zipLinearChains() {
    // create the list of start sites [doesn't modify graph yet]
    final Collection<SeqVertex> zipStarts = new LinkedList<>();
    for ( final SeqVertex source : vertexSet() ) {
        if ( isLinearChainStart(source) ) {
            zipStarts.add(source);
        }
    }

    if ( zipStarts.isEmpty() ) // nothing to do, as nothing could start a chain
    {
        return false;
    }

    // At this point, zipStarts contains all of the vertices in this graph that might start some linear
    // chain of vertices.  We walk through each start, building up the linear chain of vertices and then
    // zipping them up with mergeLinearChain, if possible
    boolean mergedOne = false;
    for ( final SeqVertex zipStart : zipStarts ) {
        final LinkedList<SeqVertex> linearChain = traceLinearChain(zipStart);

        // merge the linearized chain, recording if we actually did some useful work
        mergedOne |= mergeLinearChain(linearChain);
    }

    return mergedOne;
}
 
Example #22
Source File: ResourcesDirectoryReader.java    From ontopia with Apache License 2.0 5 votes vote down vote up
public Collection<String> getResourcesAsStrings() {
  if (resources == null) {
    findResources();
  }
  return CollectionUtils.collect(resources, new Transformer<URL, String>() {
    @Override
    public String transform(URL url) {
      try {
        return URLDecoder.decode(url.toString(), "utf-8");
      } catch (UnsupportedEncodingException uee) {
        throw new OntopiaRuntimeException(uee);
      }
    }
  });
}
 
Example #23
Source File: AbstractTransactCommand.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("checkstyle:IllegalCatch")
public AbstractTransactCommand getClone() {
    try {
        return getClass().getConstructor(HwvtepOperationalState.class, Collection.class)
                .newInstance(hwvtepOperationalState, changes);
    } catch (Throwable e) {
        LOG.error("Failed to clone the cmd ", e);
    }
    return this;
}
 
Example #24
Source File: MinAvgPairAggregator.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
@Override
public short aggregate(short[] values, short nodata)
{
  boolean data0 = values[0] != nodata;
  boolean data1 = values[1] != nodata;
  boolean data2 = values[2] != nodata;
  boolean data3 = values[3] != nodata;

  Collection<Integer> averages = new ArrayList<>();
  if (data0 && data1)
  {
    averages.add((values[0] + values[1]) / 2);
  }
  if (data0 && data2)
  {
    averages.add((values[0] + values[2]) / 2);
  }
  if (data0 && data3)
  {
    averages.add((values[0] + values[3]) / 2);
  }
  if (data1 && data2)
  {
    averages.add((values[1] + values[2]) / 2);
  }
  if (data1 && data3)
  {
    averages.add((values[1] + values[3]) / 2);
  }
  if (data2 && data3)
  {
    averages.add((values[2] + values[3]) / 2);
  }

  return (averages.isEmpty()) ? nodata : Collections.min(averages).shortValue();
}
 
Example #25
Source File: MoveValidator.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private Optional<String> canAnyPassThroughCanal(
    final CanalAttachment canalAttachment,
    final Collection<Unit> units,
    final GamePlayer player) {
  if (units.stream().anyMatch(Matches.unitIsOfTypes(canalAttachment.getExcludedUnits()))) {
    return Optional.empty();
  }
  return checkCanalStepAndOwnership(canalAttachment, player);
}
 
Example #26
Source File: AbstractDataTypeConfig.java    From datawave with Apache License 2.0 5 votes vote down vote up
private static List<String> mappingToFields(final Collection<Set<String>> mapping) {
    final List<String> fields = new ArrayList<>();
    for (final Set<String> virtual : mapping) {
        fields.add(String.join(".", virtual));
    }
    return fields;
}
 
Example #27
Source File: DecodedBitStreamParser.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
private static void decodeByteSegment(BitSource bits, StringBuilder result, int count,
		CharacterSetECI currentCharacterSetECI, Collection<byte[]> byteSegments, Map<DecodeHintType, ?> hints)
		throws FormatException {
	// Don't crash trying to read more bits than we have available.
	if (8 * count > bits.available()) {
		throw FormatException.getFormatInstance();
	}

	byte[] readBytes = new byte[count];
	for (int i = 0; i < count; i++) {
		readBytes[i] = (byte) bits.readBits(8);
	}
	String encoding;
	if (currentCharacterSetECI == null) {
		// The spec isn't clear on this mode; see
		// section 6.4.5: t does not say which encoding to assuming
		// upon decoding. I have seen ISO-8859-1 used as well as
		// Shift_JIS -- without anything like an ECI designator to
		// give a hint.
		encoding = StringUtils.guessEncoding(readBytes, hints);
	} else {
		encoding = currentCharacterSetECI.name();
	}
	try {
		result.append(new String(readBytes, encoding));
	} catch (UnsupportedEncodingException ignored) {
		throw FormatException.getFormatInstance();
	}
	byteSegments.add(readBytes);
}
 
Example #28
Source File: Classification.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
public <K, V extends Number> Map.Entry<K, Value<V>> getWinner(Type type, Collection<Map.Entry<K, Value<V>>> entries){
	Ordering<Map.Entry<K, Value<V>>> ordering = Classification.<K, V>createOrdering(type);

	try {
		return ordering.max(entries);
	} catch(NoSuchElementException nsee){
		return null;
	}
}
 
Example #29
Source File: ParameterBindingTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testBindCollectionInFromClause() throws Exception {
  Query query = CacheUtils.getQueryService().newQuery("SELECT DISTINCT * FROM $1 ");
  Object params[] = new Object[1];
  Region region = CacheUtils.getRegion("/Portfolios");
  params[0] = region.values();
  Object result = query.execute(params);
  if(result instanceof Collection){
    int resultSize = ((Collection)result).size();
    if( resultSize != region.values().size())
      fail("Results not as expected");
  }else
    fail("Invalid result");
}
 
Example #30
Source File: DbProductDao.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
@Override
public Collection<Product> getProducts() throws WarehouseException {
    try (Connection connection = getConnection();
         Statement statement = connection.createStatement()) {
        List<Product> products = new ArrayList<>();
        try (ResultSet rs = statement.executeQuery("SELECT * FROM products")) {
            while (rs.next()) {
                products.add(toProduct(rs));
            }
        }
        return products;
    } catch (SQLException ex) {
        throw new WarehouseException("Trouble while fetching products.", ex);
    }
}