Example usage for java.util Optional map

List of usage examples for java.util Optional map

Introduction

In this page you can find the example usage for java.util Optional map.

Prototype

public <U> Optional<U> map(Function<? super T, ? extends U> mapper) 

Source Link

Document

If a value is present, returns an Optional describing (as if by #ofNullable ) the result of applying the given mapping function to the value, otherwise returns an empty Optional .

Usage

From source file:org.apache.hadoop.hbase.tool.LoadIncrementalHFiles.java

/**
 * Attempt to assign the given load queue item into its target region group. If the hfile boundary
 * no longer fits into a region, physically splits the hfile such that the new bottom half will
 * fit and returns the list of LQI's corresponding to the resultant hfiles.
 * <p>/*from w w w  . java 2s.  c o m*/
 * protected for testing
 * @throws IOException if an IO failure is encountered
 */
@VisibleForTesting
protected Pair<List<LoadQueueItem>, String> groupOrSplit(Multimap<ByteBuffer, LoadQueueItem> regionGroups,
        final LoadQueueItem item, final Table table, final Pair<byte[][], byte[][]> startEndKeys)
        throws IOException {
    Path hfilePath = item.getFilePath();
    Optional<byte[]> first, last;
    try (HFile.Reader hfr = HFile.createReader(hfilePath.getFileSystem(getConf()), hfilePath,
            CacheConfig.DISABLED, true, getConf())) {
        hfr.loadFileInfo();
        first = hfr.getFirstRowKey();
        last = hfr.getLastRowKey();
    } catch (FileNotFoundException fnfe) {
        LOG.debug("encountered", fnfe);
        return new Pair<>(null, hfilePath.getName());
    }

    LOG.info("Trying to load hfile=" + hfilePath + " first=" + first.map(Bytes::toStringBinary) + " last="
            + last.map(Bytes::toStringBinary));
    if (!first.isPresent() || !last.isPresent()) {
        assert !first.isPresent() && !last.isPresent();
        // TODO what if this is due to a bad HFile?
        LOG.info("hfile " + hfilePath + " has no entries, skipping");
        return null;
    }
    if (Bytes.compareTo(first.get(), last.get()) > 0) {
        throw new IllegalArgumentException("Invalid range: " + Bytes.toStringBinary(first.get()) + " > "
                + Bytes.toStringBinary(last.get()));
    }
    int idx = Arrays.binarySearch(startEndKeys.getFirst(), first.get(), Bytes.BYTES_COMPARATOR);
    if (idx < 0) {
        // not on boundary, returns -(insertion index). Calculate region it
        // would be in.
        idx = -(idx + 1) - 1;
    }
    int indexForCallable = idx;

    /**
     * we can consider there is a region hole in following conditions. 1) if idx < 0,then first
     * region info is lost. 2) if the endkey of a region is not equal to the startkey of the next
     * region. 3) if the endkey of the last region is not empty.
     */
    if (indexForCallable < 0) {
        throw new IOException("The first region info for table " + table.getName()
                + " can't be found in hbase:meta.Please use hbck tool to fix it first.");
    } else if ((indexForCallable == startEndKeys.getFirst().length - 1)
            && !Bytes.equals(startEndKeys.getSecond()[indexForCallable], HConstants.EMPTY_BYTE_ARRAY)) {
        throw new IOException("The last region info for table " + table.getName()
                + " can't be found in hbase:meta.Please use hbck tool to fix it first.");
    } else if (indexForCallable + 1 < startEndKeys.getFirst().length
            && !(Bytes.compareTo(startEndKeys.getSecond()[indexForCallable],
                    startEndKeys.getFirst()[indexForCallable + 1]) == 0)) {
        throw new IOException("The endkey of one region for table " + table.getName()
                + " is not equal to the startkey of the next region in hbase:meta."
                + "Please use hbck tool to fix it first.");
    }

    boolean lastKeyInRange = Bytes.compareTo(last.get(), startEndKeys.getSecond()[idx]) < 0
            || Bytes.equals(startEndKeys.getSecond()[idx], HConstants.EMPTY_BYTE_ARRAY);
    if (!lastKeyInRange) {
        List<LoadQueueItem> lqis = splitStoreFile(item, table, startEndKeys.getFirst()[indexForCallable],
                startEndKeys.getSecond()[indexForCallable]);
        return new Pair<>(lqis, null);
    }

    // group regions.
    regionGroups.put(ByteBuffer.wrap(startEndKeys.getFirst()[idx]), item);
    return null;
}

From source file:org.apache.james.jmap.JMAPModule.java

private Optional<String> loadPublicKey(FileSystem fileSystem, Optional<String> jwtPublickeyPemUrl) {
    return jwtPublickeyPemUrl
            .map(Throwing.function(url -> FileUtils.readFileToString(fileSystem.getFile(url))));
}

From source file:org.apache.james.mailbox.backup.InternalDateExtraField.java

public InternalDateExtraField(Optional<Date> date) {
    super(date.map(Date::getTime));
}

From source file:org.apache.james.mailbox.tika.TikaTextExtractor.java

private ContentAndMetadata convert(Optional<InputStream> maybeInputStream)
        throws IOException, JsonParseException, JsonMappingException {
    return maybeInputStream
            .map(Throwing//from ww w  .ja v a  2 s . c  o m
                    .function(inputStream -> objectMapper.readValue(inputStream, ContentAndMetadata.class)))
            .orElse(ContentAndMetadata.empty());
}

From source file:org.apache.james.modules.objectstorage.SwiftKeystone3ConfigurationReader.java

private static Optional<Project> readProjectScope(Configuration configuration) {
    Optional<ProjectName> projectName = Optional
            .ofNullable(configuration.getString(OBJECTSTORAGE_SWIFT_KEYSTONE_3_PROJECT_NAME, null))
            .map(ProjectName::of);/*from  w w  w .  j  av a 2  s . co m*/

    Optional<DomainName> projectDomainName = Optional
            .ofNullable(configuration.getString(OBJECTSTORAGE_SWIFT_KEYSTONE_3_PROJECT_DOMAIN_NAME, null))
            .map(DomainName::of);

    Optional<DomainId> projectDomainId = Optional
            .ofNullable(configuration.getString(OBJECTSTORAGE_SWIFT_KEYSTONE_3_PROJECT_DOMAIN_ID, null))
            .map(DomainId::of);

    return OptionalUtils.or(
            projectName.flatMap(project -> projectDomainName.map(domain -> Project.of(project, domain))),
            projectName.flatMap(project -> projectDomainId.map(domain -> Project.of(project, domain))),
            projectName.map(Project::of));
}

From source file:org.apache.james.queue.rabbitmq.view.cassandra.configuration.CassandraMailQueueViewConfiguration.java

public static CassandraMailQueueViewConfiguration from(Configuration configuration) {
    int bucketCount = configuration.getInteger(BUCKET_COUNT_PROPERTY, DEFAULT_BUCKET_COUNT);
    int updateBrowseStartPace = configuration.getInteger(UPDATE_BROWSE_START_PACE_PROPERTY,
            DEFAULT_UPDATE_BROWSE_START_PACE);
    Optional<String> sliceWindowAsString = Optional
            .ofNullable(configuration.getString(SLICE_WINDOW_PROPERTY, null));

    return builder().bucketCount(bucketCount).updateBrowseStartPace(updateBrowseStartPace)
            .sliceWindow(sliceWindowAsString.map(TimeConverter::getMilliSeconds).map(Duration::ofMillis)
                    .orElse(DEFAULT_SLICE_WINDOW))
            .build();/*from  w  w w.  java  2s .c  o m*/
}

From source file:org.apache.james.transport.matchers.HasMimeTypeParameter.java

private List<Pair<String, String>> parseConfigurationString(Optional<String> maybeConfiguration) {
    return maybeConfiguration.map(tokenizeConfiguration()).orElse(ImmutableList.of());
}

From source file:org.apache.james.transport.matchers.HasMimeTypeParameter.java

@Override
public Collection<MailAddress> match(Mail mail) throws MessagingException {
    Optional<MimeType> maybeMimeType = getMimeTypeFromMessage(mail.getMessage());
    if (maybeMimeType.map(this::mimeTypeMatchParameter).orElse(false)) {
        return mail.getRecipients();
    }// w  ww  .java 2  s .  c  om
    return ImmutableList.of();
}

From source file:org.apache.james.util.mime.MessageContentExtractor.java

private Charset charset(Optional<String> charset) {
    return charset.map(Charset::forName).orElse(org.apache.james.mime4j.Charsets.DEFAULT_CHARSET);
}

From source file:org.apache.pulsar.broker.service.persistent.PersistentTopic.java

/**
 * Check whether the topic should be retained (based on time), even tough there are no producers/consumers and it's
 * marked as inactive.//from  ww  w . java 2s.  c  o  m
 */
private boolean shouldTopicBeRetained() {
    TopicName name = TopicName.get(topic);
    try {
        Optional<Policies> policies = brokerService.pulsar().getConfigurationCache().policiesCache()
                .get(AdminResource.path(POLICIES, name.getNamespace()));
        // If no policies, the default is to have no retention and delete the inactive topic
        return policies.map(p -> p.retention_policies).map(rp -> {
            long retentionTime = TimeUnit.MINUTES.toNanos(rp.getRetentionTimeInMinutes());

            // Negative retention time means the topic should be retained indefinitely,
            // because its own data has to be retained
            return retentionTime < 0 || (System.nanoTime() - lastActive) < retentionTime;
        }).orElse(false).booleanValue();
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Error getting policies", topic);
        }

        // Don't delete in case we cannot get the policies
        return true;
    }
}