java.util.Optional#map ( )源码实例Demo

下面列出了java.util.Optional#map ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: heroic   文件: PubSubConsumerModule.java
@JsonCreator
public Builder(
    @JsonProperty("id") Optional<String> id,
    @JsonProperty("threadsPerSubscription") Optional<Integer> threads,
    @JsonProperty("schema") Optional<String> schema,
    @JsonProperty("project") Optional<String> projectId,
    @JsonProperty("topic") Optional<String> topicId,
    @JsonProperty("subscription") Optional<String> subscriptionId,
    @JsonProperty("maxOutstandingElementCount") Optional<Long> maxOutstandingElementCount,
    @JsonProperty("maxOutstandingRequestBytes") Optional<Long> maxOutstandingRequestBytes,
    @JsonProperty("maxInboundMessageSize") Optional<Integer> maxInboundMessageSize,
    @JsonProperty("keepAlive") Optional<Long> keepAlive,
    @JsonProperty("endpoint") Optional<String> endpoint
) {
    this.id = id;
    this.threads = threads;
    this.schema = schema.map(s -> ReflectionUtils.buildInstance(s, ConsumerSchema.class));
    this.projectId = projectId;
    this.topicId = topicId;
    this.subscriptionId = subscriptionId;
    this.maxOutstandingElementCount = maxOutstandingElementCount;
    this.maxOutstandingRequestBytes = maxOutstandingRequestBytes;
    this.maxInboundMessageSize = maxInboundMessageSize;
    this.keepAlive = keepAlive;
    this.endpoint = endpoint;
}
 
源代码2 项目: vespa   文件: InfraDeployerImplTest.java
private Node addNode(int id, Node.State state, Optional<Version> wantedVespaVersion) {
    Node node = tester.addNode("id-" + id, "node-" + id, "default", nodeType);
    Optional<Node> nodeWithAllocation = wantedVespaVersion.map(version -> {
        ClusterSpec clusterSpec = application.getClusterSpecWithVersion(version).with(Optional.of(ClusterSpec.Group.from(0)));
        ClusterMembership membership = ClusterMembership.from(clusterSpec, 1);
        Allocation allocation = new Allocation(application.getApplicationId(), membership, node.resources(), Generation.initial(), false);
        return node.with(allocation);
    });
    return nodeRepository.database().writeTo(state, nodeWithAllocation.orElse(node), Agent.system, Optional.empty());
}
 
源代码3 项目: cloudbreak   文件: ClusterService.java
public Cluster updateClusterStatusByStackId(Long stackId, Status status, String statusReason) {
    LOGGER.debug("Updating cluster status. stackId: {}, status: {}, statusReason: {}", stackId, status, statusReason);
    StackStatus stackStatus = stackService.getCurrentStatusByStackId(stackId);
    Optional<Cluster> cluster = retrieveClusterByStackIdWithoutAuth(stackId);
    Optional<Status> clusterOldStatus = cluster.map(Cluster::getStatus);
    cluster = cluster.map(c -> {
        c.setStatus(status);
        c.setStatusReason(statusReason);
        return c;
    }).map(repository::save);
    handleInMemoryState(stackId, stackStatus, cluster, clusterOldStatus);
    return cluster.orElse(null);
}
 
源代码4 项目: presto   文件: InMemoryTransactionManager.java
private synchronized Optional<CatalogName> getConnectorId(String catalogName)
{
    Optional<Catalog> catalog = catalogByName.get(catalogName);
    if (catalog == null) {
        catalog = catalogManager.getCatalog(catalogName);
        catalogByName.put(catalogName, catalog);
        if (catalog.isPresent()) {
            registerCatalog(catalog.get());
        }
    }
    return catalog.map(Catalog::getConnectorCatalogName);
}
 
源代码5 项目: presto   文件: MetadataManager.java
@Override
public Optional<ResolvedIndex> resolveIndex(Session session, TableHandle tableHandle, Set<ColumnHandle> indexableColumns, Set<ColumnHandle> outputColumns, TupleDomain<ColumnHandle> tupleDomain)
{
    CatalogName catalogName = tableHandle.getCatalogName();
    CatalogMetadata catalogMetadata = getCatalogMetadata(session, catalogName);
    ConnectorMetadata metadata = catalogMetadata.getMetadataFor(catalogName);
    ConnectorTransactionHandle transaction = catalogMetadata.getTransactionHandleFor(catalogName);
    ConnectorSession connectorSession = session.toConnectorSession(catalogName);
    Optional<ConnectorResolvedIndex> resolvedIndex = metadata.resolveIndex(connectorSession, tableHandle.getConnectorHandle(), indexableColumns, outputColumns, tupleDomain);
    return resolvedIndex.map(resolved -> new ResolvedIndex(tableHandle.getCatalogName(), transaction, resolved));
}
 
public AssetEncryptedAttributes(
        Optional<String> domain,
        Optional<String> relativePath,
        Optional<Instant> modified,
        Optional<Instant> birth,
        Optional<Instant> statusChanged,
        Optional<Integer> userID,
        Optional<Integer> groupID,
        Optional<Integer> mode,
        Optional<Long> size,
        Optional<byte[]> encryptionKey,
        Optional<byte[]> checksum,
        Optional<Long> sizeBeforeCopy,
        Optional<Integer> contentEncodingMethod,
        Optional<Integer> contentCompressionMethod) {
    this.domain = Objects.requireNonNull(domain);
    this.relativePath = Objects.requireNonNull(relativePath);
    this.modified = Objects.requireNonNull(modified);
    this.birth = Objects.requireNonNull(birth);
    this.statusChanged = Objects.requireNonNull(statusChanged);
    this.userID = Objects.requireNonNull(userID);
    this.groupID = Objects.requireNonNull(groupID);
    this.mode = Objects.requireNonNull(mode);
    this.size = Objects.requireNonNull(size);
    this.encryptionKey = encryptionKey.map(bs -> Arrays.copyOf(bs, bs.length));
    this.checksum = checksum.map(bs -> Arrays.copyOf(bs, bs.length));
    this.sizeBeforeCopy = Objects.requireNonNull(sizeBeforeCopy);
    this.contentEncodingMethod = Objects.requireNonNull(contentEncodingMethod);
    this.contentCompressionMethod = Objects.requireNonNull(contentCompressionMethod);
}
 
源代码7 项目: cloudbreak   文件: OperationRetryService.java
public FlowIdentifier retry(Long stackId) {
    if (isFlowPending(stackId)) {
        LOGGER.info("Retry cannot be performed, because there is already an active flow. stackId: {}", stackId);
        throw new BadRequestException("Retry cannot be performed, because there is already an active flow.");
    }

    List<FlowLog> flowLogs = flowLogRepository.findAllByResourceIdOrderByCreatedDesc(stackId, PageRequest.of(0, LAST_FIFTY_FLOWLOGS));
    List<RetryableFlow> retryableFlows = getRetryableFlows(flowLogs);
    if (CollectionUtils.isEmpty(retryableFlows)) {
        LOGGER.info("Retry cannot be performed. The last flow did not fail or not retryable. stackId: {}", stackId);
        throw new BadRequestException("Retry cannot be performed. The last flow did not fail or not retryable.");
    }

    String name = retryableFlows.get(0).getName();
    eventService.fireCloudbreakEvent(stackId, Status.UPDATE_IN_PROGRESS.name(), STACK_RETRY_FLOW_START, List.of(name));

    Optional<FlowLog> failedFlowLog = getMostRecentFailedLog(flowLogs);
    Optional<FlowLog> lastSuccessfulStateFlowLog = failedFlowLog.map(log -> getLastSuccessfulStateLog(log.getCurrentState(), flowLogs));
    if (lastSuccessfulStateFlowLog.isPresent()) {
        flow2Handler.restartFlow(lastSuccessfulStateFlowLog.get());
        if (lastSuccessfulStateFlowLog.get().getFlowChainId() != null) {
            return new FlowIdentifier(FlowType.FLOW_CHAIN, lastSuccessfulStateFlowLog.get().getFlowChainId());
        } else {
            return new FlowIdentifier(FlowType.FLOW, lastSuccessfulStateFlowLog.get().getFlowId());
        }
    } else {
        LOGGER.info("Cannot restart previous flow because there is no successful state in the flow. stackId: {}", stackId);
        throw new BadRequestException("Cannot restart previous flow because there is no successful state in the flow.");
    }
}
 
源代码8 项目: presto   文件: MapColumnWriter.java
@Override
public List<StreamDataOutput> getIndexStreams(CompressedMetadataWriter metadataWriter)
        throws IOException
{
    checkState(closed);

    ImmutableList.Builder<RowGroupIndex> rowGroupIndexes = ImmutableList.builder();

    List<LongStreamCheckpoint> lengthCheckpoints = lengthStream.getCheckpoints();
    Optional<List<BooleanStreamCheckpoint>> presentCheckpoints = presentStream.getCheckpoints();
    for (int i = 0; i < rowGroupColumnStatistics.size(); i++) {
        int groupId = i;
        ColumnStatistics columnStatistics = rowGroupColumnStatistics.get(groupId);
        LongStreamCheckpoint lengthCheckpoint = lengthCheckpoints.get(groupId);
        Optional<BooleanStreamCheckpoint> presentCheckpoint = presentCheckpoints.map(checkpoints -> checkpoints.get(groupId));
        List<Integer> positions = createArrayColumnPositionList(compressed, lengthCheckpoint, presentCheckpoint);
        rowGroupIndexes.add(new RowGroupIndex(positions, columnStatistics));
    }

    Slice slice = metadataWriter.writeRowIndexes(rowGroupIndexes.build());
    Stream stream = new Stream(columnId, StreamKind.ROW_INDEX, slice.length(), false);

    ImmutableList.Builder<StreamDataOutput> indexStreams = ImmutableList.builder();
    indexStreams.add(new StreamDataOutput(slice, stream));
    indexStreams.addAll(keyWriter.getIndexStreams(metadataWriter));
    indexStreams.addAll(valueWriter.getIndexStreams(metadataWriter));
    return indexStreams.build();
}
 
源代码9 项目: flink   文件: HiveModule.java
@Override
public Optional<FunctionDefinition> getFunctionDefinition(String name) {
	if (BUILT_IN_FUNC_BLACKLIST.contains(name)) {
		return Optional.empty();
	}
	Optional<FunctionInfo> info = hiveShim.getBuiltInFunctionInfo(name);

	return info.map(functionInfo -> factory.createFunctionDefinitionFromHiveFunction(name, functionInfo.getFunctionClass().getName()));
}
 
@NotNull
public Optional<StructuralVariantLegPloidy> singleLegPloidy(@NotNull final StructuralVariantLeg leg, double leftCopyNumber,
        double rightCopyNumber) {
    Optional<ModifiableStructuralVariantLegPloidy> modifiable = create(leg, Optional.of(leftCopyNumber), Optional.of(rightCopyNumber));
    modifiable.ifPresent(x -> x.setAverageImpliedPloidy(x.unweightedImpliedPloidy()));
    return modifiable.map(x -> x);
}
 
源代码11 项目: flink   文件: RestAPIStabilityTest.java
private static <X> Optional<X> readJson(final CompatibilityRoutine<X> routine, final JsonNode call) {
	final Optional<JsonNode> jsonContainer = Optional.ofNullable(call.get(routine.getKey()));
	return jsonContainer.map(container -> jsonToObject(container, routine.getContainerClass()));
}
 
源代码12 项目: vividus   文件: JsonResponseValidationSteps.java
private Optional<List<?>> getElements(String json, String jsonPath)
{
    Optional<Optional<Object>> jsonObject = getDataByJsonPathSafely(json, jsonPath, false);
    return jsonObject.map(e -> e.map(value -> value instanceof List ? (List<?>) value : List.of(value))
            .orElseGet(() -> Collections.singletonList(null)));
}
 
源代码13 项目: buck   文件: SwiftBuckConfig.java
private Optional<Iterable<String>> getFlags(String field) {
  Optional<String> value = delegate.getValue(SECTION_NAME, field);
  return value.map(input -> Splitter.on(" ").split(input.trim()));
}
 
源代码14 项目: messenger4j   文件: GsonUtil.java
public static Optional<JsonObject> getPropertyAsJsonObject(
    JsonObject jsonObject, Constants... propertyPath) {
  final Optional<JsonElement> jsonElement = getProperty(jsonObject, propertyPath);
  return jsonElement.map(JsonElement::getAsJsonObject);
}
 
源代码15 项目: buck   文件: ConfigurationBuildTargets.java
/**
 * Performs conversion similar to {@link #convert(UnconfiguredBuildTarget)} for an optional value.
 */
public static Optional<BuildTarget> convert(Optional<UnconfiguredBuildTarget> buildTarget) {
  return buildTarget.map(ConfigurationBuildTargets::convert);
}
 
源代码16 项目: presto   文件: ExtractSpatialJoins.java
private static Result tryCreateSpatialJoin(
        Context context,
        JoinNode joinNode,
        Expression filter,
        PlanNodeId nodeId,
        List<Symbol> outputSymbols,
        FunctionCall spatialFunction,
        Optional<Expression> radius,
        Metadata metadata,
        SplitManager splitManager,
        PageSourceManager pageSourceManager,
        TypeAnalyzer typeAnalyzer)
{
    // TODO Add support for distributed left spatial joins
    Optional<String> spatialPartitioningTableName = joinNode.getType() == INNER ? getSpatialPartitioningTableName(context.getSession()) : Optional.empty();
    Optional<KdbTree> kdbTree = spatialPartitioningTableName.map(tableName -> loadKdbTree(tableName, context.getSession(), metadata, splitManager, pageSourceManager));

    List<Expression> arguments = spatialFunction.getArguments();
    verify(arguments.size() == 2);

    Expression firstArgument = arguments.get(0);
    Expression secondArgument = arguments.get(1);

    Type sphericalGeographyType = metadata.getType(SPHERICAL_GEOGRAPHY_TYPE_SIGNATURE);
    if (typeAnalyzer.getType(context.getSession(), context.getSymbolAllocator().getTypes(), firstArgument).equals(sphericalGeographyType)
            || typeAnalyzer.getType(context.getSession(), context.getSymbolAllocator().getTypes(), secondArgument).equals(sphericalGeographyType)) {
        return Result.empty();
    }

    Set<Symbol> firstSymbols = extractUnique(firstArgument);
    Set<Symbol> secondSymbols = extractUnique(secondArgument);

    if (firstSymbols.isEmpty() || secondSymbols.isEmpty()) {
        return Result.empty();
    }

    Optional<Symbol> newFirstSymbol = newGeometrySymbol(context, firstArgument, metadata);
    Optional<Symbol> newSecondSymbol = newGeometrySymbol(context, secondArgument, metadata);

    PlanNode leftNode = joinNode.getLeft();
    PlanNode rightNode = joinNode.getRight();

    PlanNode newLeftNode;
    PlanNode newRightNode;

    // Check if the order of arguments of the spatial function matches the order of join sides
    int alignment = checkAlignment(joinNode, firstSymbols, secondSymbols);
    if (alignment > 0) {
        newLeftNode = newFirstSymbol.map(symbol -> addProjection(context, leftNode, symbol, firstArgument)).orElse(leftNode);
        newRightNode = newSecondSymbol.map(symbol -> addProjection(context, rightNode, symbol, secondArgument)).orElse(rightNode);
    }
    else if (alignment < 0) {
        newLeftNode = newSecondSymbol.map(symbol -> addProjection(context, leftNode, symbol, secondArgument)).orElse(leftNode);
        newRightNode = newFirstSymbol.map(symbol -> addProjection(context, rightNode, symbol, firstArgument)).orElse(rightNode);
    }
    else {
        return Result.empty();
    }

    Expression newFirstArgument = toExpression(newFirstSymbol, firstArgument);
    Expression newSecondArgument = toExpression(newSecondSymbol, secondArgument);

    Optional<Symbol> leftPartitionSymbol = Optional.empty();
    Optional<Symbol> rightPartitionSymbol = Optional.empty();
    if (kdbTree.isPresent()) {
        leftPartitionSymbol = Optional.of(context.getSymbolAllocator().newSymbol("pid", INTEGER));
        rightPartitionSymbol = Optional.of(context.getSymbolAllocator().newSymbol("pid", INTEGER));

        if (alignment > 0) {
            newLeftNode = addPartitioningNodes(metadata, context, newLeftNode, leftPartitionSymbol.get(), kdbTree.get(), newFirstArgument, Optional.empty());
            newRightNode = addPartitioningNodes(metadata, context, newRightNode, rightPartitionSymbol.get(), kdbTree.get(), newSecondArgument, radius);
        }
        else {
            newLeftNode = addPartitioningNodes(metadata, context, newLeftNode, leftPartitionSymbol.get(), kdbTree.get(), newSecondArgument, Optional.empty());
            newRightNode = addPartitioningNodes(metadata, context, newRightNode, rightPartitionSymbol.get(), kdbTree.get(), newFirstArgument, radius);
        }
    }

    Expression newSpatialFunction = new FunctionCallBuilder(metadata)
            .setName(spatialFunction.getName())
            .addArgument(GEOMETRY_TYPE_SIGNATURE, newFirstArgument)
            .addArgument(GEOMETRY_TYPE_SIGNATURE, newSecondArgument)
            .build();
    Expression newFilter = replaceExpression(filter, ImmutableMap.of(spatialFunction, newSpatialFunction));

    return Result.ofPlanNode(new SpatialJoinNode(
            nodeId,
            SpatialJoinNode.Type.fromJoinNodeType(joinNode.getType()),
            newLeftNode,
            newRightNode,
            outputSymbols,
            newFilter,
            leftPartitionSymbol,
            rightPartitionSymbol,
            kdbTree.map(KdbTreeUtils::toJson)));
}
 
private static Optional<Instant> findOptionalInstantMillisAuthorizationListEntry(
    Map<Integer, ASN1Primitive> authorizationMap, int tag) {
  Optional<Long> millis = findOptionalLongAuthorizationListEntry(authorizationMap, tag);
  return millis.map(Instant::ofEpochMilli);
}
 
源代码18 项目: RichTextFX   文件: GenericStyledArea.java
@Override
public Optional<Bounds> getCharacterBoundsOnScreen(int from, int to) {
    if (from < 0) {
        throw new IllegalArgumentException("From is negative: " + from);
    }
    if (from > to) {
        throw new IllegalArgumentException(String.format("From is greater than to. from=%s to=%s", from, to));
    }
    if (to > getLength()) {
        throw new IllegalArgumentException(String.format("To is greater than area's length. length=%s, to=%s", getLength(), to));
    }

    // no bounds exist if range is just a newline character
    if (getText(from, to).equals("\n")) {
        return Optional.empty();
    }

    // if 'from' is the newline character at the end of a multi-line paragraph, it returns a Bounds that whose
    //  minX & minY are the minX and minY of the paragraph itself, not the newline character. So, ignore it.
    int realFrom = getText(from, from + 1).equals("\n") ? from + 1 : from;

    Position startPosition = offsetToPosition(realFrom, Bias.Forward);
    int startRow = startPosition.getMajor();
    Position endPosition = startPosition.offsetBy(to - realFrom, Bias.Forward);
    int endRow = endPosition.getMajor();
    if (startRow == endRow) {
        return getRangeBoundsOnScreen(startRow, startPosition.getMinor(), endPosition.getMinor());
    } else {
        Optional<Bounds> rangeBounds = getRangeBoundsOnScreen(startRow, startPosition.getMinor(),
                getParagraph(startRow).length());
        for (int i = startRow + 1; i <= endRow; i++) {
            Optional<Bounds> nextLineBounds = getRangeBoundsOnScreen(i, 0,
                    i == endRow
                            ? endPosition.getMinor()
                            : getParagraph(i).length()
            );
            if (nextLineBounds.isPresent()) {
                if (rangeBounds.isPresent()) {
                    Bounds lineBounds = nextLineBounds.get();
                    rangeBounds = rangeBounds.map(b -> {
                        double minX = Math.min(b.getMinX(),   lineBounds.getMinX());
                        double minY = Math.min(b.getMinY(),   lineBounds.getMinY());
                        double maxX = Math.max(b.getMaxX(),   lineBounds.getMaxX());
                        double maxY = Math.max(b.getMaxY(),   lineBounds.getMaxY());
                        return new BoundingBox(minX, minY, maxX - minX, maxY - minY);
                    });
                } else {
                    rangeBounds = nextLineBounds;
                }
            }
        }
        return rangeBounds;
    }
}
 
源代码19 项目: buck   文件: PathUtils.java
/**
 * Returns absolute path to the output rule, if the rule has an output. Cannot currently handle
 * multiple outputs since it returns either no path or one path only.
 *
 * @throws IllegalStateException if the given rule implements {@link HasMultipleOutputs} and
 *     returns more than one output from {@link
 *     HasMultipleOutputs#getSourcePathToOutput(OutputLabel)}
 */
static Optional<Path> getUserFacingOutputPath(
    SourcePathResolverAdapter pathResolver,
    BuildRule rule,
    boolean buckOutCompatLink,
    OutputLabel outputLabel,
    boolean showOutputLabels) {
  Optional<Path> outputPathOptional;
  if (rule instanceof HasMultipleOutputs) {
    if (!showOutputLabels && !outputLabel.isDefault()) {
      throw new HumanReadableException(
          "%s target %s[%s] should use --show-outputs",
          rule.getType(), rule.getFullyQualifiedName(), outputLabel);
    }
    ImmutableSortedSet<SourcePath> sourcePaths =
        ((HasMultipleOutputs) rule).getSourcePathToOutput(outputLabel);
    outputPathOptional =
        sourcePaths == null || sourcePaths.isEmpty()
            ? Optional.empty()
            : Optional.of(pathResolver.getRelativePath(Iterables.getOnlyElement(sourcePaths)));
  } else {
    Preconditions.checkState(
        outputLabel.isDefault(),
        "Multiple outputs not supported for %s target %s",
        rule.getType(),
        rule.getFullyQualifiedName());
    outputPathOptional =
        Optional.ofNullable(rule.getSourcePathToOutput()).map(pathResolver::getRelativePath);
  }
  // When using buck out compat mode, we favor using the default buck output path in the UI, so
  // amend the output paths when this is set.
  if (outputPathOptional.isPresent() && buckOutCompatLink) {
    BuckPaths paths = rule.getProjectFilesystem().getBuckPaths();
    if (outputPathOptional.get().startsWith(paths.getConfiguredBuckOut())) {
      outputPathOptional =
          Optional.of(
              paths
                  .getBuckOut()
                  .resolve(
                      outputPathOptional
                          .get()
                          .subpath(
                              paths.getConfiguredBuckOut().getNameCount(),
                              outputPathOptional.get().getNameCount())));
    }
  }

  return outputPathOptional.map(rule.getProjectFilesystem()::resolve);
}
 
源代码20 项目: blade   文件: Request.java
/**
 * Returns a request parameter for a Double type
 *
 * @param name Parameter name
 * @return Return Double parameter values
 */
default Optional<Double> queryDouble(@NonNull String name) {
    Optional<String> value = query(name);
    return value.map(Double::parseDouble);
}