Search in sources :

Example 1 with ParametersProvider

use of jetbrains.buildServer.parameters.ParametersProvider in project teamcity-rest by JetBrains.

the class BuildPromotionFinder method getBuildFilter.

@NotNull
private MultiCheckerFilter<SBuild> getBuildFilter(@NotNull final Locator locator) {
    final MultiCheckerFilter<SBuild> result = new MultiCheckerFilter<SBuild>();
    final String buildNumber = locator.getSingleDimensionValue(NUMBER);
    if (buildNumber != null) {
        result.add(new FilterConditionChecker<SBuild>() {

            public boolean isIncluded(@NotNull final SBuild item) {
                return buildNumber.equals(item.getBuildNumber());
            }
        });
    }
    final String status = locator.getSingleDimensionValue(STATUS);
    if (status != null) {
        result.add(new FilterConditionChecker<SBuild>() {

            public boolean isIncluded(@NotNull final SBuild item) {
                return status.equalsIgnoreCase(item.getStatusDescriptor().getStatus().getText());
            }
        });
    }
    final Boolean pinned = locator.getSingleDimensionValueAsBoolean(PINNED);
    if (pinned != null) {
        result.add(new FilterConditionChecker<SBuild>() {

            public boolean isIncluded(@NotNull final SBuild item) {
                return FilterUtil.isIncludedByBooleanFilter(pinned, item.isPinned());
            }
        });
    }
    final Boolean hanging = locator.getSingleDimensionValueAsBoolean(HANGING);
    if (hanging != null) {
        result.add(new FilterConditionChecker<SBuild>() {

            public boolean isIncluded(@NotNull final SBuild item) {
                if (item.isFinished())
                    return !hanging;
                return FilterUtil.isIncludedByBooleanFilter(hanging, ((SRunningBuild) item).isProbablyHanging());
            }
        });
    }
    if (locator.isUnused(AGENT_NAME)) {
        final String agentName = locator.getSingleDimensionValue(AGENT_NAME);
        if (agentName != null) {
            final ValueCondition agentNameCondition = ParameterCondition.createValueCondition(agentName);
            result.add(item -> agentNameCondition.matches(item.getAgentName()));
        }
    }
    if (locator.isUnused(AGENT_TYPE_ID)) {
        final Long agentTypeId = locator.getSingleDimensionValueAsLong(AGENT_TYPE_ID);
        if (agentTypeId != null) {
            result.add(item -> agentTypeId.intValue() == item.getAgent().getAgentTypeId());
        }
    }
    // see also settings cut off date in main filter
    final Date sinceDate = DataProvider.parseDate(locator.getSingleDimensionValue(SINCE_DATE));
    if (sinceDate != null) {
        result.add(new FilterConditionChecker<SBuild>() {

            public boolean isIncluded(@NotNull final SBuild item) {
                return sinceDate.before(item.getStartDate());
            }
        });
    }
    final Date untilDate = DataProvider.parseDate(locator.getSingleDimensionValue(UNTIL_DATE));
    if (untilDate != null) {
        result.add(new FilterConditionChecker<SBuild>() {

            public boolean isIncluded(@NotNull final SBuild item) {
                return !(untilDate.before(item.getStartDate()));
            }
        });
    }
    final List<String> statisticValues = locator.getDimensionValue(STATISTIC_VALUE);
    if (!statisticValues.isEmpty()) {
        final Matcher<ParametersProvider> parameterCondition = ParameterCondition.create(statisticValues);
        result.add(new FilterConditionChecker<SBuild>() {

            public boolean isIncluded(@NotNull final SBuild item) {
                return parameterCondition.matches(new AbstractMapParametersProvider(Build.getBuildStatisticsValues(item)));
            }
        });
    }
    if (locator.isUnused(TEST_OCCURRENCE)) {
        final String testOccurrence = locator.getSingleDimensionValue(TEST_OCCURRENCE);
        if (testOccurrence != null) {
            TestOccurrenceFinder testOccurrenceFinder = myServiceLocator.getSingletonService(TestOccurrenceFinder.class);
            Set<Long> buildPromotionIds = testOccurrenceFinder.getItems(testOccurrence).myEntries.stream().map(sTestRun -> sTestRun.getBuild().getBuildPromotion().getId()).collect(Collectors.toSet());
            result.add(new FilterConditionChecker<SBuild>() {

                public boolean isIncluded(@NotNull final SBuild item) {
                    return buildPromotionIds.contains(item.getBuildPromotion().getId());
                }
            });
        }
    }
    final String test = locator.getSingleDimensionValue(TEST);
    if (test != null) {
        TestFinder testFinder = myServiceLocator.getSingletonService(TestFinder.class);
        result.add(new FilterConditionChecker<SBuild>() {

            public boolean isIncluded(@NotNull final SBuild item) {
                String locator = new Locator(test).setDimension(TestFinder.BUILD, getLocator(item.getBuildPromotion())).setDimension(PagerData.COUNT, "1").getStringRepresentation();
                return !testFinder.getItems(locator).myEntries.isEmpty();
            }
        });
    }
    return result;
}
Also used : LocatorProcessException(jetbrains.buildServer.server.rest.errors.LocatorProcessException) MetadataStorageEx(jetbrains.buildServer.serverSide.metadata.impl.MetadataStorageEx) Filter(jetbrains.buildServer.util.filters.Filter) java.util(java.util) LocatorName(jetbrains.buildServer.server.rest.swagger.constants.LocatorName) LocatorResource(jetbrains.buildServer.server.rest.swagger.annotations.LocatorResource) Agent(jetbrains.buildServer.server.rest.model.agent.Agent) BuildDependency(jetbrains.buildServer.serverSide.dependency.BuildDependency) Converter(jetbrains.buildServer.util.Converter) ParametersProvider(jetbrains.buildServer.parameters.ParametersProvider) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) LocatorDimensionDataType(jetbrains.buildServer.server.rest.swagger.constants.LocatorDimensionDataType) AbstractMapParametersProvider(jetbrains.buildServer.parameters.impl.AbstractMapParametersProvider) TestOccurrenceFinder(jetbrains.buildServer.server.rest.data.problem.TestOccurrenceFinder) AccessDeniedException(jetbrains.buildServer.serverSide.auth.AccessDeniedException) ErrorData(jetbrains.buildServer.messages.ErrorData) StringUtil(jetbrains.buildServer.util.StringUtil) Build(jetbrains.buildServer.server.rest.model.build.Build) Logger(com.intellij.openapi.diagnostic.Logger) CollectionsUtil(jetbrains.buildServer.util.CollectionsUtil) jetbrains.buildServer.server.rest.data.util(jetbrains.buildServer.server.rest.data.util) PagerData(jetbrains.buildServer.server.rest.model.PagerData) SVcsRoot(jetbrains.buildServer.vcs.SVcsRoot) PatternSyntaxException(java.util.regex.PatternSyntaxException) Constants(jetbrains.buildServer.server.rest.request.Constants) ServiceLocator(jetbrains.buildServer.ServiceLocator) jetbrains.buildServer.serverSide(jetbrains.buildServer.serverSide) ItemsProviders(jetbrains.buildServer.server.rest.model.ItemsProviders) TagFinder(jetbrains.buildServer.server.rest.data.build.TagFinder) ItemProcessor(jetbrains.buildServer.util.ItemProcessor) StreamUtil(jetbrains.buildServer.server.rest.util.StreamUtil) Collectors(java.util.stream.Collectors) Nullable(org.jetbrains.annotations.Nullable) CommonLocatorDimensionsList(jetbrains.buildServer.server.rest.swagger.constants.CommonLocatorDimensionsList) Stream(java.util.stream.Stream) LocatorDimension(jetbrains.buildServer.server.rest.swagger.annotations.LocatorDimension) Util(jetbrains.buildServer.server.rest.model.Util) Permission(jetbrains.buildServer.serverSide.auth.Permission) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) TestFinder(jetbrains.buildServer.server.rest.data.problem.TestFinder) BuildMetadataEntry(jetbrains.buildServer.serverSide.metadata.BuildMetadataEntry) Pattern(java.util.regex.Pattern) NotNull(org.jetbrains.annotations.NotNull) SUser(jetbrains.buildServer.users.SUser) TestOccurrenceFinder(jetbrains.buildServer.server.rest.data.problem.TestOccurrenceFinder) ParametersProvider(jetbrains.buildServer.parameters.ParametersProvider) AbstractMapParametersProvider(jetbrains.buildServer.parameters.impl.AbstractMapParametersProvider) AbstractMapParametersProvider(jetbrains.buildServer.parameters.impl.AbstractMapParametersProvider) ServiceLocator(jetbrains.buildServer.ServiceLocator) TestFinder(jetbrains.buildServer.server.rest.data.problem.TestFinder) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with ParametersProvider

use of jetbrains.buildServer.parameters.ParametersProvider in project teamcity-rest by JetBrains.

the class Build method calculateAllParameters.

private static ParametersProvider calculateAllParameters(@NotNull final BuildPromotion buildPromotion, @NotNull PasswordsSearcher searcher) {
    Set<String> passwords = searcher.collectPasswords(buildPromotion);
    ParametersProvider provider = ((BuildPromotionEx) buildPromotion).getParametersProvider();
    if (passwords.isEmpty()) {
        return provider;
    }
    PasswordReplacer passwordReplacer = PasswordParametersFilterCore.createPasswordReplacer(passwords);
    return new ParametersProvider() {

        @Nullable
        @Override
        public String get(@NotNull final String key) {
            return Util.resolveNull(provider.get(key), passwordReplacer::replacePasswords);
        }

        @Override
        public int size() {
            return provider.size();
        }

        @Override
        public Map<String, String> getAll() {
            return provider.getAll().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> passwordReplacer.replacePasswords(e.getValue())));
        }
    };
}
Also used : MetadataStorageEx(jetbrains.buildServer.serverSide.metadata.impl.MetadataStorageEx) BuildProblem(jetbrains.buildServer.serverSide.problems.BuildProblem) Files(jetbrains.buildServer.server.rest.model.files.Files) VcsModificationHistory(jetbrains.buildServer.vcs.VcsModificationHistory) Agent(jetbrains.buildServer.server.rest.model.agent.Agent) AuthorityHolder(jetbrains.buildServer.serverSide.auth.AuthorityHolder) BuildDependency(jetbrains.buildServer.serverSide.dependency.BuildDependency) PasswordReplacer(jetbrains.buildServer.util.PasswordReplacer) BuildTypeOrTemplate(jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate) ActionTypesFilter(jetbrains.buildServer.serverSide.impl.audit.filters.ActionTypesFilter) jetbrains.buildServer.server.rest.data(jetbrains.buildServer.server.rest.data) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) BuildType(jetbrains.buildServer.server.rest.model.buildType.BuildType) BigDecimal(java.math.BigDecimal) OperationException(jetbrains.buildServer.server.rest.errors.OperationException) ActionType(jetbrains.buildServer.serverSide.audit.ActionType) TestOccurrenceFinder(jetbrains.buildServer.server.rest.data.problem.TestOccurrenceFinder) AccessDeniedException(jetbrains.buildServer.serverSide.auth.AccessDeniedException) RevisionsNotFoundException(jetbrains.buildServer.vcs.impl.RevisionsNotFoundException) SArtifactDependency(jetbrains.buildServer.serverSide.artifacts.SArtifactDependency) StringUtil(jetbrains.buildServer.util.StringUtil) LogUtil(jetbrains.buildServer.serverSide.impl.LogUtil) Logger(com.intellij.openapi.diagnostic.Logger) CollectionsUtil(jetbrains.buildServer.util.CollectionsUtil) ModelDescription(jetbrains.buildServer.server.rest.swagger.annotations.ModelDescription) AuditLogAction(jetbrains.buildServer.serverSide.audit.AuditLogAction) CanceledInfo(jetbrains.buildServer.serverSide.userChanges.CanceledInfo) SelectPrevBuildPolicy(jetbrains.buildServer.vcs.SelectPrevBuildPolicy) WaitReason(jetbrains.buildServer.serverSide.buildDistribution.WaitReason) AgentTypeFinder(jetbrains.buildServer.serverSide.agentTypes.AgentTypeFinder) AgentRestrictor(jetbrains.buildServer.AgentRestrictor) ServiceLocator(jetbrains.buildServer.ServiceLocator) BaseBuild(jetbrains.buildServer.serverSide.impl.BaseBuild) UserModel(jetbrains.buildServer.users.UserModel) jetbrains.buildServer.serverSide(jetbrains.buildServer.serverSide) Changes(jetbrains.buildServer.server.rest.model.change.Changes) BuildProblemImpl(jetbrains.buildServer.serverSide.impl.problems.BuildProblemImpl) TagFinder(jetbrains.buildServer.server.rest.data.build.TagFinder) Revisions(jetbrains.buildServer.server.rest.model.change.Revisions) Collectors(java.util.stream.Collectors) ChangesBean(jetbrains.buildServer.controllers.changes.ChangesBean) ProblemOccurrenceFinder(jetbrains.buildServer.server.rest.data.problem.ProblemOccurrenceFinder) Nullable(org.jetbrains.annotations.Nullable) TestOccurrences(jetbrains.buildServer.server.rest.model.problem.TestOccurrences) InvalidStateException(jetbrains.buildServer.server.rest.errors.InvalidStateException) BuildAgent(jetbrains.buildServer.BuildAgent) RevisionRule(jetbrains.buildServer.artifacts.RevisionRule) PasswordParametersFilterCore(jetbrains.buildServer.parameters.PasswordParametersFilterCore) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) AgentRestrictorType(jetbrains.buildServer.AgentRestrictorType) Branch(jetbrains.buildServer.serverSide.Branch) BuildChangeData(jetbrains.buildServer.server.rest.data.change.BuildChangeData) BeanContext(jetbrains.buildServer.server.rest.util.BeanContext) NotNull(org.jetbrains.annotations.NotNull) SVcsModification(jetbrains.buildServer.vcs.SVcsModification) ChangesPopupUtil(jetbrains.buildServer.controllers.changes.ChangesPopupUtil) java.util(java.util) SVcsModificationOrChangeDescriptor(jetbrains.buildServer.server.rest.data.change.SVcsModificationOrChangeDescriptor) User(jetbrains.buildServer.server.rest.model.user.User) Converter(jetbrains.buildServer.util.Converter) IssueUsages(jetbrains.buildServer.server.rest.model.issue.IssueUsages) Hex(org.apache.commons.codec.binary.Hex) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ParametersProvider(jetbrains.buildServer.parameters.ParametersProvider) jetbrains.buildServer.server.rest.model(jetbrains.buildServer.server.rest.model) Agents(jetbrains.buildServer.server.rest.model.agent.Agents) AgentPool(jetbrains.buildServer.serverSide.agentPools.AgentPool) Element(jetbrains.buildServer.util.browser.Element) PropEntitiesArtifactDep(jetbrains.buildServer.server.rest.model.buildType.PropEntitiesArtifactDep) XmlType(javax.xml.bind.annotation.XmlType) PasswordsSearcher(jetbrains.buildServer.serverSide.parameters.types.PasswordsSearcher) SAgentType(jetbrains.buildServer.serverSide.agentTypes.SAgentType) RevisionRules(jetbrains.buildServer.artifacts.RevisionRules) Revision(jetbrains.buildServer.server.rest.model.change.Revision) ProblemOccurrences(jetbrains.buildServer.server.rest.model.problem.ProblemOccurrences) XmlAttribute(javax.xml.bind.annotation.XmlAttribute) BuildChanges(jetbrains.buildServer.server.rest.model.change.BuildChanges) Properties(jetbrains.buildServer.server.rest.model.Properties) CachingValue(jetbrains.buildServer.server.rest.util.CachingValue) IOException(java.io.IOException) ArtifactDependencyChangesProvider(jetbrains.buildServer.serverSide.impl.changeProviders.ArtifactDependencyChangesProvider) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) ValueWithDefault(jetbrains.buildServer.server.rest.util.ValueWithDefault) DownloadedArtifacts(jetbrains.buildServer.server.rest.model.build.downloadedArtifacts.DownloadedArtifacts) DownloadedArtifactsLoggerImpl(jetbrains.buildServer.serverSide.impl.DownloadedArtifactsLoggerImpl) jetbrains.buildServer.server.rest.request(jetbrains.buildServer.server.rest.request) MapParametersProviderImpl(jetbrains.buildServer.parameters.impl.MapParametersProviderImpl) VcsLabelManager(jetbrains.buildServer.serverSide.vcs.VcsLabelManager) FileApiUrlBuilder(jetbrains.buildServer.server.rest.model.files.FileApiUrlBuilder) Permission(jetbrains.buildServer.serverSide.auth.Permission) BuildMetadataEntry(jetbrains.buildServer.serverSide.metadata.BuildMetadataEntry) SUser(jetbrains.buildServer.users.SUser) XmlElement(javax.xml.bind.annotation.XmlElement) ParametersProvider(jetbrains.buildServer.parameters.ParametersProvider) NotNull(org.jetbrains.annotations.NotNull) PasswordReplacer(jetbrains.buildServer.util.PasswordReplacer)

Example 3 with ParametersProvider

use of jetbrains.buildServer.parameters.ParametersProvider in project teamcity-rest by JetBrains.

the class VcsRootInstanceFinder method getFilter.

@NotNull
@Override
public ItemFilter<VcsRootInstance> getFilter(@NotNull final Locator locator) {
    final MultiCheckerFilter<VcsRootInstance> result = new MultiCheckerFilter<VcsRootInstance>();
    result.add(item -> hasPermission(Permission.VIEW_BUILD_CONFIGURATION_SETTINGS, item));
    final String type = locator.getSingleDimensionValue(TYPE);
    if (type != null) {
        result.add(new FilterConditionChecker<VcsRootInstance>() {

            public boolean isIncluded(@NotNull final VcsRootInstance item) {
                return type.equals(item.getVcsName());
            }
        });
    }
    if (locator.isUnused(BUILD)) {
        final String build = locator.getSingleDimensionValue(BUILD);
        if (build != null) {
            Set<Long> vcsRootInstanceIds = getVcsRootInstancesByBuilds(build).map(vcsRE -> vcsRE.getId()).collect(Collectors.toSet());
            result.add(item -> vcsRootInstanceIds.contains(item.getId()));
        }
    }
    if (locator.isUnused(VCS_ROOT_DIMENSION)) {
        final String vcsRootLocator = locator.getSingleDimensionValue(VCS_ROOT_DIMENSION);
        if (vcsRootLocator != null) {
            final List<SVcsRoot> vcsRoots = myVcsRootFinder.getItems(vcsRootLocator).myEntries;
            result.add(item -> vcsRoots.contains(item.getParent()));
        }
    }
    // todo: rework to be "there are usages directly in the project", also add to getPrefilteredItems
    // todo: support usage as versioned settings root
    // todo: support multiple here for "from all not archived projects" case
    final String projectLocator = locator.getSingleDimensionValue(PROJECT);
    if (projectLocator != null) {
        final SProject project = myProjectFinder.getItem(projectLocator);
        VcsRootInstance settingsInstance = myVersionedSettingsManager.getVersionedSettingsVcsRootInstance(project);
        final Boolean nonVersionedSettings = locator.lookupSingleDimensionValueAsBoolean(HAS_VERSIONED_SETTINGS_ONLY);
        result.add(new FilterConditionChecker<VcsRootInstance>() {

            public boolean isIncluded(@NotNull final VcsRootInstance item) {
                return // todo: rework project dimensions for the instance to mean smth. more meaningful
                project.equals(VcsRoot.getProjectByRoot(item.getParent())) || (nonVersionedSettings == null || nonVersionedSettings) && item.equals(settingsInstance);
            }
        });
    }
    final String repositoryIdString = locator.getSingleDimensionValue(REPOSITORY_ID_STRING);
    if (repositoryIdString != null) {
        result.add(new FilterConditionChecker<VcsRootInstance>() {

            public boolean isIncluded(@NotNull final VcsRootInstance item) {
                return VcsRootFinder.repositoryIdStringMatches(item, repositoryIdString, myVcsManager);
            }
        });
    }
    final List<String> properties = locator.getDimensionValue(PROPERTY);
    if (!properties.isEmpty()) {
        final Matcher<ParametersProvider> parameterCondition = ParameterCondition.create(properties);
        result.add(new FilterConditionChecker<VcsRootInstance>() {

            public boolean isIncluded(@NotNull final VcsRootInstance item) {
                return parameterCondition.matches(new AbstractMapParametersProvider(item.getProperties()));
            }
        });
    }
    final String status = locator.getSingleDimensionValue(STATUS);
    if (status != null) {
        TypedFinderBuilder<VcsRootInstanceEx> builder = new TypedFinderBuilder<VcsRootInstanceEx>();
        builder.dimensionEnum(TypedFinderBuilder.Dimension.single(), VcsRootStatus.Type.class).description("status of the VCS root instance").valueForDefaultFilter(root -> root.getStatus().getType());
        final TypedFinderBuilder<VcsRootCheckStatus> statusFilterBuilder = new TypedFinderBuilder<VcsRootCheckStatus>();
        statusFilterBuilder.dimensionEnum(new TypedFinderBuilder.Dimension<>("status"), VcsRootStatus.Type.class).description("type of operation").valueForDefaultFilter(vcsRootCheckStatus -> vcsRootCheckStatus.myStatus.getType());
        statusFilterBuilder.dimensionTimeCondition(new TypedFinderBuilder.Dimension<>("timestamp"), myTimeCondition).description("time of the operation start").valueForDefaultFilter(vcsRootCheckStatus -> vcsRootCheckStatus.myStatus.getTimestamp());
        statusFilterBuilder.dimensionEnum(new TypedFinderBuilder.Dimension<>("requestorType"), OperationRequestor.class).description("requestor of the operation").valueForDefaultFilter(vcsRootCheckStatus -> vcsRootCheckStatus.myRequestor);
        Finder<VcsRootCheckStatus> vcsRootCheckStatusFinder = statusFilterBuilder.build();
        builder.dimensionFinderFilter(new TypedFinderBuilder.Dimension<>("current"), vcsRootCheckStatusFinder, "VCS check status condition").description("current VCS root status").valueForDefaultFilter(root -> new VcsRootCheckStatus(root.getStatus(), root.getLastRequestor()));
        builder.dimensionFinderFilter(new TypedFinderBuilder.Dimension<>("previous"), vcsRootCheckStatusFinder, "VCS check status condition").description("previous VCS root status").valueForDefaultFilter(root -> new VcsRootCheckStatus(root.getPreviousStatus(), null));
        final ItemFilter<VcsRootInstanceEx> filter = builder.build().getFilter(status);
        result.add(new FilterConditionChecker<VcsRootInstance>() {

            public boolean isIncluded(@NotNull final VcsRootInstance item) {
                return filter.isIncluded((VcsRootInstanceEx) item);
            }
        });
    }
    final Boolean commitHookMode = locator.getSingleDimensionValueAsBoolean(COMMIT_HOOK_MODE);
    if (commitHookMode != null) {
        result.add(item -> FilterUtil.isIncludedByBooleanFilter(commitHookMode, !((VcsRootInstanceEx) item).isPollingMode()));
    }
    TimeCondition.FilterAndLimitingDate<VcsRootInstance> finishFiltering = myTimeCondition.processTimeConditions(FINISH_VCS_CHECKING_FOR_CHANGES, locator, (vcsRootInstance) -> getFinishCheckingForChanges(vcsRootInstance), null);
    if (finishFiltering != null)
        result.add(finishFiltering.getFilter());
    final String repositoryState = locator.getSingleDimensionValue(REPOSITORY_STATE);
    if (repositoryState != null) {
        TypedFinderBuilder<RepositoryState> builder = new TypedFinderBuilder<RepositoryState>();
        builder.dimensionTimeCondition(new TypedFinderBuilder.Dimension<>("timestamp"), myTimeCondition).description("time of the repository state creation").valueForDefaultFilter(item -> item.getCreateTimestamp());
        builder.dimensionValueCondition(new TypedFinderBuilder.Dimension<>("branchName")).description("branch name").filter((valueCondition, item) -> {
            for (String branchName : item.getBranchRevisions().keySet()) {
                if (valueCondition.matches(branchName))
                    return true;
            }
            return false;
        });
        final ItemFilter<RepositoryState> filter = builder.build().getFilter(repositoryState);
        result.add(new FilterConditionChecker<VcsRootInstance>() {

            public boolean isIncluded(@NotNull final VcsRootInstance item) {
                return filter.isIncluded(((VcsRootInstanceEx) item).getLastUsedState());
            }
        });
    }
    if (locator.isUnused(BUILD_TYPE)) {
        final String buildTypesLocator = locator.getSingleDimensionValue(BUILD_TYPE);
        if (buildTypesLocator != null) {
            Set<VcsRootInstance> vcsRootInstances = getInstances(buildTypesLocator, locator.lookupSingleDimensionValueAsBoolean(HAS_VERSIONED_SETTINGS_ONLY));
            result.add(item -> vcsRootInstances.contains(item));
        }
    }
    // todo: support multiple here
    final String affectedProjectLocator = locator.getSingleDimensionValue(AFFECTED_PROJECT);
    if (affectedProjectLocator != null) {
        final Set<VcsRootInstance> vcsRootInstances = getVcsRootInstancesUnderProject(myProjectFinder.getItem(affectedProjectLocator), locator.getSingleDimensionValueAsBoolean(HAS_VERSIONED_SETTINGS_ONLY));
        result.add(new FilterConditionChecker<VcsRootInstance>() {

            public boolean isIncluded(@NotNull final VcsRootInstance item) {
                return vcsRootInstances.contains(item);
            }
        });
    }
    return result;
}
Also used : java.util(java.util) AuthorizationFailedException(jetbrains.buildServer.server.rest.errors.AuthorizationFailedException) LocatorName(jetbrains.buildServer.server.rest.swagger.constants.LocatorName) LocatorResource(jetbrains.buildServer.server.rest.swagger.annotations.LocatorResource) BuildTypeOrTemplate(jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate) BooleanUtils(org.apache.commons.lang3.BooleanUtils) VersionedSettingsManager(jetbrains.buildServer.serverSide.versionedSettings.VersionedSettingsManager) ParametersProvider(jetbrains.buildServer.parameters.ParametersProvider) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) LocatorDimensionDataType(jetbrains.buildServer.server.rest.swagger.constants.LocatorDimensionDataType) AbstractMapParametersProvider(jetbrains.buildServer.parameters.impl.AbstractMapParametersProvider) VcsRoot(jetbrains.buildServer.server.rest.model.change.VcsRoot) ProjectManager(jetbrains.buildServer.serverSide.ProjectManager) SBuildType(jetbrains.buildServer.serverSide.SBuildType) Logger(com.intellij.openapi.diagnostic.Logger) CollectionsUtil(jetbrains.buildServer.util.CollectionsUtil) PagerData(jetbrains.buildServer.server.rest.model.PagerData) Constants(jetbrains.buildServer.server.rest.request.Constants) ServiceLocator(jetbrains.buildServer.ServiceLocator) Predicate(java.util.function.Predicate) jetbrains.buildServer.vcs(jetbrains.buildServer.vcs) Collectors(java.util.stream.Collectors) Nullable(org.jetbrains.annotations.Nullable) CommonLocatorDimensionsList(jetbrains.buildServer.server.rest.swagger.constants.CommonLocatorDimensionsList) Stream(java.util.stream.Stream) LocatorDimension(jetbrains.buildServer.server.rest.swagger.annotations.LocatorDimension) Permission(jetbrains.buildServer.serverSide.auth.Permission) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) SProject(jetbrains.buildServer.serverSide.SProject) NotNull(org.jetbrains.annotations.NotNull) ReferencesResolverUtil(jetbrains.buildServer.parameters.ReferencesResolverUtil) SProject(jetbrains.buildServer.serverSide.SProject) ParametersProvider(jetbrains.buildServer.parameters.ParametersProvider) AbstractMapParametersProvider(jetbrains.buildServer.parameters.impl.AbstractMapParametersProvider) AbstractMapParametersProvider(jetbrains.buildServer.parameters.impl.AbstractMapParametersProvider) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with ParametersProvider

use of jetbrains.buildServer.parameters.ParametersProvider in project teamcity-rest by JetBrains.

the class VcsRootInstanceFinder method filterOutUnrelatedWithoutParameterResolution.

private void filterOutUnrelatedWithoutParameterResolution(@NotNull final Locator locator, @NotNull final List<SVcsRoot> vcsRoots) {
    final List<String> properties = locator.lookupDimensionValue(PROPERTY);
    if (properties.isEmpty())
        return;
    final Matcher<ParametersProvider> parameterCondition = ParameterCondition.create(properties);
    for (Iterator<SVcsRoot> iterator = vcsRoots.iterator(); iterator.hasNext(); ) {
        SVcsRoot vcsRoot = iterator.next();
        Map<String, String> propertiesMap = vcsRoot.getProperties();
        try {
            // this assumes something about matcher: e.g. that it's logic does not change while processing items
            boolean matches = parameterCondition.matches(new ParametersProvider() {

                @Override
                public String get(@NotNull final String key) {
                    String value = propertiesMap.get(key);
                    if (value != null && ReferencesResolverUtil.containsReference(value)) {
                        throw CannedException.INSTANCE;
                    }
                    return value;
                }

                @Override
                public int size() {
                    return propertiesMap.size();
                }

                @Override
                public Map<String, String> getAll() {
                    if (propertiesMap.entrySet().stream().anyMatch(e -> ReferencesResolverUtil.containsReference(e.getValue()))) {
                        throw CannedException.INSTANCE;
                    }
                    return propertiesMap;
                }
            });
            // while filtering, no reference was encountered: remove from the collection if it does not match the condition
            if (!matches)
                iterator.remove();
        } catch (CannedException ignore) {
        // encountered a reference: preserve in the collection
        }
    }
}
Also used : java.util(java.util) AuthorizationFailedException(jetbrains.buildServer.server.rest.errors.AuthorizationFailedException) LocatorName(jetbrains.buildServer.server.rest.swagger.constants.LocatorName) LocatorResource(jetbrains.buildServer.server.rest.swagger.annotations.LocatorResource) BuildTypeOrTemplate(jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate) BooleanUtils(org.apache.commons.lang3.BooleanUtils) VersionedSettingsManager(jetbrains.buildServer.serverSide.versionedSettings.VersionedSettingsManager) ParametersProvider(jetbrains.buildServer.parameters.ParametersProvider) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) LocatorDimensionDataType(jetbrains.buildServer.server.rest.swagger.constants.LocatorDimensionDataType) AbstractMapParametersProvider(jetbrains.buildServer.parameters.impl.AbstractMapParametersProvider) VcsRoot(jetbrains.buildServer.server.rest.model.change.VcsRoot) ProjectManager(jetbrains.buildServer.serverSide.ProjectManager) SBuildType(jetbrains.buildServer.serverSide.SBuildType) Logger(com.intellij.openapi.diagnostic.Logger) CollectionsUtil(jetbrains.buildServer.util.CollectionsUtil) PagerData(jetbrains.buildServer.server.rest.model.PagerData) Constants(jetbrains.buildServer.server.rest.request.Constants) ServiceLocator(jetbrains.buildServer.ServiceLocator) Predicate(java.util.function.Predicate) jetbrains.buildServer.vcs(jetbrains.buildServer.vcs) Collectors(java.util.stream.Collectors) Nullable(org.jetbrains.annotations.Nullable) CommonLocatorDimensionsList(jetbrains.buildServer.server.rest.swagger.constants.CommonLocatorDimensionsList) Stream(java.util.stream.Stream) LocatorDimension(jetbrains.buildServer.server.rest.swagger.annotations.LocatorDimension) Permission(jetbrains.buildServer.serverSide.auth.Permission) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) SProject(jetbrains.buildServer.serverSide.SProject) NotNull(org.jetbrains.annotations.NotNull) ReferencesResolverUtil(jetbrains.buildServer.parameters.ReferencesResolverUtil) ParametersProvider(jetbrains.buildServer.parameters.ParametersProvider) AbstractMapParametersProvider(jetbrains.buildServer.parameters.impl.AbstractMapParametersProvider)

Example 5 with ParametersProvider

use of jetbrains.buildServer.parameters.ParametersProvider in project teamcity-rest by JetBrains.

the class BuildPromotionFinder method getFilter.

@NotNull
@Override
public ItemFilter<BuildPromotion> getFilter(@NotNull final Locator locator) {
    final MultiCheckerFilter<BuildPromotion> result = new MultiCheckerFilter<BuildPromotion>();
    // checking permissions to view - workaround for TW-45544
    result.add(item -> {
        try {
            ensureCanView(item);
            return true;
        } catch (AccessDeniedException e) {
            // excluding from the lists as secure wrappers usually do
            return false;
        }
    });
    if (locator.isSingleValue()) {
        try {
            long foundPromotionId = getBuildPromotionById(locator.getSingleValueAsLong(), myBuildPromotionManager, myBuildsManager).getId();
            result.add(item -> foundPromotionId == item.getId());
        } catch (NotFoundException e) {
            result.add(item -> false);
        }
    }
    if (locator.isUnused(DEFAULT_FILTERING)) {
        // basically, mark as used if it is not yet processed, but is unset or is set to false
        final Boolean defaultFiltering = locator.getSingleDimensionValueAsBoolean(DEFAULT_FILTERING);
        if (defaultFiltering != null && defaultFiltering) {
            locator.markUnused(DEFAULT_FILTERING);
        }
    }
    final Long id = locator.getSingleDimensionValueAsLong(DIMENSION_ID);
    if (id != null) {
        try {
            long foundPromotionId = getBuildPromotionById(id, myBuildPromotionManager, myBuildsManager).getId();
            result.add(item -> foundPromotionId == item.getId());
        } catch (NotFoundException e) {
            result.add(item -> false);
        }
    }
    final Long promotionId = locator.getSingleDimensionValueAsLong(PROMOTION_ID);
    if (promotionId != null) {
        try {
            long foundPromotionId = BuildFinder.getBuildPromotion(promotionId, myBuildPromotionManager).getId();
            result.add(item -> foundPromotionId == item.getId());
        } catch (NotFoundException e) {
            result.add(item -> false);
        }
    }
    final Long promotionIdAlias = locator.getSingleDimensionValueAsLong(PROMOTION_ID_ALIAS);
    if (promotionIdAlias != null) {
        try {
            long foundPromotionId = BuildFinder.getBuildPromotion(promotionIdAlias, myBuildPromotionManager).getId();
            result.add(item -> foundPromotionId == item.getId());
        } catch (NotFoundException e) {
            result.add(item -> false);
        }
    }
    final Long buildId = locator.getSingleDimensionValueAsLong(BUILD_ID);
    if (buildId != null) {
        result.add(item -> buildId.equals(item.getAssociatedBuildId()));
    }
    Locator stateLocator = getStateLocator(locator);
    if (!isStateIncluded(stateLocator, STATE_QUEUED)) {
        result.add(new FilterConditionChecker<BuildPromotion>() {

            public boolean isIncluded(@NotNull final BuildPromotion item) {
                return item.getQueuedBuild() == null;
            }
        });
    }
    if (!isStateIncluded(stateLocator, STATE_RUNNING)) {
        result.add(new FilterConditionChecker<BuildPromotion>() {

            public boolean isIncluded(@NotNull final BuildPromotion item) {
                final SBuild associatedBuild = item.getAssociatedBuild();
                return associatedBuild == null || associatedBuild.isFinished();
            }
        });
    }
    if (!isStateIncluded(stateLocator, STATE_FINISHED)) {
        result.add(new FilterConditionChecker<BuildPromotion>() {

            public boolean isIncluded(@NotNull final BuildPromotion item) {
                final SBuild associatedBuild = item.getAssociatedBuild();
                return associatedBuild == null || !associatedBuild.isFinished();
            }
        });
    }
    final Boolean composite = locator.getSingleDimensionValueAsBoolean(COMPOSITE);
    if (composite != null) {
        result.add(item -> FilterUtil.isIncludedByBooleanFilter(composite, item.isCompositeBuild()));
    }
    if (locator.isUnused(PROJECT)) {
        SProject project = getProjectFromDimension(locator, PROJECT);
        if (project != null) {
            result.add(item -> {
                final SBuildType buildType = item.getBuildType();
                return buildType != null && project.equals(buildType.getProject());
            });
        }
    }
    if (locator.isUnused(AFFECTED_PROJECT)) {
        SProject affectedProject = getProjectFromDimension(locator, AFFECTED_PROJECT);
        if (affectedProject != null && !affectedProject.isRootProject()) {
            result.add(item -> {
                final SBuildType buildType = item.getBuildType();
                return buildType != null && ProjectFinder.isSameOrParent(affectedProject, buildType.getProject());
            });
        }
    }
    if (locator.isUnused(BUILD_TYPE)) {
        final String buildTypeLocator = locator.getSingleDimensionValue(BUILD_TYPE);
        if (buildTypeLocator != null) {
            final Set<SBuildType> buildTypes = new HashSet<>(myBuildTypeFinder.getBuildTypes(getProjectFromDimension(locator, PROJECT), buildTypeLocator));
            if (buildTypes.isEmpty()) {
                throw new NotFoundException("No build types found for locator '" + buildTypeLocator + "'");
            }
            result.add(new FilterConditionChecker<BuildPromotion>() {

                public boolean isIncluded(@NotNull final BuildPromotion item) {
                    return buildTypes.contains(item.getParentBuildType());
                }
            });
        }
    }
    final String branchLocatorValue = locator.getSingleDimensionValue(BRANCH);
    if (branchLocatorValue != null) {
        PagedSearchResult<? extends Branch> branches = null;
        BadRequestException exceptinoOnFullSearch = null;
        try {
            branches = myBranchFinder.getItemsIfValidBranchListLocator(locator.lookupSingleDimensionValue(BUILD_TYPE), branchLocatorValue);
        } catch (BadRequestException e) {
            // not a valid branches listing locator
            exceptinoOnFullSearch = e;
        }
        if (branches != null) {
            // branches found - use them
            Set<String> branchNames = getBranchNamesSet(branches.myEntries);
            Set<String> branchDisplayNames = getBranchDisplayNamesSet(branches.myEntries);
            boolean defaultBranchIncluded = branches.myEntries.stream().anyMatch(Branch::isDefaultBranch);
            result.add(new FilterConditionChecker<BuildPromotion>() {

                public boolean isIncluded(@NotNull final BuildPromotion item) {
                    final Branch buildBranch = BranchData.fromBuild(item);
                    return (defaultBranchIncluded && buildBranch.isDefaultBranch()) || branchNames.contains(buildBranch.getName()) || branchDisplayNames.contains(buildBranch.getDisplayName());
                }
            });
        } else {
            // branches not found by locator - try to use filter
            BranchFinder.BranchFilterDetails branchFilterDetails;
            try {
                branchFilterDetails = myBranchFinder.getBranchFilterDetails(branchLocatorValue);
            } catch (LocatorProcessException locatorException) {
                throw new BadRequestException("Invalid sub-locator '" + BRANCH + "': Cannot" + (exceptinoOnFullSearch != null ? " find branches: " + exceptinoOnFullSearch.getMessage() + "; and cannot " : "") + " create filter: " + locatorException.getMessage(), locatorException);
            }
            if (!branchFilterDetails.isAnyBranch()) {
                result.add(new FilterConditionChecker<BuildPromotion>() {

                    public boolean isIncluded(@NotNull final BuildPromotion item) {
                        return branchFilterDetails.isIncluded(item);
                    }
                });
            }
        }
    }
    final Boolean branched = locator.getSingleDimensionValueAsBoolean(BRANCHED);
    if (branched != null) {
        result.add(item -> FilterUtil.isIncludedByBooleanFilter(branched, item.getBranch() != null));
    }
    if (locator.isUnused(AGENT)) {
        final String agentLocator = locator.getSingleDimensionValue(AGENT);
        if (agentLocator != null) {
            Set<Integer> agentIds = myAgentFinder.getItemsNotEmpty(agentLocator).myEntries.stream().map(agent -> agent.getId()).filter(i -> i != Agent.UNKNOWN_AGENT_ID).collect(Collectors.toSet());
            result.add(item -> {
                // for queued build using compatible agents
                final SQueuedBuild queuedBuild = item.getQueuedBuild();
                if (queuedBuild != null) {
                    return queuedBuild.getCanRunOnAgents().stream().anyMatch(agent -> agentIds.contains(agent.getId()));
                }
                final SBuild build = item.getAssociatedBuild();
                if (build != null) {
                    return agentIds.contains(build.getAgent().getId());
                }
                return false;
            });
        }
    }
    // compatibility support
    final String tags = locator.getSingleDimensionValue(TAGS);
    if (tags != null) {
        final List<String> tagsList = Arrays.asList(tags.split(","));
        if (tagsList.size() > 0) {
            result.add(new FilterConditionChecker<BuildPromotion>() {

                public boolean isIncluded(@NotNull final BuildPromotion item) {
                    return item.getTags().containsAll(tagsList);
                }
            });
        }
    }
    if (locator.isUnused(TAG)) {
        result.add(getFilterByTag(locator.getDimensionValue(TAG)));
    }
    final String compatibleAgentLocator = locator.getSingleDimensionValue(COMPATIBLE_AGENT);
    if (compatibleAgentLocator != null) {
        List<SBuildAgent> agents = myAgentFinder.getItems(compatibleAgentLocator).myEntries;
        result.add(build -> agents.stream().anyMatch(agent -> myAgentFinder.canActuallyRun(agent, build)));
    }
    // experimental, only for queued builds
    final Long compatibleAgentsCount = locator.getSingleDimensionValueAsLong(COMPATIBLE_AGENTS_COUNT);
    if (compatibleAgentsCount != null) {
        result.add(new FilterConditionChecker<BuildPromotion>() {

            public boolean isIncluded(@NotNull final BuildPromotion item) {
                long count = 0;
                for (SBuildAgent agent : myAgentFinder.getItems(null).myEntries) {
                    // or should process unauthorized as well?
                    if (myAgentFinder.canActuallyRun(agent, item))
                        count++;
                    if (count > compatibleAgentsCount)
                        return false;
                }
                return count == compatibleAgentsCount;
            }
        });
    }
    final Boolean personal = locator.getSingleDimensionValueAsBoolean(PERSONAL);
    if (personal != null) {
        result.add(new FilterConditionChecker<BuildPromotion>() {

            public boolean isIncluded(@NotNull final BuildPromotion item) {
                return FilterUtil.isIncludedByBooleanFilter(personal, item.isPersonal());
            }
        });
    }
    final Boolean history = locator.getSingleDimensionValueAsBoolean(HISTORY);
    if (history != null) {
        result.add(new FilterConditionChecker<BuildPromotion>() {

            public boolean isIncluded(@NotNull final BuildPromotion item) {
                return FilterUtil.isIncludedByBooleanFilter(history, item.isOutOfChangesSequence());
            }
        });
    }
    final String userDimension = locator.getSingleDimensionValue(USER);
    if (userDimension != null) {
        final SUser user = myUserFinder.getItem(userDimension);
        result.add(new FilterConditionChecker<BuildPromotion>() {

            public boolean isIncluded(@NotNull final BuildPromotion item) {
                SUser owner = item.getOwner();
                if (owner != null) {
                    // if owner is present, consider only it: this is consistent with the builds search in the prefiltering
                    return user.getId() == owner.getId();
                }
                SUser actualUser = Util.resolveNull(getTriggeredBy(item), TriggeredBy::getUser);
                return actualUser != null && user.getId() == actualUser.getId();
            }
        });
    }
    final String triggeredDimension = locator.getSingleDimensionValue(TRIGGERED);
    if (triggeredDimension != null) {
        final ItemFilter<TriggeredBy> filter = myTriggerByFinder.getFilter(triggeredDimension);
        result.add(item -> Util.resolveNull(getTriggeredBy(item), filter::isIncluded, false));
    }
    final List<String> properties = locator.getDimensionValue(PROPERTY);
    if (!properties.isEmpty()) {
        final Matcher<ParametersProvider> parameterCondition = ParameterCondition.create(properties);
        result.add(new FilterConditionChecker<BuildPromotion>() {

            public boolean isIncluded(@NotNull final BuildPromotion item) {
                if (!Build.canViewRuntimeData(myPermissionChecker, item))
                    return false;
                // TeamCity open API issue
                return parameterCondition.matches(Build.getBuildResultingParameters(item, myServiceLocator));
            }
        });
    }
    if (locator.getUnusedDimensions().contains(SNAPSHOT_DEP)) {
        // performance optimization: do not filter if already processed
        final String snapshotDepDimension = locator.getSingleDimensionValue(SNAPSHOT_DEP);
        if (snapshotDepDimension != null) {
            final Set<BuildPromotion> snapshotRelatedBuilds = new HashSet<>(getSnapshotRelatedBuilds(snapshotDepDimension));
            result.add(new FilterConditionChecker<BuildPromotion>() {

                public boolean isIncluded(@NotNull final BuildPromotion item) {
                    return snapshotRelatedBuilds.contains(item);
                }
            });
        }
    }
    if (locator.getUnusedDimensions().contains(ARTIFACT_DEP)) {
        // performance optimization: do not filter if already processed
        final String artifactDepDimension = locator.getSingleDimensionValue(ARTIFACT_DEP);
        if (artifactDepDimension != null) {
            final Set<BuildPromotion> artifactRelatedBuilds = new HashSet<>(getArtifactRelatedBuilds(artifactDepDimension, locator));
            result.add(new FilterConditionChecker<BuildPromotion>() {

                public boolean isIncluded(@NotNull final BuildPromotion item) {
                    return artifactRelatedBuilds.contains(item);
                }
            });
        }
    }
    if (locator.isUnused(SNAPSHOT_PROBLEM)) {
        final String snapshotDepProblem = locator.getSingleDimensionValue(SNAPSHOT_PROBLEM);
        if (snapshotDepProblem != null) {
            final Set<BuildPromotion> snapshotDepProblemBuilds = new HashSet<>(getSnapshotDepProblemBuilds(snapshotDepProblem));
            result.add(item -> snapshotDepProblemBuilds.contains(item));
        }
    }
    if (locator.getUnusedDimensions().contains(EQUIVALENT)) {
        // performance optimization: do not filter if already processed
        final String equivalent = locator.getSingleDimensionValue(EQUIVALENT);
        if (equivalent != null) {
            final Set<BuildPromotion> filter = new HashSet<BuildPromotion>(((BuildPromotionEx) getItem(equivalent)).getStartedEquivalentPromotions(-1));
            result.add(new FilterConditionChecker<BuildPromotion>() {

                public boolean isIncluded(@NotNull final BuildPromotion item) {
                    return filter.contains(item);
                }
            });
        }
    }
    if (locator.getUnusedDimensions().contains(METADATA)) {
        // performance optimization: do not filter if already processed
        final String metadata = locator.getSingleDimensionValue(METADATA);
        if (metadata != null) {
            final Iterator<BuildMetadataEntry> metadataEntries = getBuildMetadataEntryIterator(metadata);
            final Set<Long> buildIds = new HashSet<Long>();
            while (metadataEntries.hasNext()) {
                BuildMetadataEntry metadataEntry = metadataEntries.next();
                buildIds.add(metadataEntry.getBuildId());
            }
            result.add(new FilterConditionChecker<BuildPromotion>() {

                public boolean isIncluded(@NotNull final BuildPromotion item) {
                    if (!Build.canViewRuntimeData(myPermissionChecker, item))
                        return false;
                    return buildIds.contains(item.getAssociatedBuildId());
                }
            });
        }
    }
    if (locator.getUnusedDimensions().contains(ORDERED)) {
        // performance optimization: do not filter if already processed
        final String graphLocator = locator.getSingleDimensionValue(ORDERED);
        if (graphLocator != null) {
            final GraphFinder<BuildPromotion> graphFinder = new BuildPromotionOrderedFinder(BuildPromotionFinder.this);
            final Set<BuildPromotion> filter = new HashSet<BuildPromotion>(graphFinder.getItems(graphLocator).myEntries);
            result.add(new FilterConditionChecker<BuildPromotion>() {

                public boolean isIncluded(@NotNull final BuildPromotion item) {
                    return filter.contains(item);
                }
            });
        }
    }
    final String sinceBuildDimension = locator.getSingleDimensionValue(SINCE_BUILD);
    BuildPromotion sinceBuildPromotion = null;
    Long sinceBuildId = null;
    if (sinceBuildDimension != null) {
        try {
            sinceBuildPromotion = getItem(sinceBuildDimension);
            final SQueuedBuild queuedBuild = sinceBuildPromotion.getQueuedBuild();
            if (queuedBuild != null) {
                // compare queued builds by id (triggering sequence)
                final long buildPromotionId = getBuildId(sinceBuildPromotion);
                result.add(new FilterConditionChecker<BuildPromotion>() {

                    public boolean isIncluded(@NotNull final BuildPromotion item) {
                        return buildPromotionId < getBuildId(item);
                    }
                });
            } else {
                // for started build, compare by start time
                final SBuild limitingBuild = sinceBuildPromotion.getAssociatedBuild();
                if (limitingBuild != null) {
                    final Date startDate = limitingBuild.getStartDate();
                    result.add(new FilterConditionChecker<BuildPromotion>() {

                        public boolean isIncluded(@NotNull final BuildPromotion item) {
                            final SBuild build = item.getAssociatedBuild();
                            if (build == null)
                                return true;
                            if (startDate.equals(build.getStartDate()) && limitingBuild.getBuildId() != build.getBuildId())
                                return true;
                            return startDate.before(build.getStartDate());
                        }
                    });
                }
            }
        } catch (NotFoundException e) {
            // build not found by sinceBuild locator, extract id ad filter using it
            sinceBuildId = getBuildId(sinceBuildDimension);
            final long sinceBuildIdFinal = sinceBuildId;
            result.add(new FilterConditionChecker<BuildPromotion>() {

                public boolean isIncluded(@NotNull final BuildPromotion item) {
                    return sinceBuildIdFinal < getBuildId(item);
                }
            });
        }
    }
    final String untilBuild = locator.getSingleDimensionValue(UNTIL_BUILD);
    if (untilBuild != null) {
        try {
            final BuildPromotion untilBuildPromotion = getItem(untilBuild);
            final SQueuedBuild queuedBuild = untilBuildPromotion.getQueuedBuild();
            if (queuedBuild != null) {
                // compare queued builds by id (triggering sequence)
                final long buildPromotionId = getBuildId(untilBuildPromotion);
                result.add(new FilterConditionChecker<BuildPromotion>() {

                    public boolean isIncluded(@NotNull final BuildPromotion item) {
                        return !(buildPromotionId < getBuildId(item));
                    }
                });
            } else {
                // for started build, compare by start time
                final SBuild limitingBuild = untilBuildPromotion.getAssociatedBuild();
                if (limitingBuild != null) {
                    final Date startDate = limitingBuild.getStartDate();
                    result.add(new FilterConditionChecker<BuildPromotion>() {

                        public boolean isIncluded(@NotNull final BuildPromotion item) {
                            final SBuild build = item.getAssociatedBuild();
                            return build == null || !startDate.before(build.getStartDate());
                        }
                    });
                }
            }
        } catch (NotFoundException e) {
            // build not found by sinceBuild locator, extract id ad filter using it
            final long untilBuildId = getBuildId(untilBuild);
            result.add(new FilterConditionChecker<BuildPromotion>() {

                public boolean isIncluded(@NotNull final BuildPromotion item) {
                    return !(untilBuildId < getBuildId(item));
                }
            });
        }
    }
    TimeCondition.FilterAndLimitingDate<BuildPromotion> queuedFiltering = myTimeCondition.processTimeConditions(QUEUED_TIME, locator, TimeCondition.QUEUED_BUILD_TIME, TimeCondition.QUEUED_BUILD_TIME);
    if (queuedFiltering != null)
        result.add(queuedFiltering.getFilter());
    TimeCondition.FilterAndLimitingDate<BuildPromotion> startedFiltering = myTimeCondition.processTimeConditions(STARTED_TIME, locator, TimeCondition.STARTED_BUILD_TIME, TimeCondition.STARTED_BUILD_TIME);
    @Nullable Date sinceStartDate = null;
    if (startedFiltering != null) {
        result.add(startedFiltering.getFilter());
        sinceStartDate = startedFiltering.getLimitingDate();
    }
    // todo: add processing cut of based on assumption of max build time (say, a week); for other times as well
    TimeCondition.FilterAndLimitingDate<BuildPromotion> finishFiltering = myTimeCondition.processTimeConditions(FINISHED_TIME, locator, TimeCondition.FINISHED_BUILD_TIME, TimeCondition.FINISHED_BUILD_TIME);
    if (finishFiltering != null)
        result.add(finishFiltering.getFilter());
    final String revisionLocatorText = locator.getSingleDimensionValue(REVISION);
    if (revisionLocatorText != null) {
        final Locator revisionLocator = new Locator(revisionLocatorText, "version", "internalVersion", "vcsRoot", Locator.LOCATOR_SINGLE_VALUE_UNUSED_NAME);
        final String revision = revisionLocator.getSingleValue();
        if (revision != null) {
            result.add(new FilterConditionChecker<BuildPromotion>() {

                public boolean isIncluded(@NotNull final BuildPromotion item) {
                    // use getAllrevisions map??
                    final List<BuildRevision> buildRevisions = item.getRevisions();
                    for (BuildRevision rev : buildRevisions) {
                        if (revision.equals(rev.getRevisionDisplayName())) {
                            return true;
                        }
                    }
                    return false;
                }
            });
        } else {
            final String vcsRootLocator = revisionLocator.getSingleDimensionValue("vcsRoot");
            final SVcsRoot vcsRoot = vcsRootLocator == null ? null : myVcsRootFinder.getItem(vcsRootLocator);
            final ValueCondition versionCondition = ParameterCondition.createValueCondition(revisionLocator.getSingleDimensionValue("version"));
            final ValueCondition internalVersionCondition = ParameterCondition.createValueCondition(revisionLocator.getSingleDimensionValue("internalVersion"));
            revisionLocator.checkLocatorFullyProcessed();
            if (vcsRoot != null || versionCondition != null || internalVersionCondition != null) {
                result.add(new FilterConditionChecker<BuildPromotion>() {

                    public boolean isIncluded(@NotNull final BuildPromotion item) {
                        // use getAllrevisions map??
                        final List<BuildRevision> revisions = item.getRevisions();
                        for (BuildRevision rev : revisions) {
                            if ((vcsRoot == null || vcsRoot.getId() == rev.getRoot().getParent().getId()) && (versionCondition == null || versionCondition.matches(rev.getRevisionDisplayName())) && (internalVersionCondition == null || internalVersionCondition.matches(rev.getRevision()))) {
                                return true;
                            }
                        }
                        return false;
                    }
                });
            }
        }
    }
    final MultiCheckerFilter<SBuild> buildFilter = getBuildFilter(locator);
    if (buildFilter.getSubFiltersCount() > 0) {
        result.add(new FilterConditionChecker<BuildPromotion>() {

            public boolean isIncluded(@NotNull final BuildPromotion item) {
                final SBuild build = item.getAssociatedBuild();
                if (build == null) {
                    return false;
                }
                return buildFilter.isIncluded(build);
            }
        });
    }
    // see also filtering in getBuildFilter
    sinceStartDate = TimeCondition.maxDate(sinceStartDate, DataProvider.parseDate(locator.getSingleDimensionValue(SINCE_DATE)));
    final Boolean canceled = locator.getSingleDimensionValueAsBoolean(CANCELED);
    if (canceled != null) {
        result.add(new FilterConditionChecker<BuildPromotion>() {

            public boolean isIncluded(@NotNull final BuildPromotion item) {
                final SBuild build = item.getAssociatedBuild();
                return FilterUtil.isIncludedByBooleanFilter(canceled, build != null && build.getCanceledInfo() != null);
            }
        });
    }
    final Boolean failedToStart = locator.getSingleDimensionValueAsBoolean(FAILED_TO_START);
    if (failedToStart != null) {
        result.add(new FilterConditionChecker<BuildPromotion>() {

            public boolean isIncluded(@NotNull final BuildPromotion item) {
                final SBuild build = item.getAssociatedBuild();
                return FilterUtil.isIncludedByBooleanFilter(failedToStart, build != null && build.isInternalError());
            }
        });
    }
    return getFilterWithProcessingCutOff(result, locator.getSingleDimensionValueAsLong(SINCE_BUILD_ID_LOOK_AHEAD_COUNT), sinceBuildPromotion, sinceBuildId, sinceStartDate);
}
Also used : LocatorProcessException(jetbrains.buildServer.server.rest.errors.LocatorProcessException) MetadataStorageEx(jetbrains.buildServer.serverSide.metadata.impl.MetadataStorageEx) Filter(jetbrains.buildServer.util.filters.Filter) java.util(java.util) LocatorName(jetbrains.buildServer.server.rest.swagger.constants.LocatorName) LocatorResource(jetbrains.buildServer.server.rest.swagger.annotations.LocatorResource) Agent(jetbrains.buildServer.server.rest.model.agent.Agent) BuildDependency(jetbrains.buildServer.serverSide.dependency.BuildDependency) Converter(jetbrains.buildServer.util.Converter) ParametersProvider(jetbrains.buildServer.parameters.ParametersProvider) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) LocatorDimensionDataType(jetbrains.buildServer.server.rest.swagger.constants.LocatorDimensionDataType) AbstractMapParametersProvider(jetbrains.buildServer.parameters.impl.AbstractMapParametersProvider) TestOccurrenceFinder(jetbrains.buildServer.server.rest.data.problem.TestOccurrenceFinder) AccessDeniedException(jetbrains.buildServer.serverSide.auth.AccessDeniedException) ErrorData(jetbrains.buildServer.messages.ErrorData) StringUtil(jetbrains.buildServer.util.StringUtil) Build(jetbrains.buildServer.server.rest.model.build.Build) Logger(com.intellij.openapi.diagnostic.Logger) CollectionsUtil(jetbrains.buildServer.util.CollectionsUtil) jetbrains.buildServer.server.rest.data.util(jetbrains.buildServer.server.rest.data.util) PagerData(jetbrains.buildServer.server.rest.model.PagerData) SVcsRoot(jetbrains.buildServer.vcs.SVcsRoot) PatternSyntaxException(java.util.regex.PatternSyntaxException) Constants(jetbrains.buildServer.server.rest.request.Constants) ServiceLocator(jetbrains.buildServer.ServiceLocator) jetbrains.buildServer.serverSide(jetbrains.buildServer.serverSide) ItemsProviders(jetbrains.buildServer.server.rest.model.ItemsProviders) TagFinder(jetbrains.buildServer.server.rest.data.build.TagFinder) ItemProcessor(jetbrains.buildServer.util.ItemProcessor) StreamUtil(jetbrains.buildServer.server.rest.util.StreamUtil) Collectors(java.util.stream.Collectors) Nullable(org.jetbrains.annotations.Nullable) CommonLocatorDimensionsList(jetbrains.buildServer.server.rest.swagger.constants.CommonLocatorDimensionsList) Stream(java.util.stream.Stream) LocatorDimension(jetbrains.buildServer.server.rest.swagger.annotations.LocatorDimension) Util(jetbrains.buildServer.server.rest.model.Util) Permission(jetbrains.buildServer.serverSide.auth.Permission) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) TestFinder(jetbrains.buildServer.server.rest.data.problem.TestFinder) BuildMetadataEntry(jetbrains.buildServer.serverSide.metadata.BuildMetadataEntry) Pattern(java.util.regex.Pattern) NotNull(org.jetbrains.annotations.NotNull) SUser(jetbrains.buildServer.users.SUser) AccessDeniedException(jetbrains.buildServer.serverSide.auth.AccessDeniedException) SUser(jetbrains.buildServer.users.SUser) ServiceLocator(jetbrains.buildServer.ServiceLocator) CommonLocatorDimensionsList(jetbrains.buildServer.server.rest.swagger.constants.CommonLocatorDimensionsList) Nullable(org.jetbrains.annotations.Nullable) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) LocatorProcessException(jetbrains.buildServer.server.rest.errors.LocatorProcessException) ParametersProvider(jetbrains.buildServer.parameters.ParametersProvider) AbstractMapParametersProvider(jetbrains.buildServer.parameters.impl.AbstractMapParametersProvider) NotNull(org.jetbrains.annotations.NotNull) SVcsRoot(jetbrains.buildServer.vcs.SVcsRoot) BuildMetadataEntry(jetbrains.buildServer.serverSide.metadata.BuildMetadataEntry) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

Logger (com.intellij.openapi.diagnostic.Logger)5 java.util (java.util)5 Collectors (java.util.stream.Collectors)5 ServiceLocator (jetbrains.buildServer.ServiceLocator)5 ParametersProvider (jetbrains.buildServer.parameters.ParametersProvider)5 BadRequestException (jetbrains.buildServer.server.rest.errors.BadRequestException)5 NotFoundException (jetbrains.buildServer.server.rest.errors.NotFoundException)5 Permission (jetbrains.buildServer.serverSide.auth.Permission)5 CollectionsUtil (jetbrains.buildServer.util.CollectionsUtil)5 NotNull (org.jetbrains.annotations.NotNull)5 Nullable (org.jetbrains.annotations.Nullable)5 Stream (java.util.stream.Stream)4 AbstractMapParametersProvider (jetbrains.buildServer.parameters.impl.AbstractMapParametersProvider)3 TagFinder (jetbrains.buildServer.server.rest.data.build.TagFinder)3 TestOccurrenceFinder (jetbrains.buildServer.server.rest.data.problem.TestOccurrenceFinder)3 PagerData (jetbrains.buildServer.server.rest.model.PagerData)3 Constants (jetbrains.buildServer.server.rest.request.Constants)3 LocatorDimension (jetbrains.buildServer.server.rest.swagger.annotations.LocatorDimension)3 LocatorResource (jetbrains.buildServer.server.rest.swagger.annotations.LocatorResource)3 CommonLocatorDimensionsList (jetbrains.buildServer.server.rest.swagger.constants.CommonLocatorDimensionsList)3