private ImmutableSet<Pipeline> selectPipelines(InterpreterListener interpreterListener, Set<Tuple2<String, String>> processingBlacklist, Message message, Set<String> initialStreamIds, ImmutableSetMultimap<String, Pipeline> streamConnection) { final String msgId = message.getId(); // if a message-stream combination has already been processed (is in the set), skip that execution final Set<String> streamsIds = initialStreamIds.stream() .filter(streamId -> !processingBlacklist.contains(tuple(msgId, streamId))) .filter(streamConnection::containsKey) .collect(Collectors.toSet()); final ImmutableSet<Pipeline> pipelinesToRun = streamsIds.stream() .flatMap(streamId -> streamConnection.get(streamId).stream()) .collect(ImmutableSet.toImmutableSet()); interpreterListener.processStreams(message, pipelinesToRun, streamsIds); log.debug("[{}] running pipelines {} for streams {}", msgId, pipelinesToRun, streamsIds); return pipelinesToRun; }
@Override public boolean processLine(@Nonnull String line) throws IOException { final String[] strings = csvParser.parseLine(line); if (strings == null) { return false; } if (firstLine) { fieldNames = strings; firstLine = false; return true; } final Map<String, Object> fields = Seq.of(fieldNames) .zipWithIndex() .map(nameAndIndex -> nameAndIndex.map2(index -> strings[Math.toIntExact(index)])) .collect(Collectors.toMap(Tuple2::v1, Tuple2::v2)); fields.put(Message.FIELD_ID, new UUID().toString()); messages.add(new Message(fields)); return true; }
@Test public void testGetIdentityToken() throws Exception { EndpointDescription endpoint = new EndpointDescription( null, null, null, null, null, new UserTokenPolicy[]{ new UserTokenPolicy( "anonymous", UserTokenType.Anonymous, null, null, null) }, null, null ); AnonymousProvider p = new AnonymousProvider(); Tuple2<UserIdentityToken, SignatureData> t2 = p.getIdentityToken(endpoint, ByteString.NULL_VALUE); assertEquals(t2.v1().getPolicyId(), "anonymous"); assertTrue(t2.v1() instanceof AnonymousIdentityToken); }
@Test public void testGetIdentityToken_EmptyPolicyId() throws Exception { EndpointDescription endpoint = new EndpointDescription( null, null, null, null, null, new UserTokenPolicy[]{ new UserTokenPolicy( "", UserTokenType.Anonymous, null, null, null) }, null, null ); AnonymousProvider p = new AnonymousProvider(); Tuple2<UserIdentityToken, SignatureData> t2 = p.getIdentityToken(endpoint, ByteString.NULL_VALUE); assertEquals(t2.v1().getPolicyId(), ""); assertTrue(t2.v1() instanceof AnonymousIdentityToken); }
@Test public void testGetIdentityToken_NullPolicyId() throws Exception { EndpointDescription endpoint = new EndpointDescription( null, null, null, null, null, new UserTokenPolicy[]{ new UserTokenPolicy( null, UserTokenType.Anonymous, null, null, null) }, null, null ); AnonymousProvider p = new AnonymousProvider(); Tuple2<UserIdentityToken, SignatureData> t2 = p.getIdentityToken(endpoint, ByteString.NULL_VALUE); assertNull(t2.v1().getPolicyId()); assertTrue(t2.v1() instanceof AnonymousIdentityToken); }
/** * GetMonitoredItems is used to get information about monitored items of a subscription. * * @param subscriptionId identifier of the subscription. * @return a {@link Tuple2} containing the output arguments. * <p> * serverHandles (UInt32[]) - array of serverHandles for all MonitoredItems of the subscription identified by * subscriptionId. * <p> * clientHandles (UInt32[]) - array of clientHandles for all MonitoredItems of the subscription identified by * subscriptionId. */ public CompletableFuture<Tuple2<UInteger[], UInteger[]>> invoke(UInteger subscriptionId) { Variant[] inputArguments = new Variant[]{ new Variant(subscriptionId) }; return invoke(inputArguments).thenCompose(outputArguments -> { try { UInteger[] v0 = (UInteger[]) outputArguments[0].getValue(); UInteger[] v1 = (UInteger[]) outputArguments[1].getValue(); return CompletableFuture.completedFuture(new Tuple2<>(v0, v1)); } catch (Throwable t) { CompletableFuture<Tuple2<UInteger[], UInteger[]>> f = new CompletableFuture<>(); f.completeExceptionally(new UaException(t)); return f; } }); }
@Override public Tuple2<UserIdentityToken, SignatureData> getIdentityToken( EndpointDescription endpoint, ByteString serverNonce) throws Exception { List<UserTokenPolicy> userIdentityTokens = l(endpoint.getUserIdentityTokens()); return userIdentityTokens.stream() .filter(t -> t.getTokenType() == UserTokenType.Anonymous) .findFirst() .map(policy -> { UserIdentityToken token = new AnonymousIdentityToken(policy.getPolicyId()); return new Tuple2<>(token, new SignatureData()); }) .orElseThrow(() -> new Exception("no anonymous token policy found")); }
@Override public Tuple2<UserIdentityToken, SignatureData> getIdentityToken(EndpointDescription endpoint, ByteString serverNonce) throws Exception { Iterator<IdentityProvider> iterator = providers.iterator(); while (iterator.hasNext()) { IdentityProvider provider = iterator.next(); try { return provider.getIdentityToken(endpoint, serverNonce); } catch (Exception e) { if (!iterator.hasNext()) { throw e; } logger.debug("IdentityProvider={} failed, trying next...", provider.toString()); } } throw new Exception("no sufficient UserTokenPolicy found"); }
@Override public Observable<JsonObject> bulkInsert(String type, List<Tuple2<String, JsonObject>> documents) { String uri = "/" + index + "/" + type + "/_bulk"; // prepare the whole body now because it's much faster to send // it at once instead of using HTTP chunked mode. StringBuilder body = new StringBuilder(); for (Tuple2<String, JsonObject> e : documents) { String id = e.v1; String source = e.v2.encode(); JsonObject subject = new JsonObject().put("_id", id); body.append("{\"index\":" + subject.encode() + "}\n" + source + "\n"); } return performRequestRetry(HttpMethod.POST, uri, body.toString()); }
/** * Test if the client can insert multiple documents in one request * @param context the test context */ @Test public void bulkInsert(TestContext context) { String url = "/" + INDEX + "/" + TYPE + "/_bulk"; stubFor(post(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withBody("{}"))); List<Tuple2<String, JsonObject>> documents = new ArrayList<>(); documents.add(Tuple.tuple("A", new JsonObject().put("name", "Elvis"))); documents.add(Tuple.tuple("B", new JsonObject().put("name", "Max"))); Async async = context.async(); client.bulkInsert(TYPE, documents).subscribe(res -> { verify(postRequestedFor(urlEqualTo(url)) .withRequestBody(equalToJson("{\"index\":{\"_id\":\"A\"}}\n" + "{\"name\":\"Elvis\"}\n" + "{\"index\":{\"_id\":\"B\"}}\n" + "{\"name\":\"Max\"}\n"))); context.assertEquals(0, res.size()); async.complete(); }, context::fail); }
private List<Tuple2<GeoJsonChunkMeta, JsonObject>> split(String file) throws IOException { byte[] json = IOUtils.toByteArray(GeoJsonSplitterTest.class.getResource(file)); List<Tuple2<GeoJsonChunkMeta, JsonObject>> chunks = new ArrayList<>(); StringWindow window = new StringWindow(); GeoJsonSplitter splitter = new GeoJsonSplitter(window); Observable.just(json) .map(Buffer::buffer) .doOnNext(window::append) .lift(new JsonParserOperator()) .flatMap(splitter::onEventObservable) .toBlocking() .forEach(result -> { JsonObject o = new JsonObject(result.getChunk()); chunks.add(Tuple.tuple((GeoJsonChunkMeta)result.getMeta(), o)); }); return chunks; }
/** * Test if a Feature can be split correctly * @throws IOException if the test file could not be read */ @Test public void feature() throws IOException { String filename = "feature.json"; long size = getFileSize(filename); List<Tuple2<GeoJsonChunkMeta, JsonObject>> chunks = split(filename); assertEquals(1, chunks.size()); Tuple2<GeoJsonChunkMeta, JsonObject> t1 = chunks.get(0); GeoJsonChunkMeta m1 = t1.v1; assertNull(m1.getParentFieldName()); assertEquals(0, m1.getStart()); assertEquals(size, m1.getEnd()); assertEquals("Feature", m1.getType()); JsonObject o1 = t1.v2; assertEquals("Feature", o1.getString("type")); assertEquals("Fraunhofer IGD", o1.getJsonObject("properties").getString("name")); }
/** * Test if a LineString can be split correctly * @throws IOException if the test file could not be read */ @Test public void lineString() throws IOException { String filename = "linestring.json"; long size = getFileSize(filename); List<Tuple2<GeoJsonChunkMeta, JsonObject>> chunks = split(filename); assertEquals(1, chunks.size()); Tuple2<GeoJsonChunkMeta, JsonObject> t1 = chunks.get(0); GeoJsonChunkMeta m1 = t1.v1; assertNull(m1.getParentFieldName()); assertEquals(0, m1.getStart()); assertEquals(size, m1.getEnd()); assertEquals("LineString", m1.getType()); JsonObject o1 = t1.v2; assertEquals("LineString", o1.getString("type")); assertEquals(13, o1.getJsonArray("coordinates").size()); }
/** * Test if a MultiLineString can be split correctly * @throws IOException if the test file could not be read */ @Test public void muliLineString() throws IOException { String filename = "multilinestring.json"; long size = getFileSize(filename); List<Tuple2<GeoJsonChunkMeta, JsonObject>> chunks = split(filename); assertEquals(1, chunks.size()); Tuple2<GeoJsonChunkMeta, JsonObject> t1 = chunks.get(0); GeoJsonChunkMeta m1 = t1.v1; assertNull(m1.getParentFieldName()); assertEquals(0, m1.getStart()); assertEquals(size, m1.getEnd()); assertEquals("MultiLineString", m1.getType()); JsonObject o1 = t1.v2; assertEquals("MultiLineString", o1.getString("type")); assertEquals(3, o1.getJsonArray("coordinates").size()); }
/** * Test if a MultiPoint can be split correctly * @throws IOException if the test file could not be read */ @Test public void multiPoint() throws IOException { String filename = "multipoint.json"; long size = getFileSize(filename); List<Tuple2<GeoJsonChunkMeta, JsonObject>> chunks = split(filename); assertEquals(1, chunks.size()); Tuple2<GeoJsonChunkMeta, JsonObject> t1 = chunks.get(0); GeoJsonChunkMeta m1 = t1.v1; assertNull(m1.getParentFieldName()); assertEquals(0, m1.getStart()); assertEquals(size, m1.getEnd()); assertEquals("MultiPoint", m1.getType()); JsonObject o1 = t1.v2; assertEquals("MultiPoint", o1.getString("type")); assertEquals(2, o1.getJsonArray("coordinates").size()); }
/** * Test if a MultiPolygon can be split correctly * @throws IOException if the test file could not be read */ @Test public void multiPolygon() throws IOException { String filename = "multipolygon.json"; long size = getFileSize(filename); List<Tuple2<GeoJsonChunkMeta, JsonObject>> chunks = split(filename); assertEquals(1, chunks.size()); Tuple2<GeoJsonChunkMeta, JsonObject> t1 = chunks.get(0); GeoJsonChunkMeta m1 = t1.v1; assertNull(m1.getParentFieldName()); assertEquals(0, m1.getStart()); assertEquals(size, m1.getEnd()); assertEquals("MultiPolygon", m1.getType()); JsonObject o1 = t1.v2; assertEquals("MultiPolygon", o1.getString("type")); assertEquals(1, o1.getJsonArray("coordinates").size()); assertEquals(1, o1.getJsonArray("coordinates").getJsonArray(0).size()); assertEquals(13, o1.getJsonArray("coordinates").getJsonArray(0) .getJsonArray(0).size()); }
/** * Test if a Point can be split correctly * @throws IOException if the test file could not be read */ @Test public void point() throws IOException { String filename = "point.json"; long size = getFileSize(filename); List<Tuple2<GeoJsonChunkMeta, JsonObject>> chunks = split(filename); assertEquals(1, chunks.size()); Tuple2<GeoJsonChunkMeta, JsonObject> t1 = chunks.get(0); GeoJsonChunkMeta m1 = t1.v1; assertNull(m1.getParentFieldName()); assertEquals(0, m1.getStart()); assertEquals(size, m1.getEnd()); assertEquals("Point", m1.getType()); JsonObject o1 = t1.v2; assertEquals("Point", o1.getString("type")); assertEquals(2, o1.getJsonArray("coordinates").size()); }
/** * Test if a Polygon can be split correctly * @throws IOException if the test file could not be read */ @Test public void polygon() throws IOException { String filename = "polygon.json"; long size = getFileSize(filename); List<Tuple2<GeoJsonChunkMeta, JsonObject>> chunks = split(filename); assertEquals(1, chunks.size()); Tuple2<GeoJsonChunkMeta, JsonObject> t1 = chunks.get(0); GeoJsonChunkMeta m1 = t1.v1; assertNull(m1.getParentFieldName()); assertEquals(0, m1.getStart()); assertEquals(size, m1.getEnd()); assertEquals("Polygon", m1.getType()); JsonObject o1 = t1.v2; assertEquals("Polygon", o1.getString("type")); assertEquals(1, o1.getJsonArray("coordinates").size()); assertEquals(13, o1.getJsonArray("coordinates").getJsonArray(0).size()); }
@Test public void testGetAPIKeysBitfinex() { when(config.getString("bitfinex.apiKey")).thenReturn("API_KEY"); when(config.getString("bitfinex.apiSecretKey")) .thenReturn("API_SECRET_KEY"); configReader.setConfig(config); Tuple2<String, String> apiKeys = configReader.getAPIKeys("bitfinex"); String apiKey = apiKeys.v1(); String apiSecretKey = apiKeys.v2(); verify(config).getString("bitfinex.apiKey"); verify(config).getString("bitfinex.apiSecretKey"); verify(config, times(2)).getString(anyString()); assertEquals("API_KEY", apiKey); assertEquals("API_SECRET_KEY", apiSecretKey); }
@Test public void testGetAPIKeysBTC_E() { when(config.getString("btce.apiKey")).thenReturn("API_KEY"); when(config.getString("btce.apiSecretKey")) .thenReturn("API_SECRET_KEY"); configReader.setConfig(config); Tuple2<String, String> apiKeys = configReader.getAPIKeys("BTC-E"); String apiKey = apiKeys.v1(); String apiSecretKey = apiKeys.v2(); verify(config).getString("btce.apiKey"); verify(config).getString("btce.apiSecretKey"); verify(config, times(2)).getString(anyString()); assertEquals("API_KEY", apiKey); assertEquals("API_SECRET_KEY", apiSecretKey); }
@Override protected void update(Tuple2od<I> biv) { double norm = featureData.getItemFeatures(biv.v1) .map(Tuple2::v1) .mapToDouble(f -> biv.v2 / probNorm.getDouble(f)) .sum(); featureData.getItemFeatures(biv.v1).sequential() .map(Tuple2::v1) .forEach(f -> { double v = biv.v2 / (probNorm.getDouble(f) * norm); featureCount.addTo(f, v); }); lcf = getLcf(); }
/** * Returns a score for the recommendation list. * * @param recommendation recommendation list * @return score of the metric to the recommendation */ @Override public double evaluate(Recommendation<U, I> recommendation) { RelevanceModel.UserRelevanceModel<U, I> userRelModel = relModel.getModel(recommendation.getUser()); Set<F> subtopics = new HashSet<>(); int rank = 0; for (Tuple2od<I> iv : recommendation.getItems()) { if (userRelModel.isRelevant(iv.v1)) { subtopics.addAll(featureData.getItemFeatures(iv.v1) .map(Tuple2::v1) .collect(toList())); } rank++; if (rank >= cutoff) { break; } } return subtopics.size() / (double) featureData.numFeatures(); }
@Override protected double nov(Tuple2od<I> itemValue) { Set<F> itemFeatures = featureData.getItemFeatures(itemValue.v1) .map(Tuple2::v1) .collect(Collectors.toCollection(HashSet::new)); double iNonRed = featureCount.keySet().stream() .mapToDouble(f -> { if (itemFeatures.contains(f)) { return patienceLater.getDouble(f); } else { return patienceNow.getDouble(f); } }).reduce((x, y) -> x * y).orElse(1.0); int m = featureCount.size() + (int) itemFeatures.stream() .filter(f -> !featureCount.containsKey(f)) .count(); iNonRed = Math.pow(iNonRed, 1 / (double) m); return iNonRed; }
public List<LogicalFlow> findBySourcesAndTargets(List<Tuple2<EntityReference, EntityReference>> sourceAndTargets) { if(sourceAndTargets.isEmpty()) { return Collections.emptyList(); } Condition condition = sourceAndTargets .stream() .map(t -> isSourceCondition(t.v1) .and(isTargetCondition(t.v2)) .and(NOT_REMOVED)) .reduce((a, b) -> a.or(b)) .get(); List<LogicalFlow> fetch = baseQuery() .where(condition) .fetch(TO_DOMAIN_MAPPER); return fetch; }
public Map<Long, List<DatabaseInformation>> findByAppSelector(Select<Record1<Long>> appIdSelector) { return dsl .select(ENTITY_RELATIONSHIP.ID_A, ENTITY_RELATIONSHIP.KIND_A) .select(DATABASE_INFORMATION.fields()) .from(DATABASE_INFORMATION) .innerJoin(APPLICATION) .on(APPLICATION.ASSET_CODE.eq(DATABASE_INFORMATION.ASSET_CODE)) .where(APPLICATION.ID.in(appIdSelector)) .fetch() .stream() .map(r -> tuple( r.getValue(ENTITY_RELATIONSHIP.ID_A), DATABASE_RECORD_MAPPER.map(r))) .collect(groupingBy( Tuple2::v1, mapping(Tuple2::v2, Collectors.toList()) )); }
public List<Tuple2<Long, BigDecimal>> calculateCombinedAmountsForSelector(int year, Select<Record1<Long>> appIdSelector) { checkNotNull(appIdSelector, "appIdSelector cannot be null"); Field<BigDecimal> totalAmount = DSL.sum(ASSET_COST.AMOUNT).as("total_amount"); Condition condition = ASSET_COST.YEAR.eq(year) .and(APPLICATION.ID.in(appIdSelector)); return dsl.select(APPLICATION.ID, totalAmount) .from(ASSET_COST) .innerJoin(APPLICATION) .on(APPLICATION.ASSET_CODE.eq(ASSET_COST.ASSET_CODE)) .where(dsl.renderInlined(condition)) .groupBy(APPLICATION.ID) .fetch(r -> Tuple.tuple(r.value1(), r.value2())); }
@Test public void testCss_Ancestor() throws Exception { List<Tuple2<Predicate<StreamContext>,Integer>> list = ImmutableList.of( Tuple.tuple(Predicates.css("child4" ), 2), Tuple.tuple(Predicates.css("ancestor1 child4" ), 1), Tuple.tuple(Predicates.css("ancestor1 > parent1 > child4" ), 1), Tuple.tuple(Predicates.css("xml parent1 > child4" ), 1), Tuple.tuple(Predicates.css("xml parent1 > child4 + child5" ), 1), Tuple.tuple(Predicates.css("xml parent1 > child4 + child5 + child6" ), 1), Tuple.tuple(Predicates.css("xml parent1 > child4 ~ child5" ), 1), Tuple.tuple(Predicates.css("xml parent1 > child4 ~ child6" ), 1), Tuple.tuple(Predicates.css("xml parent1 > child1 ~ child3 ~ child5" ), 1), Tuple.tuple(Predicates.css("xml parent1 > child4 ~ child6 grandchild1" ), 1), Tuple.tuple(Predicates.css("xml parent1 > child4 + child6" ), 0), Tuple.tuple(Predicates.css("xml parent1 > child6 ~ child4" ), 0), Tuple.tuple(Predicates.css("xml parent1 > child4 ~ grandchild1" ), 0), Tuple.tuple(Predicates.css("xml parent1 > child6 ~ grandchild1" ), 0), Tuple.tuple(Predicates.css("ancestor1 > child4" ), 0), Tuple.tuple(Predicates.css("child4 ~ child6" ), 2), Tuple.tuple(Predicates.css("xml grandchild1" ), 2) ); test(list , "src/test/resources/css/children/children.xml"); }
@Test public void testCss_PseudoClass() throws Exception { List<Tuple2<Predicate<StreamContext>,Integer>> list = ImmutableList.of( Tuple.tuple(Predicates.css("child3:nth-child(2)" ), 0), Tuple.tuple(Predicates.css("child3:nth-child(3)" ), 1), Tuple.tuple(Predicates.css("child3:nth-child(4)" ), 1), Tuple.tuple(Predicates.css("child3:nth-child(5)" ), 0), Tuple.tuple(Predicates.css("child5:nth-of-type(2)" ), 1), Tuple.tuple(Predicates.css("child1:first-child" ), 1), Tuple.tuple(Predicates.css("child2:first-child" ), 0), Tuple.tuple(Predicates.css("child5:first-of-type" ), 1), Tuple.tuple(Predicates.css("grandchild2" ), 1), Tuple.tuple(Predicates.css("id#foo" ), 1) ); test(list , "src/test/resources/css/pseudoclass/pseudoclass.xml"); }
@Test public void authorsAndBooksQuery() throws SQLException { // All we need to execute a query is provide it with a connection and then // call fetch() on it. Tools.title("Selecting authorsAndBooks"); JdbcMapper<Tuple2<AuthorRecord, List<BookRecord>>> mapper = JdbcMapperFactory.newInstance() .addKeys("id").newMapper(new TypeReference<Tuple2<AuthorRecord, List<BookRecord>>>() { }); Tools.print(DSL.using(connection()) .select(AUTHOR.ID, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME, AUTHOR.DATE_OF_BIRTH, BOOK.ID, BOOK.TITLE) .from(AUTHOR).leftJoin(BOOK).on(BOOK.AUTHOR_ID.eq(AUTHOR.ID)) .orderBy(AUTHOR.ID).fetch()); }
@Test public void authorsAndBooks() throws SQLException { // All we need to execute a query is provide it with a connection and then // call fetch() on it. Tools.title("Selecting authorsAndBooks"); JdbcMapper<Tuple2<AuthorRecord, List<BookRecord>>> mapper = JdbcMapperFactory.newInstance() .addKeys("id").newMapper(new TypeReference<Tuple2<AuthorRecord, List<BookRecord>>>() { }); try (ResultSet rs = DSL.using(connection()) .select(AUTHOR.ID, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME, AUTHOR.DATE_OF_BIRTH, BOOK.ID, BOOK.TITLE) .from(AUTHOR).leftJoin(BOOK).on(BOOK.AUTHOR_ID.eq(AUTHOR.ID)) .orderBy(AUTHOR.ID).fetchResultSet()) { mapper.stream(rs).forEach(Tools::print); } }
@SuppressWarnings({ "unchecked" }) WindowImpl( Tuple2<T, Long> value, Partition<T> partition, WindowSpecification<T> specification ) { this.value = value; this.partition = partition; this.order = specification.order().orElse((Comparator<? super T>) naturalOrder()); this.lower = specification.lower(); this.upper = specification.upper(); int i = specification.order().isPresent() ? binarySearch(partition.list, value, comparing((Tuple2<T, Long> t) -> t.v1, specification.order().get()).thenComparing(t -> t.v2)) : binarySearch(partition.list, value, comparing(t -> t.v2)); this.index = (i >= 0 ? i : -i - 1); }
@Test public void testGroupedWithCollector() throws Exception { List<Tuple2<Integer, List<Integer>>> l1 = Seq.of(1, 2, 3, 4) .grouped(x -> x % 2, Collectors.toList()) .toList(); assertEquals(asList( Tuple.tuple(1, Arrays.asList(1, 3)), Tuple.tuple(0, Arrays.asList(2, 4)) ), l1); List<Tuple2<Integer, String>> l2 = Seq.of(1, 2, 3, 4) .grouped(x -> x % 2, Collectors.mapping(Object::toString, Collectors.joining(", "))) .toList(); assertEquals(asList( Tuple.tuple(1, "1, 3"), Tuple.tuple(0, "2, 4") ), l2); }
@Test public void testConsumer5to3() { Tuple2<Integer, Integer> t1 = tuple(4, 4); Tuple3<Integer, Integer, Integer> t2 = tuple(5, 3, 2); // Concat the two and three tuples and apply them together. lift(this::fiveArgConsumer).accept(t1.concat(t2)); int normal1 = result; // Accept partially the first two values, then accept the remaining three lift(this::fiveArgConsumer).acceptPartially(t1.v1, t1.v2).accept(t2.v1, t2.v2, t2.v3); int partiallyAppliedExplicitExplicit = result; lift(this::fiveArgConsumer).acceptPartially(t1.v1, t1.v2).accept(t2); int partiallyAppliedExplicitTuple = result; lift(this::fiveArgConsumer).acceptPartially(t1).accept(t2.v1, t2.v2, t2.v3); int partiallyAppliedTupleExplicit = result; lift(this::fiveArgConsumer).acceptPartially(t1).accept(t2); int partiallyAppliedTupleTuple = result; assertEquals(normal1, partiallyAppliedExplicitExplicit); assertEquals(normal1, partiallyAppliedExplicitTuple); assertEquals(normal1, partiallyAppliedTupleExplicit); assertEquals(normal1, partiallyAppliedTupleTuple); }
@Test public void testEqualsHashCode() { Set<Tuple2<Integer, String>> set = new HashSet<>(); set.add(tuple(1, "abc")); assertEquals(1, set.size()); set.add(tuple(1, "abc")); assertEquals(1, set.size()); set.add(tuple(null, null)); assertEquals(2, set.size()); set.add(tuple(null, null)); assertEquals(2, set.size()); set.add(tuple(1, null)); assertEquals(3, set.size()); set.add(tuple(1, null)); assertEquals(3, set.size()); }
/** * Map this stream to a windowed stream with 2 distinct windows. */ @Generated("This method was generated using jOOQ-tools") default Seq<Tuple2<Window<T>, Window<T>>> window( WindowSpecification<T> specification1, WindowSpecification<T> specification2 ) { List<Tuple2<T, Long>> buffer = zipWithIndex().toList(); Map<?, Partition<T>> partitions1 = SeqUtils.partitions(specification1, buffer); Map<?, Partition<T>> partitions2 = SeqUtils.partitions(specification2, buffer); return seq(buffer) .map(t -> tuple( (Window<T>) new WindowImpl<>(t, partitions1.get(specification1.partition().apply(t.v1)), specification1), (Window<T>) new WindowImpl<>(t, partitions2.get(specification2.partition().apply(t.v1)), specification2) )) .onClose(this::close); }
/** * Map this stream to a windowed stream with 4 distinct windows. */ @Generated("This method was generated using jOOQ-tools") default Seq<Tuple4<Window<T>, Window<T>, Window<T>, Window<T>>> window( WindowSpecification<T> specification1, WindowSpecification<T> specification2, WindowSpecification<T> specification3, WindowSpecification<T> specification4 ) { List<Tuple2<T, Long>> buffer = zipWithIndex().toList(); Map<?, Partition<T>> partitions1 = SeqUtils.partitions(specification1, buffer); Map<?, Partition<T>> partitions2 = SeqUtils.partitions(specification2, buffer); Map<?, Partition<T>> partitions3 = SeqUtils.partitions(specification3, buffer); Map<?, Partition<T>> partitions4 = SeqUtils.partitions(specification4, buffer); return seq(buffer) .map(t -> tuple( (Window<T>) new WindowImpl<>(t, partitions1.get(specification1.partition().apply(t.v1)), specification1), (Window<T>) new WindowImpl<>(t, partitions2.get(specification2.partition().apply(t.v1)), specification2), (Window<T>) new WindowImpl<>(t, partitions3.get(specification3.partition().apply(t.v1)), specification3), (Window<T>) new WindowImpl<>(t, partitions4.get(specification4.partition().apply(t.v1)), specification4) )) .onClose(this::close); }
@Override public ProductId getRelatedProductId(AssetId baseAssetId, AssetId quoteAssetId) throws NoSuchProductException { Tuple2<AssetId, AssetId> assetKey = Tuple.tuple(baseAssetId, quoteAssetId); ProductId id = assetIdMap.get(assetKey); if (id == null) { throw new NoSuchProductException("no product found for assets " + baseAssetId + "/" + quoteAssetId); } return id; }
private static String mapAndGetOriginTable(Path tempDBPath, List<ValueMapping> map, final JDefaultDict<String, ConcurrentMap<ValueMapping, Tuple2<String, String>>> foreignKeyMapping, final ConcurrentMap<ValueMapping, Joiner> joiners) throws IOException { try (final Database db = DatabaseBuilder.open(tempDBPath.toFile());) { // Populate the table mapping for each value mapping return parseTableMappings(map, db, foreignKeyMapping, joiners); } }
private static String parseTableMappings(List<ValueMapping> map, final Database db, JDefaultDict<String, ConcurrentMap<ValueMapping, Tuple2<String, String>>> foreignKeyMapping, ConcurrentMap<ValueMapping, Joiner> joiners) throws IOException { String originTable = map.isEmpty() ? null : db.getTable(CSVUtil.DOT_PATTERN.split(map.get(0).getInputField())[0]).getName(); // for (final ValueMapping nextValueMapping : map) { // Must be a sequential mapping as ordering is important map.stream().sequential().forEach(Unchecked.consumer(nextValueMapping -> { if (nextValueMapping.getLanguage() == ValueMappingLanguage.ACCESS) { final String[] splitDBField = CSVUtil.DOT_PATTERN.split(nextValueMapping.getInputField()); System.out.println(nextValueMapping.getInputField()); final Table nextTable = db.getTable(splitDBField[0]); final String[] splitForeignDBField = CSVUtil.DOT_PATTERN.split(nextValueMapping.getMapping()); final Table nextForeignTable = db.getTable(splitForeignDBField[0]); if (nextForeignTable == null) { throw new RuntimeException( "Could not find table referenced by access mapping: " + nextValueMapping.getMapping()); } foreignKeyMapping.get(splitForeignDBField[0]).put(nextValueMapping, Tuple.tuple(nextTable.getName(), nextForeignTable.getName())); try { final Joiner create = Joiner.create(nextTable, nextForeignTable); if (create != null) { joiners.put(nextValueMapping, create); System.out.println("PK->FK: " + joiners.get(nextValueMapping).toFKString()); } } catch (IllegalArgumentException e) { e.printStackTrace(); } } })); return originTable; }
@Override public Map evaluateUnsafe(EvaluationContext context) { // evaluate all values for each key and return the resulting map return Seq.seq(map) .map(entry -> entry.map2(value -> value.evaluateUnsafe(context))) .toMap(Tuple2::v1, Tuple2::v2); }