public void rollback() { Optional.ofNullable(rollbackAction.getAndSet(null)).ifPresent(Runnable::run); }
private void validateSelectors(List<ResourceGroupSpec> groups, SelectorSpec spec) { spec.getQueryType().ifPresent(this::validateQueryType); List<ResourceGroupNameTemplate> selectorGroups = spec.getGroup().getSegments(); StringBuilder fullyQualifiedGroupName = new StringBuilder(); while (!selectorGroups.isEmpty()) { ResourceGroupNameTemplate groupName = selectorGroups.get(0); fullyQualifiedGroupName.append(groupName); Optional<ResourceGroupSpec> match = groups .stream() .filter(groupSpec -> groupSpec.getName().equals(groupName)) .findFirst(); if (!match.isPresent()) { throw new IllegalArgumentException(format("Selector refers to nonexistent group: %s", fullyQualifiedGroupName.toString())); } fullyQualifiedGroupName.append("."); groups = match.get().getSubGroups(); selectorGroups = selectorGroups.subList(1, selectorGroups.size()); } }
@Override public synchronized void notify(List<URL> urls) { List<URL> categoryUrls = urls.stream() .filter(this::isValidCategory) .filter(this::isNotCompatibleFor26x) .collect(Collectors.toList()); /** * TODO Try to refactor the processing of these three type of urls using Collectors.groupBy()? */ this.configurators = Configurator.toConfigurators(classifyUrls(categoryUrls, UrlUtils::isConfigurator)) .orElse(configurators); toRouters(classifyUrls(categoryUrls, UrlUtils::isRoute)).ifPresent(this::addRouters); // providers refreshOverrideAndInvoker(classifyUrls(categoryUrls, UrlUtils::isProvider)); }
/** * Returns initial {@link Method} as well as all matching ones found in interfaces. * This allows to introspect metadata for a method which is both declared in parent class and in implemented * interface(s). <code>interfaces</code> typically is obtained by {@link ClassUtils#getAllInterfacesAsSet} */ Collection<Method> getMethodAndInterfaceDeclarations(Method method, Collection<Class> interfaces) { final List<Method> methods = new ArrayList<>(); methods.add(method); // we search for matching method by iteration and comparison vs getMethod to avoid repeated NoSuchMethodException // being thrown, while interface typically only define a few set of methods to check. interfaces.stream() .map(Class::getMethods) .flatMap(Arrays::stream) .filter(m -> m.getName().equals(method.getName()) && Arrays.equals(m.getParameterTypes(), method.getParameterTypes())) .findFirst() .ifPresent(methods::add); return methods; }
public String getBearerToken(String subject) { checkState(jwtSigner.isPresent(), "not configured"); JwtBuilder jwt = Jwts.builder() .setSubject(subject) .setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant())); jwtSigner.get().accept(jwt); jwtKeyId.ifPresent(keyId -> jwt.setHeaderParam(KEY_ID, keyId)); jwtIssuer.ifPresent(jwt::setIssuer); jwtAudience.ifPresent(jwt::setAudience); return jwt.compact(); }
private static void addPullRequest(ProjectPullRequests.ListWsResponse.Builder response, BranchDto branch, Map<String, BranchDto> mergeBranchesByUuid, @Nullable LiveMeasureDto qualityGateMeasure, BranchStatistics branchStatistics, @Nullable String analysisDate) { Optional<BranchDto> mergeBranch = Optional.ofNullable(mergeBranchesByUuid.get(branch.getMergeBranchUuid())); ProjectPullRequests.PullRequest.Builder builder = ProjectPullRequests.PullRequest.newBuilder(); builder.setKey(branch.getKey()); DbProjectBranches.PullRequestData pullRequestData = requireNonNull(branch.getPullRequestData(), "Pull request data should be available for branch type PULL_REQUEST"); builder.setBranch(pullRequestData.getBranch()); ofNullable(emptyToNull(pullRequestData.getUrl())).ifPresent(builder::setUrl); ofNullable(emptyToNull(pullRequestData.getTitle())).ifPresent(builder::setTitle); if (mergeBranch.isPresent()) { String mergeBranchKey = mergeBranch.get().getKey(); builder.setBase(mergeBranchKey); } else { builder.setIsOrphan(true); } ofNullable(analysisDate).ifPresent(builder::setAnalysisDate); setQualityGate(builder, qualityGateMeasure, branchStatistics); response.addPullRequests(builder); }
private static void addAllStages(Optional<StageInfo> stageInfo, ImmutableList.Builder<StageInfo> collector) { stageInfo.ifPresent(stage -> { collector.add(stage); stage.getSubStages().stream() .forEach(subStage -> addAllStages(Optional.ofNullable(subStage), collector)); }); }
private void analyzeHaving(QuerySpecification node, Scope scope) { if (node.getHaving().isPresent()) { Expression predicate = node.getHaving().get(); ExpressionAnalysis expressionAnalysis = analyzeExpression(predicate, scope); expressionAnalysis.getWindowFunctions().stream() .findFirst() .ifPresent(function -> { throw new SemanticException(NESTED_WINDOW, function.getNode(), "HAVING clause cannot contain window functions"); }); analysis.recordSubqueries(node, expressionAnalysis); Type predicateType = expressionAnalysis.getType(predicate); if (!predicateType.equals(BOOLEAN) && !predicateType.equals(UNKNOWN)) { throw new SemanticException(TYPE_MISMATCH, predicate, "HAVING clause must evaluate to a boolean: actual type %s", predicateType); } analysis.setHaving(node, predicate); } }
private void flattenNode(PlanNode node, int limit) { PlanNode resolved = lookup.resolve(node); // (limit - 2) because you need to account for adding left and right side if (!(resolved instanceof JoinNode) || (sources.size() > (limit - 2))) { sources.add(node); return; } JoinNode joinNode = (JoinNode) resolved; if (joinNode.getType() != INNER || !isDeterministic(joinNode.getFilter().orElse(TRUE_LITERAL)) || joinNode.getDistributionType().isPresent()) { sources.add(node); return; } // we set the left limit to limit - 1 to account for the node on the right flattenNode(joinNode.getLeft(), limit - 1); flattenNode(joinNode.getRight(), limit); joinNode.getCriteria().stream() .map(EquiJoinClause::toExpression) .forEach(filters::add); joinNode.getFilter().ifPresent(filters::add); }
public static void checkTableName(String catalogName, Optional<String> schemaName, Optional<String> tableName) { checkCatalogName(catalogName); schemaName.ifPresent(name -> checkLowerCase(name, "schemaName")); tableName.ifPresent(name -> checkLowerCase(name, "tableName")); checkArgument(schemaName.isPresent() || !tableName.isPresent(), "tableName specified but schemaName is missing"); }
private static void writeIfNeeded(String fieldName, @Nullable Date value, Consumer<String> setter, Set<String> desiredFields) { if (desiredFields.contains(fieldName)) { ofNullable(value).map(DateUtils::formatDateTime).ifPresent(setter); } }
private Object[] resolvePathParams(Object[] pathParams) { Arrays.stream(pathParams).filter(param -> !(param instanceof String)) .findAny().ifPresent(param -> { throw new IllegalArgumentException("Only Strings allowed in path parameters."); }); return Arrays.stream(pathParams) .map(param -> UriUtils.encode((String) param, Charsets.UTF_8)).toArray(); }
/** * Checks whether all of the data buffers allocated by this factory have also been released. * If not, then an {@link AssertionError} is thrown. Typically used from a JUnit {@link After} * method. */ public void checkForLeaks() { this.created.stream() .filter(LeakAwareDataBuffer::isAllocated) .findFirst() .map(LeakAwareDataBuffer::leakError) .ifPresent(leakError -> { throw leakError; }); }
private List<Setting> loadSettings(DbSession dbSession, Optional<ComponentDto> component, Set<String> keys) { // List of settings must be kept in the following orders : default -> global -> component -> branch List<Setting> settings = new ArrayList<>(); settings.addAll(loadDefaultValues(keys)); settings.addAll(loadGlobalSettings(dbSession, keys)); if (component.isPresent() && component.get().getBranch() != null && component.get().getMainBranchProjectUuid() != null) { ComponentDto project = dbClient.componentDao().selectOrFailByUuid(dbSession, component.get().getMainBranchProjectUuid()); settings.addAll(loadComponentSettings(dbSession, keys, project).values()); } component.ifPresent(componentDto -> settings.addAll(loadComponentSettings(dbSession, keys, componentDto).values())); return settings.stream() .filter(s -> settingsWsSupport.isVisible(s.getKey(), s.getDefinition(), component)) .collect(Collectors.toList()); }
@Override public synchronized void notify(List<URL> urls) { List<URL> categoryUrls = urls.stream() .filter(this::isValidCategory) .filter(this::isNotCompatibleFor26x) .collect(Collectors.toList()); /** * TODO Try to refactor the processing of these three type of urls using Collectors.groupBy()? */ this.configurators = Configurator.toConfigurators(classifyUrls(categoryUrls, UrlUtils::isConfigurator)) .orElse(configurators); toRouters(classifyUrls(categoryUrls, UrlUtils::isRoute)).ifPresent(this::addRouters); // providers refreshOverrideAndInvoker(classifyUrls(categoryUrls, UrlUtils::isProvider)); }
/** * Validates that the given prefix is not included in these properties. */ public void validatePrefixExclusion(String prefix) { properties.keySet().stream() .filter(k -> k.startsWith(prefix)) .findFirst() .ifPresent((k) -> { throw new ValidationException( "Properties with prefix '" + prefix + "' are not allowed in this context. " + "But property '" + k + "' was found."); }); }