Java Code Examples for reactor.util.function.Tuple2#getT2()
The following examples show how to use
reactor.util.function.Tuple2#getT2() .
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: MigrationTask.java From james-project with Apache License 2.0 | 6 votes |
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 2
Source File: CloudFoundryNativeReactiveDiscoveryClient.java From spring-cloud-cloudfoundry with Apache License 2.0 | 6 votes |
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 3
Source File: UserServiceImpl.java From alibaba-rsocket-broker with Apache License 2.0 | 5 votes |
@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 4
Source File: CtrlSosReportApiCallHandler.java From linstor-server with GNU General Public License v3.0 | 5 votes |
private Flux<String> assembleReport( Set<String> nodes, List<Tuple2<NodeName, ByteArrayInputStream>> sosReportAnswers, Path tmpDir, Date since ) throws IOException, AccessDeniedException, ChildProcessTimeoutException, ExtCmdFailedException { if (containsController(nodes)) { createControllerFilesInto(tmpDir, since); } for (Tuple2<NodeName, ByteArrayInputStream> sosReportAnswer : sosReportAnswers) { ByteArrayInputStream sosReportMsgDataIn = sosReportAnswer.getT2(); deserializeErrorReportsInto(sosReportMsgDataIn, tmpDir); } String fileName = errorReporter.getLogDirectory() + "/" + SOS_PREFIX + SDF_UTC.format(new Date()) + SOS_SUFFIX; HashSet<String> copyNodes = new HashSet<>(); nodes.forEach(node -> copyNodes.add(node.toLowerCase())); Stream<Node> nodeStream = nodeRepository.getMapForView(peerAccCtx.get()).values().stream() .filter( node -> copyNodes.isEmpty() || copyNodes.contains(node.getName().getDisplayName().toLowerCase()) ); List<String> names = nodeStream.map(node -> node.getName().displayValue).collect(Collectors.toList()); if (containsController(nodes)) { names.add("_" + LinStor.CONTROLLER_MODULE); } createTar(tmpDir, fileName, names); return Flux.just(fileName); }
Example 5
Source File: CtrlErrorListApiCallHandler.java From linstor-server with GNU General Public License v3.0 | 5 votes |
private List<ErrorReport> assembleList( Set<String> nodesToRequest, boolean withContent, @Nullable final Date since, @Nullable final Date to, final Set<String> ids, List<Tuple2<NodeName, ByteArrayInputStream>> errorReportsAnswers) throws IOException { List<ErrorReport> errorReports = new ArrayList<>(); // Controller error reports if (nodesToRequest.isEmpty() || nodesToRequest.stream().anyMatch(LinStor.CONTROLLER_MODULE::equalsIgnoreCase)) { errorReports.addAll(errorReporter.listReports( withContent, since, to, ids )); } // Returned satellite error reports for (Tuple2<NodeName, ByteArrayInputStream> errorReportAnswer : errorReportsAnswers) { // NodeName nodeName = errorReportAnswer.getT1(); ByteArrayInputStream errorReportMsgDataIn = errorReportAnswer.getT2(); errorReports.addAll(deserializeErrorReports(errorReportMsgDataIn)); } return errorReports; }
Example 6
Source File: ReactorNettySender.java From micrometer with Apache License 2.0 | 5 votes |
@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 7
Source File: BeanFactoryAwareFunctionRegistryTests.java From spring-cloud-function with Apache License 2.0 | 5 votes |
@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 8
Source File: Repeater.java From spring-cloud-function with Apache License 2.0 | 5 votes |
@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 9
Source File: RequestHelper.java From linstor-server with GNU General Public License v3.0 | 4 votes |
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 |
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 |
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 |
@Test public void serverCompressionPredicateTrue() throws Exception { HttpServer server = HttpServer.create() .port(0) .compress((req, res) -> true) .wiretap(true); DisposableServer connection = server.handle((in, out) -> out.sendString(Mono.just("reply"))) .bindNow(); //don't activate compression on the client options to avoid auto-handling (which removes the header) HttpClient client = HttpClient.create() .remoteAddress(connection::address); Tuple2<HttpHeaders, byte[]> resp = //edit the header manually to attempt to trigger compression on server side client.headers(h -> h.add("Accept-Encoding", "gzip")) .wiretap(true) .get() .uri("/test") .responseSingle((res, byteBufMono) -> Mono.just(res.responseHeaders()) .zipWith(byteBufMono .asByteArray()) .log()) .block(); assertThat(resp).isNotNull(); assertThat(resp.getT1().get("content-encoding")).isEqualTo("gzip"); byte[] replyBuffer = resp.getT2(); assertThat(new String(replyBuffer, Charset.defaultCharset())).isNotEqualTo("reply"); GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(replyBuffer)); 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"); connection.dispose(); connection.onDispose() .block(); }
Example 13
Source File: ReactorClient.java From selenium with Apache License 2.0 | 4 votes |
@Override public HttpResponse execute(HttpRequest request) { StringBuilder uri = new StringBuilder(request.getUri()); List<String> queryPairs = new ArrayList<>(); request.getQueryParameterNames().forEach( name -> request.getQueryParameters(name).forEach( value -> { try { queryPairs.add( URLEncoder.encode(name, UTF_8.toString()) + "=" + URLEncoder.encode(value, UTF_8.toString())); } catch (UnsupportedEncodingException e) { Thread.currentThread().interrupt(); throw new UncheckedIOException(e); } })); if (!queryPairs.isEmpty()) { uri.append("?"); Joiner.on('&').appendTo(uri, queryPairs); } Tuple2<InputStream, HttpResponse> result = httpClient .headers(h -> { request.getHeaderNames().forEach( name -> request.getHeaders(name).forEach(value -> h.set(name, value))); if (request.getHeader("User-Agent") == null) { h.set("User-Agent", AddSeleniumUserAgent.USER_AGENT); } } ) .request(methodMap.get(request.getMethod())) .uri(uri.toString()) .send((r, out) -> out.send(fromInputStream(request.getContent().get()))) .responseSingle((res, buf) -> { HttpResponse toReturn = new HttpResponse(); toReturn.setStatus(res.status().code()); res.responseHeaders().entries().forEach( entry -> toReturn.addHeader(entry.getKey(), entry.getValue())); return buf.asInputStream() .switchIfEmpty(Mono.just(new ByteArrayInputStream("".getBytes()))) .zipWith(Mono.just(toReturn)); }).block(); result.getT2().setContent(result::getT1); return result.getT2(); }