Java Code Examples for reactor.core.publisher.Mono#flatMap()

The following examples show how to use reactor.core.publisher.Mono#flatMap() . 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: VpcManagerServiceProxy.java    From alcor with Apache License 2.0 6 votes vote down vote up
public Mono<ResponseId> deleteVpcById(String projectId, String vpcId) {
    Mono<ClientResponse> response = webClient
            .delete()
            .uri(webDestinations.getVpcManagerServiceUrl() + "/project/{projectId}/vpcs/{vpcId}", projectId, vpcId)
            .exchange();
    return response.flatMap(resp -> {
        switch (resp.statusCode()) {
            case OK:
                return resp.bodyToMono(ResponseId.class);
            case NOT_FOUND:
                return Mono.error(new VpcNotFoundException());
            default:
                return Mono.error(new RuntimeException("Unknown" + resp.statusCode()));
        }
    });
}
 
Example 2
Source File: SubnetManagerServiceProxy.java    From alcor with Apache License 2.0 6 votes vote down vote up
public Mono<SubnetWebJson> updateSubnetById(UUID projectId, UUID subnetId, Mono<SubnetWebJson> updatedSubnetJson) {
    Mono<ClientResponse> response = webClient
            .put()
            .uri(webDestinations.getSubnetManagerServiceUrl() + "/project/{projectId}/subnets/{subnetId}", projectId, subnetId)
            .body(updatedSubnetJson, SubnetWebJson.class)
            .exchange();
    return response.flatMap(resp -> {
        switch (resp.statusCode()) {
            case OK:
                return resp.bodyToMono(SubnetWebJson.class);
            case NOT_FOUND:
                return Mono.error(new SubnetNotFoundException());
            default:
                return Mono.error(new RuntimeException("Unknown" + resp.statusCode()));
        }
    });
}
 
Example 3
Source File: BaseGuildChannel.java    From Discord4J with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Mono<PermissionSet> getEffectivePermissions(Snowflake memberId) {
    Mono<Member> getMember = getClient().getMemberById(getGuildId(), memberId);
    Mono<PermissionSet> getBasePerms = getMember.flatMap(Member::getBasePermissions);

    return Mono.zip(getMember, getBasePerms, (member, basePerms) -> {
        PermissionOverwrite everyoneOverwrite = getOverwriteForRole(getGuildId()).orElse(null);

        List<PermissionOverwrite> roleOverwrites = member.getRoleIds().stream()
                .map(this::getOverwriteForRole)
                .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) // jdk 9 Optional#stream
                .collect(Collectors.toList());
        PermissionOverwrite memberOverwrite = getOverwriteForMember(member.getId()).orElse(null);

        return PermissionUtil.computePermissions(basePerms, everyoneOverwrite, roleOverwrites, memberOverwrite);
    });
}
 
Example 4
Source File: SubnetManagerServiceProxy.java    From alcor with Apache License 2.0 6 votes vote down vote up
public Mono<ResponseId> deleteSubnetById(UUID projectId, UUID subnetId) {
    Mono<ClientResponse> response = webClient
            .delete()
            .uri(webDestinations.getSubnetManagerServiceUrl() + "/project/{projectId}/subnets/{subnetId}", projectId, subnetId)
            .exchange();
    return response.flatMap(resp -> {
        switch (resp.statusCode()) {
            case OK:
                return resp.bodyToMono(ResponseId.class);
            case NOT_FOUND:
                return Mono.error(new SubnetNotFoundException());
            default:
                return Mono.error(new RuntimeException("Unknown" + resp.statusCode()));
        }
    });
}
 
Example 5
Source File: UserHandler.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * DELETE a User
 */
public Mono<ServerResponse> deleteUser(ServerRequest request) {
    // parse id from path-variable
    long customerId = Long.valueOf(request.pathVariable("id"));

    // get customer from repository 
    Mono<String> responseMono = customerRepository.deleteUser(customerId);

    // build response
    return responseMono
        .flatMap(strMono -> ServerResponse.ok().contentType(MediaType.TEXT_PLAIN).body(fromObject(strMono)));
}
 
Example 6
Source File: SunriseSunsetServiceImpl.java    From reactive-ms-example with MIT License 5 votes vote down vote up
Mono<String> buildUrl(final Mono<GeographicCoordinates> geographicCoordinatesMono) {
    return geographicCoordinatesMono.flatMap(geographicCoordinates -> Mono.just(endPoint
            .concat(BEGIN_PARAMETERS)
            .concat(LATITUDE_PARAMETER).concat(Double.toString(geographicCoordinates.getLatitude()))
            .concat(NEXT_PARAMETER)
            .concat(LONGITUDE_PARAMETER).concat(Double.toString(geographicCoordinates.getLongitude()))
            .concat(NEXT_PARAMETER)
            .concat(DATE_PARAMETER).concat(TODAY_DATE)
            .concat(NEXT_PARAMETER)
            .concat(FORMATTED_PARAMETER).concat(NOT_FORMATTED)
    ));
}
 
Example 7
Source File: RedisRouteDefinitionRepository.java    From SpringCloud with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> save(Mono<RouteDefinition> route) {
    return route.flatMap(routeDefinition -> {
        routeService.save(routeDefinition);
        return Mono.empty();
    });
}
 
Example 8
Source File: CfBlueGreenStage1Delegate.java    From ya-cf-app-gradle-plugin with Apache License 2.0 5 votes vote down vote up
public Mono<Void> runStage1(Project project, CloudFoundryOperations cfOperations,
                            CfProperties cfProperties) {
    
    final String greenNameString = cfProperties.name() + "-green";
    final Mono<String> greenRouteStringMono = CfRouteUtil.getTempRoute(cfOperations, cfProperties, "green");

    Mono<Optional<ApplicationDetail>> appDetailMono = appDetailsDelegate
        .getAppDetails(cfOperations, cfProperties);

    // Get App Env Vars
    Mono<Optional<ApplicationEnvironments>> appEnvMono =
        appEnvDelegate.getAppEnv(cfOperations, cfProperties);

    Mono<ImmutableCfProperties> cfPropertiesMono = Mono.zip(appEnvMono, appDetailMono, greenRouteStringMono).map(function((appEnvOpt, appDetailOpt, greenRouteString) -> {
        LOGGER.lifecycle(
            "Running Blue Green Deploy - deploying a 'green' app. App '{}' with route '{}'",
            cfProperties.name(),
            greenRouteString);

        return appDetailOpt.map(appDetail -> {
            printAppDetail(appDetail);
            return ImmutableCfProperties.copyOf(cfProperties)
                .withName(greenNameString)
                .withHost(null)
                .withDomain(null)
                .withRoutes(Collections.singletonList(greenRouteString))
                .withInstances(appDetail.getInstances())
                .withMemory(appDetail.getMemoryLimit())
                .withDiskQuota(appDetail.getDiskQuota());
        }).orElse(ImmutableCfProperties.copyOf(cfProperties)
            .withName(greenNameString)
            .withHost(null)
            .withDomain(null)
            .withRoutes(Collections.singletonList(greenRouteString)));
    }));

    return cfPropertiesMono.flatMap(
        withNewNameAndRoute -> pushDelegate.push(cfOperations, withNewNameAndRoute));
}
 
Example 9
Source File: OrderApiController.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@PostMapping(path="fromEmail", consumes="application/json")
@ResponseStatus(HttpStatus.CREATED)
public Mono<Order> postOrderFromEmail(@RequestBody Mono<EmailOrder> emailOrder) {
  Mono<Order> order = emailOrderService.convertEmailOrderToDomainOrder(emailOrder);
  order.subscribe(orderMessages::sendOrder); // TODO: not ideal...work into reactive flow below
  return order
      .flatMap(repo::save);
}
 
Example 10
Source File: DynamicRouteService.java    From momo-cloud-permission with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> delete(Mono<String> routeId) {
    return routeId.flatMap(id -> {
        if (redisTemplate.opsForHash().hasKey(GATEWAY_ROUTES, id)) {
            redisTemplate.opsForHash().delete(GATEWAY_ROUTES, id);
            return Mono.empty();
        }
        return Mono.defer(() -> Mono.error(new NotFoundException("RouteDefinition not found: " + routeId)));
    });
}
 
Example 11
Source File: SunriseSunsetServiceImpl.java    From reactive-ms-example with MIT License 5 votes vote down vote up
Mono<SunriseSunset> createResult(final Mono<GeoTimesResponse> geoTimesResponseMono) {
    return geoTimesResponseMono.flatMap(geoTimesResponse -> {
        if ((geoTimesResponse.getStatus() != null) && (geoTimesResponse.getStatus().equals(STATUS_OK))) {
            return Mono.just(new SunriseSunset(geoTimesResponse.getResults().getSunrise(),
                    geoTimesResponse.getResults().getSunset()));
        } else {
            return Mono.error(new GetSunriseSunsetException(SUNRISE_RESULT_NOT_OK));
        }
    });
}
 
Example 12
Source File: InMemoryRouteDefinitionRepository.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> save(Mono<RouteDefinition> route) {
	return route.flatMap(r -> {
		if (StringUtils.isEmpty(r.getId())) {
			return Mono.error(new IllegalArgumentException("id may not be empty"));
		}
		routes.put(r.getId(), r);
		return Mono.empty();
	});
}
 
Example 13
Source File: RedisRouteDefinitionRepository.java    From SpringCloud with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> delete(Mono<String> routeId) {
    return routeId.flatMap(id -> {
        routeService.delete(id);
        return Mono.empty();
    });
}
 
Example 14
Source File: SkipCmd.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Mono<Void> execute(Context context) {
    final GuildMusic guildMusic = context.requireGuildMusic();

    final Mono<Message> sendMessage = context.getChannel()
            .flatMap(channel -> DiscordUtils.sendMessage(String.format(Emoji.TRACK_NEXT + " Music skipped by **%s**.",
                    context.getUsername()), channel));

    if (context.getArg().isPresent()) {
        final int playlistSize = guildMusic.getTrackScheduler().getPlaylist().size();
        final Integer num = NumberUtils.toIntBetweenOrNull(context.getArg().orElseThrow(), 1, playlistSize);
        if (num == null) {
            return Mono.error(new CommandException(String.format("Number must be between 1 and %d.",
                    playlistSize)));
        }
        return sendMessage
                .doOnNext(ignored -> {
                    guildMusic.getTrackScheduler().skipTo(num);
                    // If the music has been started correctly, we resume it in case the previous music was paused
                    guildMusic.getTrackScheduler().getAudioPlayer().setPaused(false);
                })
                .then();
    } else {
        return sendMessage
                .flatMap(ignored -> {
                    // If the music has been started correctly
                    if (guildMusic.getTrackScheduler().nextTrack()) {
                        // we resume it in case the previous music was paused.
                        guildMusic.getTrackScheduler().getAudioPlayer().setPaused(false);
                        return Mono.empty();
                    }
                    // else
                    else {
                        // there is no more music, this is the end.
                        return guildMusic.end();
                    }
                });
    }
}
 
Example 15
Source File: CfAutoPilotDelegate.java    From ya-cf-app-gradle-plugin with Apache License 2.0 5 votes vote down vote up
public Mono<Void> runAutopilot(Project project, CloudFoundryOperations cfOperations,
                               CfProperties cfProperties) {
    LOGGER.lifecycle("Running Autopilot on App: {}", cfProperties.name());
    CfProperties withNameChanged = ImmutableCfProperties.copyOf(cfProperties)
        .withName(cfProperties.name() + "-venerable");

    Mono<Optional<ApplicationDetail>> appDetailMono = detailsDelegate
        .getAppDetails(cfOperations, cfProperties);

    Mono<Void> autopilotResult = appDetailMono.flatMap(appDetailOpt -> {
        if (appDetailOpt.isPresent()) {
            ApplicationDetail appDetail = appDetailOpt.get();
            CfProperties withExistingDetails = ImmutableCfProperties
                .copyOf(cfProperties).withInstances(appDetail.getInstances())
                .withMemory(appDetail.getMemoryLimit())
                .withDiskQuota(appDetail.getDiskQuota());
            Mono<Void> renameResult = renameAppDelegate
                .renameApp(cfOperations, cfProperties, withNameChanged);
            return renameResult
                .then(pushDelegate.push(cfOperations, withExistingDetails))
                .then(deleteDelegate.deleteApp(cfOperations, withNameChanged));
        } else {
            return pushDelegate.push(cfOperations, cfProperties);
        }
    });

    return autopilotResult;
}
 
Example 16
Source File: EmployeeRepository.java    From webflux-rxjava2-jdbc-example with Apache License 2.0 4 votes vote down vote up
Mono<Employee> createNewEmployee(Mono<Employee> employeeMono) {

    String createSql =
        "INSERT INTO employee (employee_firstname, employee_lastname, department_id) VALUES (?, ?, ?)";
    String selectDepartmentId = "SELECT department_id from department where department_name = ?";
    String selectSql =
        "SELECT employee_id, employee_firstname, employee_lastname, department_name FROM employee e "
            + "JOIN department d ON e.department_id = d.department_id "
            + "WHERE employee_id = ?";

    return employeeMono.flatMap(
        newEmployee -> {
          Flowable<Integer> employeeIds =
              db.select(selectDepartmentId)
                  .parameters(newEmployee.getDepartment())
                  .getAs(Integer.class)
                  .flatMap(
                      departmentId ->
                          db.update(createSql)
                              .parameters(
                                  newEmployee.getFirstName(),
                                  newEmployee.getLastName(),
                                  departmentId)
                              .returnGeneratedKeys()
                              .getAs(Integer.class));

          Flowable<Employee> employeeFlowable =
              db.select(selectSql)
                  .parameterStream(employeeIds)
                  .get(
                      rs -> {
                        Employee employee = new Employee();
                        employee.setId(rs.getInt("employee_id"));
                        employee.setFirstName(rs.getString("employee_firstname"));
                        employee.setLastName(rs.getString("employee_lastname"));
                        employee.setDepartment(rs.getString("department_name"));

                        return employee;
                      });

          return Mono.from(employeeFlowable);
        });
  }
 
Example 17
Source File: CrnkVertxHandler.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
public Publisher<HttpServerRequest> process(HttpServerRequest serverRequest) {
    VertxRequestContext vertxRequestContext = new VertxRequestContext(serverRequest, boot.getWebPathPrefix());
    Mono waitForBody = getBody(vertxRequestContext);
    Mono<HttpRequestContext> setupContext = waitForBody.flatMap(body -> createContext(vertxRequestContext));
    return setupContext.flatMap(context -> processRequest(context, serverRequest));
}
 
Example 18
Source File: ResponseEntityResultHandler.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {

	Mono<?> returnValueMono;
	MethodParameter bodyParameter;
	ReactiveAdapter adapter = getAdapter(result);
	MethodParameter actualParameter = result.getReturnTypeSource();

	if (adapter != null) {
		Assert.isTrue(!adapter.isMultiValue(), "Only a single ResponseEntity supported");
		returnValueMono = Mono.from(adapter.toPublisher(result.getReturnValue()));
		bodyParameter = actualParameter.nested().nested();
	}
	else {
		returnValueMono = Mono.justOrEmpty(result.getReturnValue());
		bodyParameter = actualParameter.nested();
	}

	return returnValueMono.flatMap(returnValue -> {
		HttpEntity<?> httpEntity;
		if (returnValue instanceof HttpEntity) {
			httpEntity = (HttpEntity<?>) returnValue;
		}
		else if (returnValue instanceof HttpHeaders) {
			httpEntity = new ResponseEntity<>((HttpHeaders) returnValue, HttpStatus.OK);
		}
		else {
			throw new IllegalArgumentException(
					"HttpEntity or HttpHeaders expected but got: " + returnValue.getClass());
		}

		if (httpEntity instanceof ResponseEntity) {
			ResponseEntity<?> responseEntity = (ResponseEntity<?>) httpEntity;
			ServerHttpResponse response = exchange.getResponse();
			if (response instanceof AbstractServerHttpResponse) {
				((AbstractServerHttpResponse) response).setStatusCodeValue(responseEntity.getStatusCodeValue());
			}
			else {
				response.setStatusCode(responseEntity.getStatusCode());
			}
		}

		HttpHeaders entityHeaders = httpEntity.getHeaders();
		HttpHeaders responseHeaders = exchange.getResponse().getHeaders();
		if (!entityHeaders.isEmpty()) {
			entityHeaders.entrySet().stream()
					.forEach(entry -> responseHeaders.put(entry.getKey(), entry.getValue()));
		}

		if (httpEntity.getBody() == null || returnValue instanceof HttpHeaders) {
			return exchange.getResponse().setComplete();
		}

		String etag = entityHeaders.getETag();
		Instant lastModified = Instant.ofEpochMilli(entityHeaders.getLastModified());
		HttpMethod httpMethod = exchange.getRequest().getMethod();
		if (SAFE_METHODS.contains(httpMethod) && exchange.checkNotModified(etag, lastModified)) {
			return exchange.getResponse().setComplete();
		}

		return writeBody(httpEntity.getBody(), bodyParameter, actualParameter, exchange);
	});
}
 
Example 19
Source File: HandlePublisher.java    From reactor-guice with Apache License 2.0 4 votes vote down vote up
private Mono<?> invokeMethod(HttpServerRequest request, HttpServerResponse response, Method method, Object handleObject, com.doopp.reactor.guice.RequestAttribute requestAttribute, ModelMap modelMap) {

        // value of url quest
        Map<String, List<String>> questParams = new HashMap<>();
        // values of form post
        Map<String, List<String>> formParams = new HashMap<>();
        // values of file upload
        Map<String, List<FileUpload>> fileParams = new HashMap<>();
        // get results
        this.queryParams(request, questParams);

        Mono<Object[]> objectMono;

        if (request.method() == HttpMethod.POST || request.method() == HttpMethod.PUT || request.method() == HttpMethod.DELETE) {
            objectMono = request.receive()
                .aggregate()
                .flatMap(byteBuf -> {
                    this.formParams(request, byteBuf, formParams, fileParams);
                    return methodParams(
                            method,
                            request,
                            response,
                            requestAttribute,
                            modelMap,
                            byteBuf,
                            questParams,
                            formParams,
                            fileParams
                    );
                });
        } else {
                // this.formParams(request, null, formParams, fileParams);
                objectMono = methodParams(
                        method,
                        request,
                        response,
                        requestAttribute,
                        modelMap,
                        null,
                        questParams,
                        formParams,
                        fileParams
                );
        }
        return objectMono.flatMap(oo -> {
            fileParams
                    .forEach((name, fileUploads)->fileUploads
                            .forEach(ReferenceCounted::release));
            try {
                Object result = method.invoke(handleObject, oo);
                return (result instanceof Mono<?>) ? (Mono<?>) result : Mono.just(result);
            } catch (Exception e) {
                return Mono.error(e);
            }
        });
    }
 
Example 20
Source File: CfRouteUtil.java    From ya-cf-app-gradle-plugin with Apache License 2.0 3 votes vote down vote up
/**
 * Get the first route and generate a temp route from it, adding the suffix
 * after the hostname.
 *
 * @param cfOperations the operations to check the domain names against
 * @param cfProperties the properties of the app
 * @param suffix       the suffix to add in the host
 * @return the calculated route
 */
public static Mono<String> getTempRoute(CloudFoundryOperations cfOperations, CfProperties cfProperties, String suffix) {
    if (cfProperties.routes() == null || cfProperties.routes().isEmpty())
        return getTempRoute(cfProperties.host(), cfProperties.domain(), null, cfProperties.path(), suffix);
    Mono<DecomposedRoute> routeMono = fetchDomainSummaries(cfOperations).flatMap(domainSummaries -> decomposeRoute(domainSummaries, cfProperties.routes().get(0), cfProperties.path()));
    return routeMono.flatMap(route -> getTempRoute(route.getHost(), route.getDomain(), route.getPort(), route.getPath(), suffix));
}