Example usage for com.google.common.base Optional transform

List of usage examples for com.google.common.base Optional transform

Introduction

In this page you can find the example usage for com.google.common.base Optional transform.

Prototype

public abstract <V> Optional<V> transform(Function<? super T, V> function);

Source Link

Document

If the instance is present, it is transformed with the given Function ; otherwise, Optional#absent is returned.

Usage

From source file:org.apache.james.mailbox.store.mail.model.impl.MessageParser.java

private Optional<String> name(Optional<ContentTypeField> contentTypeField) {
    return contentTypeField.transform(new Function<ContentTypeField, Optional<String>>() {
        @Override/*from  w w  w.  j  ava  2s . c o m*/
        public Optional<String> apply(ContentTypeField field) {
            return Optional.fromNullable(field.getParameter("name")).transform(new Function<String, String>() {
                public String apply(String input) {
                    DecodeMonitor monitor = null;
                    return DecoderUtil.decodeEncodedWords(input, monitor);
                }
            });
        }
    }).or(Optional.<String>absent());
}

From source file:org.apache.james.mailbox.store.mail.model.impl.MessageParser.java

private boolean isInline(Optional<ContentDispositionField> contentDispositionField) {
    return contentDispositionField.transform(new Function<ContentDispositionField, Boolean>() {
        @Override/*from w  w  w . ja  va2 s  . co m*/
        public Boolean apply(ContentDispositionField field) {
            return field.isInline();
        }
    }).or(false);
}

From source file:com.webbfontaine.valuewebb.irms.repo.DefaultAssignmentEventRepository.java

private Optional<TTAssignmentEvent> tryToRestoreAssignee(final TTAssignmentEvent event) {
    Optional<TTAssignmentEvent> lastAssignment = getLastAssignment(event.getTtId());

    return lastAssignment.transform(new Function<TTAssignmentEvent, TTAssignmentEvent>() {
        @Override/*from  w  w  w . j  av  a2s.  c  o m*/
        public TTAssignmentEvent apply(TTAssignmentEvent input) {
            String assignee = input.getAssignee();

            return assignmentEventCreator.copyOfWithNewAssignee(assignee, event);
        }
    });
}

From source file:com.qcadoo.mes.assignmentToShift.hooks.AssignmentToShiftHooks.java

void setNextDay(final Entity assignmentToShift) {
    Optional<LocalDate> maybeNewDate = resolveNextStartDate(assignmentToShift);
    assignmentToShift.setField("startDate", maybeNewDate.transform(TO_DATE).orNull());
}

From source file:com.google.errorprone.refaster.UPlaceholderStatement.java

@Override
public List<JCStatement> inlineStatements(final Inliner inliner) throws CouldNotResolveImportException {
    try {/* ww w .  j a v  a  2 s  . c  om*/
        Optional<List<JCStatement>> binding = inliner.getOptionalBinding(placeholder().blockKey());

        // If a placeholder was used as an expression binding in the @BeforeTemplate,
        // and as a bare statement or as a return in the @AfterTemplate, we may need to convert.
        Optional<JCExpression> exprBinding = inliner.getOptionalBinding(placeholder().exprKey());
        binding = binding.or(exprBinding.transform(new Function<JCExpression, List<JCStatement>>() {
            @Override
            public List<JCStatement> apply(JCExpression expr) {
                switch (implementationFlow()) {
                case NEVER_EXITS:
                    return List.of((JCStatement) inliner.maker().Exec(expr));
                case ALWAYS_RETURNS:
                    return List.of((JCStatement) inliner.maker().Return(expr));
                default:
                    throw new AssertionError();
                }
            }
        }));
        return UPlaceholderExpression.copier(arguments(), inliner).copy(binding.get(), inliner);
    } catch (UncheckedCouldNotResolveImportException e) {
        throw e.getCause();
    }
}

From source file:org.sonar.server.ce.ws.TaskFormatter.java

public WsCe.Task formatQueue(DbSession dbSession, CeQueueDto dto, Optional<ComponentDto> component) {
    checkArgument(Objects.equals(dto.getComponentUuid(), component.transform(ComponentDto::uuid).orNull()));
    return formatQueue(dto, ComponentDtoCache.forComponentDto(dbClient, dbSession, component));
}

From source file:springfox.documentation.swagger.readers.operation.SwaggerResponseMessageReader.java

protected Set<ResponseMessage> read(OperationContext context) {
    ResolvedType defaultResponse = context.getReturnType();
    Optional<ApiOperation> operationAnnotation = context.findAnnotation(ApiOperation.class);
    Optional<ResolvedType> operationResponse = operationAnnotation
            .transform(resolvedTypeFromOperation(typeResolver, defaultResponse));
    Optional<ResponseHeader[]> defaultResponseHeaders = operationAnnotation.transform(responseHeaders());
    Map<String, Header> defaultHeaders = newHashMap();
    if (defaultResponseHeaders.isPresent()) {
        defaultHeaders.putAll(headers(defaultResponseHeaders.get()));
    }// w ww  .j  ava 2  s .c  om

    List<ApiResponses> allApiResponses = context.findAllAnnotations(ApiResponses.class);
    Set<ResponseMessage> responseMessages = newHashSet();

    Map<Integer, ApiResponse> seenResponsesByCode = newHashMap();
    for (ApiResponses apiResponses : allApiResponses) {
        ApiResponse[] apiResponseAnnotations = apiResponses.value();
        for (ApiResponse apiResponse : apiResponseAnnotations) {
            if (!seenResponsesByCode.containsKey(apiResponse.code())) {
                seenResponsesByCode.put(apiResponse.code(), apiResponse);
                ModelContext modelContext = returnValue(apiResponse.response(), context.getDocumentationType(),
                        context.getAlternateTypeProvider(), context.getGenericsNamingStrategy(),
                        context.getIgnorableParameterTypes());
                Optional<ModelReference> responseModel = Optional.absent();
                Optional<ResolvedType> type = resolvedType(null, apiResponse);
                if (isSuccessful(apiResponse.code())) {
                    type = type.or(operationResponse);
                }
                if (type.isPresent()) {
                    responseModel = Optional.of(modelRefFactory(modelContext, typeNameExtractor)
                            .apply(context.alternateFor(type.get())));
                }
                Map<String, Header> headers = newHashMap(defaultHeaders);
                headers.putAll(headers(apiResponse.responseHeaders()));

                responseMessages.add(
                        new ResponseMessageBuilder().code(apiResponse.code()).message(apiResponse.message())
                                .responseModel(responseModel.orNull()).headersWithDescription(headers).build());
            }
        }
    }
    if (operationResponse.isPresent()) {
        ModelContext modelContext = returnValue(operationResponse.get(), context.getDocumentationType(),
                context.getAlternateTypeProvider(), context.getGenericsNamingStrategy(),
                context.getIgnorableParameterTypes());
        ResolvedType resolvedType = context.alternateFor(operationResponse.get());

        ModelReference responseModel = modelRefFactory(modelContext, typeNameExtractor).apply(resolvedType);
        context.operationBuilder().responseModel(responseModel);
        ResponseMessage defaultMessage = new ResponseMessageBuilder().code(httpStatusCode(context))
                .message(message(context)).responseModel(responseModel).build();
        if (!responseMessages.contains(defaultMessage) && !"void".equals(responseModel.getType())) {
            responseMessages.add(defaultMessage);
        }
    }
    return responseMessages;
}

From source file:org.opendaylight.netvirt.bgpmanager.FibDSWriter.java

public synchronized void removeOrUpdateFibEntryFromDS(String rd, String prefix, String nextHop) {

    if (rd == null || rd.isEmpty()) {
        LOG.error("Prefix {} not associated with vpn", prefix);
        return;/*from  w  w  w .  j  a v a2  s.  c o  m*/
    }
    LOG.debug("Removing fib entry with destination prefix {} from vrf table for rd {} and nextHop {}", prefix,
            rd, nextHop);
    try {
        InstanceIdentifier<VrfEntry> vrfEntryId = InstanceIdentifier.builder(FibEntries.class)
                .child(VrfTables.class, new VrfTablesKey(rd)).child(VrfEntry.class, new VrfEntryKey(prefix))
                .build();
        Optional<VrfEntry> existingVrfEntry = singleTxDB.syncReadOptional(LogicalDatastoreType.CONFIGURATION,
                vrfEntryId);
        List<RoutePaths> routePaths = existingVrfEntry.transform(VrfEntry::getRoutePaths)
                .or(Collections.EMPTY_LIST);
        if (routePaths.size() == 1) {
            if (routePaths.get(0).getNexthopAddress().equals(nextHop)) {
                BgpUtil.delete(dataBroker, LogicalDatastoreType.CONFIGURATION, vrfEntryId);
            }
        } else {
            routePaths.stream().map(routePath -> routePath.getNexthopAddress())
                    .filter(nextHopAddress -> nextHopAddress.equals(nextHop)).findFirst().ifPresent(nh -> {
                        InstanceIdentifier<RoutePaths> routePathId = FibHelper.buildRoutePathId(rd, prefix,
                                nextHop);
                        BgpUtil.delete(dataBroker, LogicalDatastoreType.CONFIGURATION, routePathId);
                    });
        }
    } catch (ReadFailedException e) {
        LOG.error("Error while reading vrfEntry for rd {}, prefix {}", rd, prefix);
        return;
    }
}

From source file:springfox.documentation.swagger.readers.parameter.ApiParamParameterBuilder.java

@Override
public void apply(ParameterContext context) {
    Optional<ApiParam> apiParam = context.resolvedMethodParameter().findAnnotation(ApiParam.class);
    context.parameterBuilder()/*  w ww. j ava 2 s.  co m*/
            .allowableValues(allowableValues(context.resolvedMethodParameter().getParameterType(),
                    apiParam.transform(toAllowableValue()).or("")));
    if (apiParam.isPresent()) {
        context.parameterBuilder().name(emptyToNull(apiParam.get().name()));
        context.parameterBuilder().description(emptyToNull(apiParam.get().value()));
        context.parameterBuilder().parameterAccess(emptyToNull(apiParam.get().access()));
        context.parameterBuilder().defaultValue(emptyToNull(apiParam.get().defaultValue()));
        context.parameterBuilder().allowMultiple(apiParam.get().allowMultiple());
        context.parameterBuilder().required(apiParam.get().required());
    }
}

From source file:org.opendaylight.netconf.topology.pipeline.tx.ProxyReadOnlyTransaction.java

@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    final Future<Optional<NormalizedNodeMessage>> future = delegate.read(store, path);
    final SettableFuture<Optional<NormalizedNode<?, ?>>> settableFuture = SettableFuture.create();
    final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> checkedFuture = Futures
            .makeChecked(settableFuture, new Function<Exception, ReadFailedException>() {
                @Nullable//from  w  w w  .j  a v  a  2  s .c  o  m
                @Override
                public ReadFailedException apply(Exception cause) {
                    return new ReadFailedException("Read from transaction failed", cause);
                }
            });
    future.onComplete(new OnComplete<Optional<NormalizedNodeMessage>>() {
        @Override
        public void onComplete(Throwable throwable, Optional<NormalizedNodeMessage> normalizedNodeMessage)
                throws Throwable {
            if (throwable == null) {
                if (normalizedNodeMessage.isPresent()) {
                    settableFuture.set(normalizedNodeMessage
                            .transform(new Function<NormalizedNodeMessage, NormalizedNode<?, ?>>() {
                                @Nullable
                                @Override
                                public NormalizedNode<?, ?> apply(NormalizedNodeMessage input) {
                                    return input.getNode();
                                }
                            }));
                } else {
                    settableFuture.set(Optional.absent());
                }
            } else {
                settableFuture.setException(throwable);
            }
        }
    }, actorSystem.dispatcher());
    return checkedFuture;
}