Java Code Examples for java.util.Objects#requireNonNullElseGet()

The following examples show how to use java.util.Objects#requireNonNullElseGet() . 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: BalanceFileParser.java    From hedera-mirror-node with Apache License 2.0 6 votes vote down vote up
/**
 * List the verified balance files and parse them. We can process them in any order, but we choose to process the
 * latest balance first since most clients will want to query for the latest data.
 */
@Override
public void parse() {
    Stopwatch stopwatch = Stopwatch.createStarted();

    try {
        File balanceFilePath = parserProperties.getValidPath().toFile();
        File[] balanceFiles = Objects.requireNonNullElseGet(balanceFilePath.listFiles(), () -> new File[] {});
        Arrays.sort(balanceFiles, Collections.reverseOrder());

        for (File balanceFile : balanceFiles) {
            if (ShutdownHelper.isStopping()) {
                throw new RuntimeException("Process is shutting down");
            }
            parseBalanceFile(balanceFile);
        }

        log.info("Completed processing {} balance files in {}", balanceFiles.length, stopwatch);
    } catch (Exception e) {
        log.error("Error processing balances files after {}", stopwatch, e);
    }
}
 
Example 2
Source File: Book.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
public void renderBook(Format format, Renderer renderer, String size) {

        Objects.requireNonNull(format, "Format cannot be null");
        Objects.requireNonNull(renderer, "Renderer cannot be null");
        String bookSize = Objects.requireNonNullElseGet(size, () -> "125 x 200");

        System.out.println("Rendering ...");
    }
 
Example 3
Source File: FakePendingRequest.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void async(@Nullable Consumer<T> onSuccess, @Nullable Consumer<RequestException> onError) {
    final Consumer<T> finalOnSuccess = Objects.requireNonNullElseGet(onSuccess, () -> (__) -> {});

    // this should work fine
    //noinspection ConstantConditions
    finalOnSuccess.accept(this.onSuccess(null));
}
 
Example 4
Source File: AbstractEnforcement.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private BiFunction<Contextual<WithDittoHeaders>, Throwable, Contextual<WithDittoHeaders>> handleEnforcementCompletion() {
    return (result, throwable) -> {
        context.getStartedTimer()
                .map(startedTimer -> startedTimer.tag("outcome", throwable != null ? "fail" : "success"))
                .ifPresent(StartedTimer::stop);
        return Objects.requireNonNullElseGet(result,
                () -> withMessageToReceiver(convertError(throwable), sender()));
    };
}
 
Example 5
Source File: EnvironmentDtoConverter.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Json getTags(EnvironmentCreationDto creationDto) {
    boolean internalTenant = entitlementService.internalTenant(creationDto.getCreator(), creationDto.getAccountId());
    Map<String, String> userDefinedTags = creationDto.getTags();
    Set<AccountTag> accountTags = accountTagService.get(creationDto.getAccountId());
    List<AccountTagResponse> accountTagResponses = accountTagToAccountTagResponsesConverter.convert(accountTags);
    defaultInternalAccountTagService.merge(accountTagResponses);
    Map<String, String> accountTagsMap = accountTagResponses
            .stream()
            .collect(Collectors.toMap(AccountTagResponse::getKey, AccountTagResponse::getValue));
    CDPTagGenerationRequest request = CDPTagGenerationRequest.Builder.builder()
            .withCreatorCrn(creationDto.getCreator())
            .withEnvironmentCrn(creationDto.getCrn())
            .withAccountId(creationDto.getAccountId())
            .withPlatform(creationDto.getCloudPlatform())
            .withResourceCrn(creationDto.getCrn())
            .withIsInternalTenant(internalTenant)
            .withUserName(getUserFromCrn(creationDto.getCreator()))
            .withAccountTags(accountTagsMap)
            .withUserDefinedTags(userDefinedTags)
            .build();

    try {
        Map<String, String> defaultTags = costTagging.prepareDefaultTags(request);
        return new Json(new EnvironmentTags(Objects.requireNonNullElseGet(userDefinedTags, HashMap::new), defaultTags));
    } catch (AccountTagValidationFailed aTVF) {
        throw new BadRequestException(aTVF.getMessage());
    } catch (Exception ignored) {
        throw new BadRequestException("Failed to convert dynamic tags.");
    }
}
 
Example 6
Source File: Car.java    From Java-Coding-Problems with MIT License 4 votes vote down vote up
public Car(String name, Color color) {

        this.name = Objects.requireNonNullElse(name, "No name");
        this.color = Objects.requireNonNullElseGet(color, () -> new Color(0, 0, 0));
    }
 
Example 7
Source File: ImmutableBlock.java    From Cleanstone with MIT License 4 votes vote down vote up
private static CachingImmutableBlockProvider getLoadingSource() {
    return Objects.requireNonNullElseGet(loadingSource, () -> (loadingSource = new CachingImmutableBlockProvider()));
}
 
Example 8
Source File: ObjectsRequireNonNullUpdate.java    From blog-tutorials with MIT License 4 votes vote down vote up
public static void transferMoney(String recipient, BigDecimal amount) {
	amount = Objects.requireNonNullElseGet(amount, ObjectsRequireNonNullUpdate::calculateDefaultAmount);
	recipient = Objects.requireNonNullElse(recipient, "Phil");

	System.out.println(amount + " is transfered to " + recipient);
}
 
Example 9
Source File: ZKApplicationPackage.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public File getFileReference(Path pathRelativeToAppDir) {
    String fileName = zkApplication.getData(ConfigCurator.USERAPP_ZK_SUBPATH + "/" + pathRelativeToAppDir.getRelative());
    // File does not exist: Manufacture a non-existing file
    return new File(Objects.requireNonNullElseGet(fileName, pathRelativeToAppDir::getRelative));
}
 
Example 10
Source File: JamesServerWebApplicationContext.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 */
@Override
public String getConfDirectory() {
    return Objects.requireNonNullElseGet(confDirectory, () -> getRootDirectory() + "/WEB-INF/conf/");
}
 
Example 11
Source File: JamesServerWebApplicationContext.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 */
@Override
public String getVarDirectory() {
    return Objects.requireNonNullElseGet(varDirectory, () -> getRootDirectory() + "/var/");
}
 
Example 12
Source File: Java9ObjectsAPIUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenObject_whenRequireNonNullElseGet_thenObject(){
    List<String> aList = Objects.<List>requireNonNullElseGet(null, List::of);
    assertThat(aList, is(List.of()));
}
 
Example 13
Source File: JoinPhase.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<String> nodeIds() {
    return Objects.requireNonNullElseGet(executionNodes, Set::of);
}
 
Example 14
Source File: ContentManager.java    From uyuni with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Initialize a new instance specifying the libmodulemd API instance to use
 * @param modulemdApiIn the libmodulemd API to use when resolving modular dependencies
 */
public ContentManager(ModulemdApi modulemdApiIn) {
    this.modulemdApi = Objects.requireNonNullElseGet(modulemdApiIn, ModulemdApi::new);
}
 
Example 15
Source File: DependencyResolver.java    From uyuni with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Initialize a new instance with a content project and a {@link ModulemdApi} instance
 *
 * @param projectIn the content project
 * @param modulemdApiIn the libmodulemd API instance
 */
public DependencyResolver(ContentProject projectIn, ModulemdApi modulemdApiIn) {
    this.project = projectIn;
    this.modulemdApi = Objects.requireNonNullElseGet(modulemdApiIn, ModulemdApi::new);
}