Java Code Examples for java.util.Optional#map()

The following examples show how to use java.util.Optional#map() . 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: PubSubConsumerModule.java    From heroic with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 2
Source File: ClusterService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 3
Source File: InfraDeployerImplTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 4
Source File: StructuralVariantLegPloidyFactory.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example 5
Source File: InMemoryTransactionManager.java    From presto with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 6
Source File: MetadataManager.java    From presto with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 7
Source File: AssetEncryptedAttributes.java    From InflatableDonkey with MIT License 5 votes vote down vote up
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);
}
 
Example 8
Source File: HiveModule.java    From flink with Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example 9
Source File: MapColumnWriter.java    From presto with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 10
Source File: OperationRetryService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
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.");
    }
}
 
Example 11
Source File: PathUtils.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
}
 
Example 12
Source File: GenericStyledArea.java    From RichTextFX with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@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;
    }
}
 
Example 13
Source File: AuthorizationList.java    From android-key-attestation with Apache License 2.0 4 votes vote down vote up
private static Optional<Instant> findOptionalInstantMillisAuthorizationListEntry(
    Map<Integer, ASN1Primitive> authorizationMap, int tag) {
  Optional<Long> millis = findOptionalLongAuthorizationListEntry(authorizationMap, tag);
  return millis.map(Instant::ofEpochMilli);
}
 
Example 14
Source File: ExtractSpatialJoins.java    From presto with Apache License 2.0 4 votes vote down vote up
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)));
}
 
Example 15
Source File: ConfigurationBuildTargets.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Performs conversion similar to {@link #convert(UnconfiguredBuildTarget)} for an optional value.
 */
public static Optional<BuildTarget> convert(Optional<UnconfiguredBuildTarget> buildTarget) {
  return buildTarget.map(ConfigurationBuildTargets::convert);
}
 
Example 16
Source File: GsonUtil.java    From messenger4j with MIT License 4 votes vote down vote up
public static Optional<JsonObject> getPropertyAsJsonObject(
    JsonObject jsonObject, Constants... propertyPath) {
  final Optional<JsonElement> jsonElement = getProperty(jsonObject, propertyPath);
  return jsonElement.map(JsonElement::getAsJsonObject);
}
 
Example 17
Source File: SwiftBuckConfig.java    From buck with Apache License 2.0 4 votes vote down vote up
private Optional<Iterable<String>> getFlags(String field) {
  Optional<String> value = delegate.getValue(SECTION_NAME, field);
  return value.map(input -> Splitter.on(" ").split(input.trim()));
}
 
Example 18
Source File: JsonResponseValidationSteps.java    From vividus with Apache License 2.0 4 votes vote down vote up
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)));
}
 
Example 19
Source File: RestAPIStabilityTest.java    From flink with Apache License 2.0 4 votes vote down vote up
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()));
}
 
Example 20
Source File: Request.java    From blade with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}