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

The following examples show how to use java.util.Objects#requireNonNullElse() . 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: FileTokenizer.java    From Java-Coding-Problems with MIT License 6 votes vote down vote up
public static List<String> getV6(Path path, Charset cs, String delimiter) throws IOException {

        if (path == null || delimiter == null) {
            throw new IllegalArgumentException("Path/delimiter cannot be null");
        }

        cs = Objects.requireNonNullElse(cs, StandardCharsets.UTF_8);

        List<String> content = new ArrayList<>();
        try (BufferedReader br = Files.newBufferedReader(path, cs)) {
            String line;
            while ((line = br.readLine()) != null) {
                content.addAll(Collections.list(new StringTokenizer(line, delimiter)).stream()
                        .map(t -> (String) t)
                        .collect(Collectors.toList()));

            }
        }

        return content;
    }
 
Example 2
Source File: Csvs.java    From Java-Coding-Problems with MIT License 6 votes vote down vote up
public static List<List<String>> readAsObject(
        Path path, Charset cs, String delimiter) throws IOException {

    if (path == null || delimiter == null) {
        throw new IllegalArgumentException("Path/delimiter cannot be null");
    }

    cs = Objects.requireNonNullElse(cs, StandardCharsets.UTF_8);

    List<List<String>> content = new ArrayList<>();
    try (BufferedReader br = Files.newBufferedReader(path, cs)) {
        String line;
        while ((line = br.readLine()) != null) {
            String[] values = line.split(Pattern.quote(delimiter));
            content.add(Arrays.asList(values));
        }
    }

    return content;
}
 
Example 3
Source File: FileReadingIterator.java    From crate with Apache License 2.0 6 votes vote down vote up
private Predicate<URI> generateUriPredicate(FileInput fileInput, @Nullable Predicate<URI> globPredicate) {
    Predicate<URI> moduloPredicate;
    boolean sharedStorage = Objects.requireNonNullElse(shared, fileInput.sharedStorageDefault());
    if (sharedStorage) {
        moduloPredicate = input -> {
            int hash = input.hashCode();
            if (hash == Integer.MIN_VALUE) {
                hash = 0; // Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
            }
            return Math.abs(hash) % numReaders == readerNumber;
        };
    } else {
        moduloPredicate = MATCH_ALL_PREDICATE;
    }

    if (globPredicate != null) {
        return moduloPredicate.and(globPredicate);
    }
    return moduloPredicate;
}
 
Example 4
Source File: FileTokenizer.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
public static List<String> getV3(Path path, Charset cs, String delimiter) throws IOException {

        if (path == null || delimiter == null) {
            throw new IllegalArgumentException("Path/delimiter cannot be null");
        }

        cs = Objects.requireNonNullElse(cs, StandardCharsets.UTF_8);

        try (Stream<String> lines = Files.lines(path, cs)) {
            return lines.map(l -> l.split(Pattern.quote(delimiter)))
                    .flatMap(Arrays::stream)
                    .collect(Collectors.toList());
        }
    }
 
Example 5
Source File: BookAvoid.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
public BookAvoid(String title, Optional<String> isbn) {
    this.title = Objects.requireNonNull(title, () -> "Title cannot be null");

    /*
    if (isbn == null) {
        this.isbn = Optional.empty();
    } else {
        this.isbn = isbn;
    }*/
    
    // or
    this.isbn = Objects.requireNonNullElse(isbn, Optional.empty());
}
 
Example 6
Source File: VulnerabilityNotificationMessageBuilder.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
private Collection<ComponentItem> createVulnerabilityItems(Long notificationId, ItemOperation operation, ComponentData componentData, @Nullable ComponentItemCallbackInfo callbackInfo, List<LinkableItem> componentAttributes,
    List<VulnerabilitySourceQualifiedId> vulnerabilityList, BlackDuckResponseCache blackDuckResponseCache, Collection<String> vulnerabilityFilters) {
    LinkedList<ComponentItem> items = new LinkedList<>();
    for (VulnerabilitySourceQualifiedId vulnerabilityItem : vulnerabilityList) {
        String vulnerabilityId = vulnerabilityItem.getVulnerabilityId();
        String vulnerabilityUrl = vulnerabilityItem.getVulnerability();
        LinkableItem vulnIdItem = new LinkableItem(MessageBuilderConstants.LABEL_VULNERABILITIES, vulnerabilityId, vulnerabilityUrl);

        String notificationSeverity = Objects.requireNonNullElse(vulnerabilityItem.getSeverity(), "UNKNOWN");
        if (vulnerabilityFilters.isEmpty() || vulnerabilityFilters.contains(notificationSeverity)) {
            LinkableItem severity = new LinkableItem(MessageBuilderConstants.LABEL_VULNERABILITY_SEVERITY, notificationSeverity);

            ComponentItemPriority priority = ComponentItemPriority.findPriority(severity.getValue());
            ComponentItem.Builder builder = new ComponentItem.Builder()
                                                .applyCategory(MessageBuilderConstants.CATEGORY_TYPE_VULNERABILITY)
                                                .applyOperation(operation)
                                                .applyPriority(priority)
                                                .applyCategoryItem(vulnIdItem)
                                                .applyCategoryGroupingAttribute(severity)
                                                .applyCollapseOnCategory(true)
                                                .applyComponentItemCallbackInfo(callbackInfo)
                                                .applyAllComponentAttributes(componentAttributes)
                                                .applyNotificationId(notificationId);
            ComponentBuilderUtil.applyComponentInformation(builder, blackDuckResponseCache, componentData);
            try {
                items.add(builder.build());
            } catch (AlertException ex) {
                logger.info("Error building vulnerability component for notification {}, operation {}, component {}, component version {}", notificationId, operation, componentData.getComponentName(),
                    componentData.getComponentVersionName());
                logger.debug("Error building vulnerability component cause ", ex);
            }
        }
    }
    return items;
}
 
Example 7
Source File: MatchLineRMA3.java    From megan-ce with GNU General Public License v3.0 4 votes vote down vote up
public void setCogId(Integer id) {
    this.cogId = Objects.requireNonNullElse(id, 0);
}
 
Example 8
Source File: GuiNoteTool.java    From VocabHunter with Apache License 2.0 4 votes vote down vote up
public static String toGuiNote(final String note) {
    return Objects.requireNonNullElse(note, "");
}
 
Example 9
Source File: ToolDependencies.java    From curiostack with MIT License 4 votes vote down vote up
private static String getVersion(String tool, Project project) {
  return Objects.requireNonNullElse(
      (String) project.getRootProject().findProperty("org.curioswitch.curiostack.tools." + tool),
      DEFAULT_VERSIONS.getOrDefault(tool, ""));
}
 
Example 10
Source File: ConfigDefinition.java    From vespa with Apache License 2.0 4 votes vote down vote up
DoubleDef(Double defVal, Double min, Double max) {
    super();
    this.defVal = defVal;
    this.min = Objects.requireNonNullElse(min, DOUBLE_MIN);
    this.max = Objects.requireNonNullElse(max, DOUBLE_MAX);
}
 
Example 11
Source File: Mqtt5MessageWithUserPropertiesEncoder.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
private @NotNull Long calculateMaxMessageSize(final @NotNull Channel channel) {
    Preconditions.checkNotNull(channel, "A Channel must never be null");
    final Long maxMessageSize = channel.attr(ChannelAttributes.MAX_PACKET_SIZE_SEND).get();
    return Objects.requireNonNullElse(maxMessageSize, (long) MAXIMUM_PACKET_SIZE_LIMIT);
}
 
Example 12
Source File: Mqtt5MessageWithUserPropertiesEncoder.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Override
public int bufferSize(@NotNull final ChannelHandlerContext ctx, final @NotNull T message) {

    int omittedProperties = 0;
    int propertyLength = calculatePropertyLength(message);

    if (!securityConfigurationService.allowRequestProblemInformation() || !Objects.requireNonNullElse(ctx.channel().attr(ChannelAttributes.REQUEST_PROBLEM_INFORMATION).get(), Mqtt5CONNECT.DEFAULT_PROBLEM_INFORMATION_REQUESTED)) {

        //Must omit user properties and reason string for any other packet than PUBLISH, CONNACK, DISCONNECT
        //if no problem information requested.
        final boolean mustOmit = !(message instanceof PUBLISH || message instanceof CONNACK || message instanceof DISCONNECT);

        if (mustOmit) {
            // propertyLength - reason string
            propertyLength = propertyLength(message, propertyLength, ++omittedProperties);
            // propertyLength - user properties
            propertyLength = propertyLength(message, propertyLength, ++omittedProperties);
        }
    }

    final long maximumPacketSize = calculateMaxMessageSize(ctx.channel());
    final int remainingLengthWithoutProperties = calculateRemainingLengthWithoutProperties(message);
    int remainingLength = remainingLength(message, remainingLengthWithoutProperties, propertyLength);
    int encodedLength = encodedPacketLength(remainingLength);
    while (encodedLength > maximumPacketSize) {

        omittedProperties++;
        propertyLength = propertyLength(message, propertyLength, omittedProperties);

        if (propertyLength == -1) {
            break;
        }

        remainingLength = remainingLength(message, remainingLengthWithoutProperties, propertyLength);
        encodedLength = encodedPacketLength(remainingLength);
    }

    message.setEncodedLength(encodedLength);
    message.setOmittedProperties(omittedProperties);
    message.setRemainingLength(remainingLength);
    message.setPropertyLength(propertyLength);

    return encodedLength;
}
 
Example 13
Source File: Stats.java    From Shadbot with GNU General Public License v3.0 4 votes vote down vote up
public SubStats getSeasonDuoStats() {
    return Objects.requireNonNullElse(this.seasonDuoStats, SubStats.DEFAULT);
}
 
Example 14
Source File: MeganFile.java    From megan-ce with GNU General Public License v3.0 4 votes vote down vote up
public String getFileName() {
    return Objects.requireNonNullElse(fileName, "Untitled");
}
 
Example 15
Source File: Dashboard.java    From mirrorgate with Apache License 2.0 4 votes vote down vote up
public Float getErrorsRateAlertingLevelWarning() {
    return Objects.requireNonNullElse(errorsRateAlertingLevelWarning, .3f);
}
 
Example 16
Source File: Java9ObjectsAPIUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenObject_whenRequireNonNullElse_thenObject(){
    List<String> aList = Objects.<List>requireNonNullElse(
            aMethodReturningNonNullList(), Collections.EMPTY_LIST);
    assertThat(aList, is(List.of("item1", "item2")));
}
 
Example 17
Source File: ConfigDefinition.java    From vespa with Apache License 2.0 4 votes vote down vote up
IntDef(Integer def, Integer min, Integer max) {
    super();
    this.defVal = def;
    this.min = Objects.requireNonNullElse(min, INT_MIN);
    this.max = Objects.requireNonNullElse(max, INT_MAX);
}
 
Example 18
Source File: ZoneId.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Obtains an instance of {@code ZoneId} using its ID using a map
 * of aliases to supplement the standard zone IDs.
 * <p>
 * Many users of time-zones use short abbreviations, such as PST for
 * 'Pacific Standard Time' and PDT for 'Pacific Daylight Time'.
 * These abbreviations are not unique, and so cannot be used as IDs.
 * This method allows a map of string to time-zone to be setup and reused
 * within an application.
 *
 * @param zoneId  the time-zone ID, not null
 * @param aliasMap  a map of alias zone IDs (typically abbreviations) to real zone IDs, not null
 * @return the zone ID, not null
 * @throws DateTimeException if the zone ID has an invalid format
 * @throws ZoneRulesException if the zone ID is a region ID that cannot be found
 */
public static ZoneId of(String zoneId, Map<String, String> aliasMap) {
    Objects.requireNonNull(zoneId, "zoneId");
    Objects.requireNonNull(aliasMap, "aliasMap");
    String id = Objects.requireNonNullElse(aliasMap.get(zoneId), zoneId);
    return of(id);
}
 
Example 19
Source File: Chronology.java    From Bytecoder with Apache License 2.0 2 votes vote down vote up
/**
 * Obtains an instance of {@code Chronology} from a temporal object.
 * <p>
 * This obtains a chronology based on the specified temporal.
 * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 * which this factory converts to an instance of {@code Chronology}.
 * <p>
 * The conversion will obtain the chronology using {@link TemporalQueries#chronology()}.
 * If the specified temporal object does not have a chronology, {@link IsoChronology} is returned.
 * <p>
 * This method matches the signature of the functional interface {@link TemporalQuery}
 * allowing it to be used as a query via method reference, {@code Chronology::from}.
 *
 * @param temporal  the temporal to convert, not null
 * @return the chronology, not null
 * @throws DateTimeException if unable to convert to a {@code Chronology}
 */
static Chronology from(TemporalAccessor temporal) {
    Objects.requireNonNull(temporal, "temporal");
    Chronology obj = temporal.query(TemporalQueries.chronology());
    return Objects.requireNonNullElse(obj, IsoChronology.INSTANCE);
}
 
Example 20
Source File: ShapeAndLabelManager.java    From megan-ce with GNU General Public License v3.0 2 votes vote down vote up
/**
 * get shape for sample
 *
 * @param sample
 * @return shape
 */
public NodeShape getShape(String sample) {
    NodeShape shape = sample2shape.get(sample);
    return Objects.requireNonNullElse(shape, NodeShape.Oval);
}