Java Code Examples for reactor.util.function.Tuple2#getT1()

The following examples show how to use reactor.util.function.Tuple2#getT1() . 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: CtrlSnapshotRollbackApiCallHandler.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
private Tuple2<NodeName, Flux<ApiCallRc>> handleRollbackResponse(
    ResourceName rscName,
    Tuple2<NodeName, Flux<ApiCallRc>> nodeResponse
)
{
    NodeName nodeName = nodeResponse.getT1();

    return nodeResponse.mapT2(responses -> responses
        .concatWith(scopeRunner
            .fluxInTransactionalScope(
                "Handle successful rollback",
                lockGuardFactory.create()
                    .read(LockObj.NODES_MAP)
                    .write(LockObj.RSC_DFN_MAP)
                    .buildDeferred(),
                () -> resourceRollbackSuccessfulInTransaction(rscName, nodeName)
            )
        )
    );
}
 
Example 2
Source File: MigrationTask.java    From james-project with Apache License 2.0 6 votes vote down vote up
private void runMigration(Tuple2<SchemaTransition, Migration> tuple) throws InterruptedException {
    SchemaVersion currentVersion = getCurrentVersion();
    SchemaTransition transition = tuple.getT1();
    SchemaVersion targetVersion = transition.to();
    if (currentVersion.isAfterOrEquals(targetVersion)) {
        return;
    }

    LOGGER.info("Migrating to version {} ", transition.toAsString());
    Migration migration = tuple.getT2();
    migration.asTask().run()
        .onComplete(
            () -> schemaVersionDAO.updateVersion(transition.to()).block(),
            () -> LOGGER.info("Migrating to version {} done", transition.toAsString()))
        .onFailure(
            () -> LOGGER.warn(failureMessage(transition.to())),
            () -> throwMigrationException(transition.to()));
}
 
Example 3
Source File: CloudFoundryNativeReactiveDiscoveryClient.java    From spring-cloud-cloudfoundry with Apache License 2.0 6 votes vote down vote up
protected ServiceInstance mapApplicationInstanceToServiceInstance(
		Tuple2<ApplicationDetail, InstanceDetail> tuple) {
	ApplicationDetail applicationDetail = tuple.getT1();
	InstanceDetail instanceDetail = tuple.getT2();

	String applicationId = applicationDetail.getId();
	String applicationIndex = instanceDetail.getIndex();
	String instanceId = applicationId + "." + applicationIndex;
	String name = applicationDetail.getName();
	String url = applicationDetail.getUrls().size() > 0
			? applicationDetail.getUrls().get(0) : null;
	boolean secure = (url + "").toLowerCase().startsWith("https");

	HashMap<String, String> metadata = new HashMap<>();
	metadata.put("applicationId", applicationId);
	metadata.put("instanceId", applicationIndex);

	return new DefaultServiceInstance(instanceId, name, url, secure ? 443 : 80,
			secure, metadata);
}
 
Example 4
Source File: UserServiceImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ByteBuf> findUserByIdAndNick(ByteBuf byteBuf) {
    Tuple2<Integer, String> tuple2 = ByteBufTuples.of(byteBuf, Integer.class, String.class);
    //language=json
    String jsonData = "{\n" +
            "  \"id\": " + tuple2.getT1() + ",\n" +
            "  \"nick\": \"" + tuple2.getT2() + "\"\n" +
            "}";
    return Mono.just(Unpooled.wrappedBuffer(jsonData.getBytes(StandardCharsets.UTF_8)));
}
 
Example 5
Source File: ReactorNettySender.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public Response send(Request request) {
    Tuple2<Integer, String> response = httpClient
            .request(toNettyHttpMethod(request.getMethod()))
            .uri(request.getUrl().toString())
            .send((httpClientRequest, nettyOutbound) -> {
                request.getRequestHeaders().forEach(httpClientRequest::addHeader);
                return nettyOutbound.sendByteArray(Mono.just(request.getEntity()));
            })
            .responseSingle((r, body) -> Mono.just(r.status().code()).zipWith(body.asString().defaultIfEmpty("")))
            .block();

    return new Response(response.getT1(), response.getT2());
}
 
Example 6
Source File: BeanFactoryAwareFunctionRegistryTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected Object convertFromInternal(
		Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) {
	Tuple2<String, String> payload = (Tuple2<String, String>) message.getPayload();

	String convertedPayload = payload.getT1() + "," + payload.getT2();
	return convertedPayload;
}
 
Example 7
Source File: Repeater.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Override
public Tuple2<Flux<String>, Flux<Integer>> apply(Tuple2<Flux<String>, Flux<Integer>> inputs) {
    Flux<String> stringFlux = inputs.getT1();
    Flux<Integer> integerFlux = inputs.getT2();
    Flux<Integer> sharedIntFlux = integerFlux.publish().autoConnect(2);

    Flux<String> repeated = stringFlux.zipWith(sharedIntFlux)
            .flatMap(t -> Flux.fromIterable(Collections.nCopies(t.getT2(), t.getT1())));

    Flux<Integer> sum = sharedIntFlux.buffer(2, 1)
            .map(l -> l.stream().mapToInt(Integer::intValue).sum())
            ;

    return Tuples.of(repeated, sum);
}
 
Example 8
Source File: EndpointPolicyExecutorTask.java    From cf-butler with Apache License 2.0 4 votes vote down vote up
private static List<EmailAttachment> buildAttachments(List<Tuple2<String, ResponseEntity<String>>> tuples) {
    List<EmailAttachment> result = new ArrayList<>();
    for (Tuple2<String, ResponseEntity<String>> t: tuples) {
        String filename = t.getT1();
        String content = t.getT2().getBody();
        String mimeType = t.getT2().getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        if (StringUtils.isNotBlank(content)) {
            if (mimeType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
                result.add(
                    EmailAttachment
                        .builder()
                            .filename(filename)
                            .content(content)
                            .extension(".json")
                            .mimeType(mimeType)
                            .build()
                );
            } else if (mimeType.startsWith(MediaType.TEXT_PLAIN_VALUE)) {
                result.add(
                    EmailAttachment
                        .builder()
                            .filename(filename)
                            .content(content)
                            .extension(".txt")
                            .mimeType(mimeType)
                            .build()
                );
            }
        } else {
            result.add(
                EmailAttachment
                    .builder()
                        .filename(t.getT1())
                        .content("No results")
                        .extension(".txt")
                        .mimeType("text/plain")
                        .build()
            );
        }
    }
    return result;
}
 
Example 9
Source File: RequestHelper.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
private void checkLDAPAuth(Peer peer, String authHeader)
{
    if (linstorConfig.isLdapEnabled())
    {
        // request.getAuthorization() contains authorization http field
        if (authHeader != null)
        {
            Tuple2<String, String> userPassword = parseBasicAuthHeader(authHeader);
            String user = userPassword.getT1();
            String password = userPassword.getT2();

            try
            {
                AccessContext clientCtx = authentication.signIn(
                    new IdentityName(user),
                    password.getBytes(StandardCharsets.UTF_8)
                );
                AccessContext privCtx = sysContext.clone();
                privCtx.getEffectivePrivs().enablePrivileges(Privilege.PRIV_SYS_ALL);
                peer.setAccessContext(privCtx, clientCtx);
            }
            catch (AccessDeniedException accExc)
            {
                throw new ImplementationError(
                    "Enabling privileges on the system context failed",
                    accExc
                );
            }
            catch (InvalidNameException nameExc)
            {
                throw new ApiRcException(
                    ApiCallRcImpl.singleApiCallRc(ApiConsts.FAIL_SIGN_IN, nameExc.getMessage())
                );
            }
            catch (SignInException signIgnExc)
            {
                throw new ApiRcException(
                    ApiCallRcImpl.singleApiCallRc(ApiConsts.FAIL_SIGN_IN, signIgnExc)
                );
            }
        }
        else
        {
            if (!linstorConfig.isLdapPublicAccessAllowed())
            {
                ApiCallRc apiCallRc = ApiCallRcImpl.singleApiCallRc(
                    ApiConsts.FAIL_SIGN_IN_MISSING_CREDENTIALS,
                    "Login required but no 'Authorization' header given."
                );
                throw new ApiRcException(apiCallRc);
            }
        }
    }
}
 
Example 10
Source File: VlmAllocatedFetcherProto.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
private Map<Volume.Key, VlmAllocatedResult> parseVlmAllocated(
    List<Tuple2<NodeName, ByteArrayInputStream>> vlmAllocatedAnswers)
{
    Map<Volume.Key, VlmAllocatedResult> vlmAllocatedCapacities = new HashMap<>();

    try
    {
        for (Tuple2<NodeName, ByteArrayInputStream> vlmAllocatedAnswer : vlmAllocatedAnswers)
        {
            NodeName nodeName = vlmAllocatedAnswer.getT1();
            ByteArrayInputStream vlmAllocatedMsgDataIn = vlmAllocatedAnswer.getT2();

            MsgIntVlmAllocated nodeVlmAllocated = MsgIntVlmAllocated.parseDelimitedFrom(vlmAllocatedMsgDataIn);
            for (VlmAllocated vlmAllocated : nodeVlmAllocated.getAllocatedCapacitiesList())
            {
                ApiCallRcImpl apiCallRc = new ApiCallRcImpl();
                for (ApiCallResponse msgApiCallResponse : vlmAllocated.getErrorsList())
                {
                    apiCallRc.addEntry(ProtoDeserializationUtils.parseApiCallRc(
                        msgApiCallResponse,
                        "Node: '" + nodeName +
                            "', resource: '" + vlmAllocated.getRscName() +
                            "', volume: " + vlmAllocated.getVlmNr() + " - "
                    ));
                }

                vlmAllocatedCapacities.put(
                    new Volume.Key(
                        nodeName,
                        new ResourceName(vlmAllocated.getRscName()),
                        new VolumeNumber(vlmAllocated.getVlmNr())
                    ),
                    new VlmAllocatedResult(vlmAllocated.getAllocated(), apiCallRc)
                );
            }
        }
    }
    catch (IOException | InvalidNameException | ValueOutOfRangeException exc)
    {
        throw new ImplementationError(exc);
    }

    return vlmAllocatedCapacities;
}
 
Example 11
Source File: FreeCapacityFetcherProto.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
private Flux<Tuple2<StorPool.Key, Tuple2<SpaceInfo, List<ApiCallRc>>>> parseFreeSpacesInTransaction(
    Tuple2<NodeName, ByteArrayInputStream> freeSpaceAnswer
)
{
    List<Tuple2<Key, Tuple2<SpaceInfo, List<ApiCallRc>>>> ret = new ArrayList<>();
    try
    {
        NodeName nodeName = freeSpaceAnswer.getT1();
        ByteArrayInputStream freeSpaceMsgDataIn = freeSpaceAnswer.getT2();

        MsgIntFreeSpace freeSpaces = MsgIntFreeSpace.parseDelimitedFrom(freeSpaceMsgDataIn);
        for (StorPoolFreeSpace freeSpaceInfo : freeSpaces.getFreeSpacesList())
        {
            List<ApiCallRc> apiCallRcs = new ArrayList<>();
            if (freeSpaceInfo.getErrorsCount() > 0)
            {
                ApiCallRcImpl apiCallRc = new ApiCallRcImpl();
                for (ApiCallResponse msgApiCallResponse : freeSpaceInfo.getErrorsList())
                {
                    apiCallRc.addEntry(
                        ProtoDeserializationUtils.parseApiCallRc(
                            msgApiCallResponse,
                            "Node: '" + nodeName + "', storage pool: '" + freeSpaceInfo.getStorPoolName() +
                                "' - "
                        )
                    );
                }
                apiCallRcs.add(apiCallRc);
            }

            StorPoolName storPoolName = new StorPoolName(freeSpaceInfo.getStorPoolName());
            long freeCapacity = freeSpaceInfo.getFreeCapacity();
            long totalCapacity = freeSpaceInfo.getTotalCapacity();

            ret.add(
                Tuples.of(
                    new StorPool.Key(nodeName, storPoolName),
                    Tuples.of(
                        new SpaceInfo(totalCapacity, freeCapacity),
                        apiCallRcs
                    )
                )
            );

            // also update storage pool's freespacemanager
            StorPool storPool = nodeRepository.get(apiCtx, nodeName).getStorPool(apiCtx, storPoolName);
            storPool.getFreeSpaceTracker().setCapacityInfo(apiCtx, freeCapacity, totalCapacity);

            ctrlTransactionHelper.commit();
        }
    }
    catch (IOException | InvalidNameException | AccessDeniedException exc)
    {
        throw new ImplementationError(exc);
    }
    return Flux.just(ret.toArray(new Tuple2[0]));
}
 
Example 12
Source File: HttpCompressionClientServerTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void serverCompressionAlwaysEnabled() throws Exception {
	HttpServer server = HttpServer.create()
	                              .port(0)
	                              .compress(true);

	DisposableServer runningServer =
			server.handle((in, out) -> out.sendString(Mono.just("reply")))
			      .wiretap(true)
			      .bindNow(Duration.ofSeconds(10));

	//don't activate compression on the client options to avoid auto-handling (which removes the header)
	HttpClient client = HttpClient.create()
			                      .remoteAddress(runningServer::address)
	                              .compress(false)
			                      .wiretap(true);
	Tuple2<byte[], HttpHeaders> resp =
			//edit the header manually to attempt to trigger compression on server side
			client.headers(h -> h.add("Accept-Encoding", "gzip"))
			      .get()
			      .uri("/test")
			      .responseSingle((res, buf) -> buf.asByteArray()
			                                       .zipWith(Mono.just(res.responseHeaders())))
			      .block();

	assertThat(resp).isNotNull();
	assertThat(resp.getT2().get("content-encoding")).isEqualTo("gzip");

	assertThat(new String(resp.getT1(), Charset.defaultCharset())).isNotEqualTo("reply");

	GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(resp.getT1()));
	byte[] deflatedBuf = new byte[1024];
	int readable = gis.read(deflatedBuf);
	gis.close();

	assertThat(readable).isGreaterThan(0);

	String deflated = new String(deflatedBuf, 0, readable, Charset.defaultCharset());

	assertThat(deflated).isEqualTo("reply");

	runningServer.dispose();
	runningServer.onDispose()
	          .block();
}
 
Example 13
Source File: HttpCompressionClientServerTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void serverCompressionEnabledBigResponse() throws Exception {
	HttpServer server = HttpServer.create()
	                              .port(0)
	                              .compress(4);

	DisposableServer runningServer =
			server.handle((in, out) -> out.sendString(Mono.just("reply")))
			      .wiretap(true)
			      .bindNow(Duration.ofSeconds(10));

	//don't activate compression on the client options to avoid auto-handling (which removes the header)
	HttpClient client = HttpClient.create()
			                      .remoteAddress(runningServer::address)
			                      .wiretap(true);
	Tuple2<byte[], HttpHeaders> resp =
			//edit the header manually to attempt to trigger compression on server side
			client.headers(h -> h.add("accept-encoding", "gzip"))
			      .get()
			      .uri("/test")
			      .responseSingle((res, buf) -> buf.asByteArray()
			                                       .zipWith(Mono.just(res.responseHeaders())))
			      .block();

	assertThat(resp).isNotNull();
	assertThat(resp.getT2().get("content-encoding")).isEqualTo("gzip");

	assertThat(new String(resp.getT1(), Charset.defaultCharset())).isNotEqualTo("reply");

	GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(resp.getT1()));
	byte[] deflatedBuf = new byte[1024];
	int readable = gis.read(deflatedBuf);
	gis.close();

	assertThat(readable).isGreaterThan(0);

	String deflated = new String(deflatedBuf, 0, readable, Charset.defaultCharset());

	assertThat(deflated).isEqualTo("reply");

	runningServer.dispose();
	runningServer.onDispose()
	          .block();
}
 
Example 14
Source File: MyFn.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
@Override
public Tuple2<Flux<Double>, Flux<String>> apply(Tuple2<Flux<String>, Flux<Integer>> inputs) {
    Flux<String> words = inputs.getT1();
    Flux<Integer> numbers = inputs.getT2().publish().autoConnect(2);


    Flux<Double> avg = numbers.buffer(2, 1)
            .map(l -> l.stream().mapToInt(Integer::intValue).average().getAsDouble())
            .take(3);

    Flux<String> repeated = words.zipWith(numbers)
            .flatMap(t -> Flux.fromIterable(Collections.nCopies(t.getT2(), t.getT1())));

    return Tuples.of(avg, repeated);

}