Search in sources :

Example 56 with SUser

use of jetbrains.buildServer.users.SUser in project teamcity-rest by JetBrains.

the class BuildQueueRequest method queueNewBuild.

@POST
@Consumes({ "application/xml", "application/json" })
@Produces({ "application/xml", "application/json" })
@ApiOperation(value = "Add a new build to the queue.", nickname = "addBuildToQueue")
public Build queueNewBuild(Build build, @QueryParam("moveToTop") Boolean moveToTop, @Context HttpServletRequest request, @Context HttpServletResponse response) {
    if (QueueWebUtil.processLargeQueueCase(request, response, myServiceLocator.getSingletonService(BuildQueue.class))) {
        return null;
    }
    final SUser user = myServiceLocator.getSingletonService(UserFinder.class).getCurrentUser();
    SQueuedBuild queuedBuild = build.triggerBuild(user, myServiceLocator, new HashMap<Long, Long>());
    if (moveToTop != null && moveToTop) {
        final BuildQueue buildQueue = myServiceLocator.getSingletonService(BuildQueue.class);
        buildQueue.moveTop(queuedBuild.getItemId());
    }
    return new Build(queuedBuild.getBuildPromotion(), Fields.LONG, myBeanContext);
}
Also used : Build(jetbrains.buildServer.server.rest.model.build.Build) SUser(jetbrains.buildServer.users.SUser) ApiOperation(io.swagger.annotations.ApiOperation)

Example 57 with SUser

use of jetbrains.buildServer.users.SUser in project teamcity-rest by JetBrains.

the class AgentRequest method setEnabledInfo.

@PUT
@Path("/{agentLocator}/enabledInfo")
@Consumes({ "application/xml", "application/json" })
@Produces({ "application/xml", "application/json" })
@ApiOperation(value = "Update the enablement status of the matching agent.", nickname = "setEnabledInfo")
public AgentEnabledInfo setEnabledInfo(@ApiParam(format = LocatorName.AGENT) @PathParam("agentLocator") String agentLocator, AgentEnabledInfo enabledInfo, @QueryParam("fields") String fields) {
    final SBuildAgent agent = myAgentFinder.getItem(agentLocator);
    if (enabledInfo == null)
        throw new BadRequestException("No data is sent as payload.");
    String commentText = enabledInfo.getCommentTextFromPosted();
    Boolean value = enabledInfo.getStatusFromPosted();
    if (value == null && commentText == null)
        throw new BadRequestException("Neither value nor comment are provided, nothing to change");
    Date switchTime = enabledInfo.getStatusSwitchTimeFromPosted(myServiceLocator);
    SUser currentUser = myServiceLocator.getSingletonService(UserFinder.class).getCurrentUser();
    if (switchTime == null) {
        agent.setEnabled(value != null ? value : agent.isEnabled(), currentUser, Agent.getActualActionComment(commentText));
    } else {
        agent.setEnabled(value != null ? value : agent.isEnabled(), currentUser, Agent.getActualActionComment(commentText), switchTime.getTime());
    }
    return new AgentEnabledInfo(agent, new Fields(fields), myBeanContext);
}
Also used : Fields(jetbrains.buildServer.server.rest.model.Fields) SUser(jetbrains.buildServer.users.SUser) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) SBuildAgent(jetbrains.buildServer.serverSide.SBuildAgent) Date(java.util.Date) ApiOperation(io.swagger.annotations.ApiOperation)

Example 58 with SUser

use of jetbrains.buildServer.users.SUser in project teamcity-rest by JetBrains.

the class Query method globalPermissions.

@NotNull
public GlobalPermissions globalPermissions(@NotNull DataFetchingEnvironment env) {
    GraphQLContext ctx = env.getContext();
    SUser user = ctx.getUser();
    if (user == null) {
        return new GlobalPermissions(false);
    }
    return new GlobalPermissions(user.getGlobalPermissions().contains(Permission.MANAGE_AGENT_POOLS));
}
Also used : GlobalPermissions(jetbrains.buildServer.server.graphql.model.GlobalPermissions) SUser(jetbrains.buildServer.users.SUser) GraphQLContext(jetbrains.buildServer.server.graphql.GraphQLContext) NotNull(org.jetbrains.annotations.NotNull)

Example 59 with SUser

use of jetbrains.buildServer.users.SUser in project teamcity-rest by JetBrains.

the class BranchFinder method getPrefilteredItemsInternal.

@NotNull
private ItemHolder<BranchData> getPrefilteredItemsInternal(@NotNull final Locator locator, boolean existenseCheck) {
    String buildLocator = locator.getSingleDimensionValue(BUILD);
    if (!StringUtil.isEmpty(buildLocator)) {
        BuildPromotion build = myServiceLocator.getSingletonService(BuildPromotionFinder.class).getItem(buildLocator);
        return getItemHolder(Collections.singleton(BranchData.fromBuild(build)));
    }
    final String buildTypeLocator = locator.getSingleDimensionValue(BUILD_TYPE);
    if (buildTypeLocator == null) {
        throw new BadRequestException("No '" + BUILD_TYPE + "' dimension is present but it is required for searching branches. Locator: '" + locator.getStringRepresentation() + "'");
    }
    final List<SBuildType> buildTypes = myBuildTypeFinder.getBuildTypes(null, buildTypeLocator);
    AggregatingItemHolder<BranchData> result = new AggregatingItemHolder<>();
    final String groupsInclude = locator.getSingleDimensionValue(GROUP_INCLUDE);
    if (groupsInclude != null) {
        SUser user = validateAndgetGroupIncludeUser(groupsInclude);
        BranchGroupsService branchGroupsService = myServiceLocator.getSingletonService(BranchGroupsService.class);
        result.add(FinderDataBinding.getItemHolder(buildTypes.stream().flatMap(buildType -> branchGroupsService.getAvailableBranchGroups(new BranchGroupsProvider.Context((BuildTypeEx) buildType, user)).stream()).distinct().map(branchGroup -> BranchData.fromBranchGroup(branchGroup))));
    }
    final String groupDimension = locator.getSingleDimensionValue(BRANCH_GROUP);
    if (groupDimension != null) {
        UserFinder userFinder = myServiceLocator.getSingletonService(UserFinder.class);
        BranchGroupsService branchGroupsService = myServiceLocator.getSingletonService(BranchGroupsService.class);
        Locator branchGroupLocator = new Locator(groupDimension, "id", "user", Locator.LOCATOR_SINGLE_VALUE_UNUSED_NAME);
        String userLocator = branchGroupLocator.getSingleDimensionValue("user");
        SUser user = userLocator == null ? userFinder.getCurrentUser() : userFinder.getItem(userLocator);
        if (user == null) {
            throw new BadRequestException("Can only filter by branch group when the user is present");
        } else {
            userFinder.checkViewUserPermission(user);
        }
        String branchGroupId = branchGroupLocator.isSingleValue() ? branchGroupLocator.getSingleValue() : branchGroupLocator.getSingleDimensionValue("id");
        if (branchGroupId == null) {
            throw new BadRequestException("Dimension '" + BRANCH_GROUP + "' does not specify 'id' subdimension. Example: " + branchGroupsService.getAvailableBranchGroups(new BranchGroupsProvider.Context((BuildTypeEx) buildTypes.get(0), user)).stream().map(branchGroup -> branchGroup.getId()).collect(Collectors.joining(", ")));
        }
        branchGroupLocator.checkLocatorFullyProcessed();
        result.add(processor -> {
            try {
                buildTypes.forEach(buildType -> branchGroupsService.collectBranches(branchGroupId, new BranchGroupsProvider.Context((BuildTypeEx) buildType, user), item -> processor.processItem(BranchData.fromBranchEx(item, myServiceLocator, null, true))));
            } catch (IllegalStateException e) {
                throw new BadRequestException("Error retrieving branch groups: " + e.getMessage());
            }
        });
        return result;
    }
    BranchSearchOptions searchOptions = getBranchSearchOptions(locator);
    boolean lookingForDefaultBranch = BooleanUtils.isTrue(locator.getSingleDimensionValueAsBoolean(DEFAULT));
    // i.e. loose relevant item.
    if (lookingForDefaultBranch && existenseCheck && locator.getUnusedDimensions().isEmpty()) {
        for (SBuildType buildType : buildTypes) {
            final BranchData branch = detectDefaultBranch(buildType, searchOptions);
            // As soon as default branch is found, create a simple processor and don't look into other buildTypes.
            if (branch != null) {
                result.add(processor -> processor.processItem(branch));
                break;
            }
        }
    } else {
        locator.markUnused(DEFAULT);
        Filter<SBuildType> dependenciesFilter = getBranchDependenciesFilter(buildTypes);
        if (existenseCheck) {
            // We don't use deduplication here as in this case we have a chance to stop earlier
            // using lazy stream evaluation and avoid getting branches from all build types.
            // We also skip computing timestamps as that is unnecessary for an existence check.
            locator.markUsed(COMPUTE_TIMESTAMPS);
            Stream<BranchData> branchStream = buildTypes.stream().flatMap(buildType -> getBranches(buildType, searchOptions, false, dependenciesFilter));
            result.add(FinderDataBinding.getItemHolder(branchStream));
        } else {
            DeduplicatingAccumulator resultAccumulator = new DeduplicatingAccumulator();
            for (SBuildType buildType : buildTypes) {
                Boolean locatorComputeTimestamps = locator.getSingleDimensionValueAsBoolean(COMPUTE_TIMESTAMPS);
                boolean finalComputeTimestamps = locatorComputeTimestamps != null ? locatorComputeTimestamps : TeamCityProperties.getBoolean("rest.beans.branch.defaultComputeTimestamp");
                Stream<BranchData> branchStream = getBranches(buildType, searchOptions, finalComputeTimestamps, dependenciesFilter);
                resultAccumulator.addAll(branchStream.collect(Collectors.toList()));
            }
            result.add(FinderDataBinding.getItemHolder(resultAccumulator.get()));
        }
    }
    return result;
}
Also used : LocatorProcessException(jetbrains.buildServer.server.rest.errors.LocatorProcessException) Filter(jetbrains.buildServer.util.filters.Filter) java.util(java.util) LocatorName(jetbrains.buildServer.server.rest.swagger.constants.LocatorName) DuplicateChecker(jetbrains.buildServer.server.rest.data.util.DuplicateChecker) LocatorResource(jetbrains.buildServer.server.rest.swagger.annotations.LocatorResource) ComparatorDuplicateChecker(jetbrains.buildServer.server.rest.data.util.ComparatorDuplicateChecker) BuildTypeOrTemplate(jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BooleanUtils(org.apache.commons.lang3.BooleanUtils) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) LocatorDimensionDataType(jetbrains.buildServer.server.rest.swagger.constants.LocatorDimensionDataType) StringUtil(jetbrains.buildServer.util.StringUtil) ServiceLocator(jetbrains.buildServer.ServiceLocator) jetbrains.buildServer.serverSide(jetbrains.buildServer.serverSide) ItemProcessor(jetbrains.buildServer.util.ItemProcessor) ComparisonChain(com.google.common.collect.ComparisonChain) Collectors(java.util.stream.Collectors) AggregatingItemHolder(jetbrains.buildServer.server.rest.data.util.AggregatingItemHolder) Nullable(org.jetbrains.annotations.Nullable) Contract(org.jetbrains.annotations.Contract) Stream(java.util.stream.Stream) LocatorDimension(jetbrains.buildServer.server.rest.swagger.annotations.LocatorDimension) NotNull(org.jetbrains.annotations.NotNull) SUser(jetbrains.buildServer.users.SUser) SUser(jetbrains.buildServer.users.SUser) ServiceLocator(jetbrains.buildServer.ServiceLocator) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) AggregatingItemHolder(jetbrains.buildServer.server.rest.data.util.AggregatingItemHolder) NotNull(org.jetbrains.annotations.NotNull)

Example 60 with SUser

use of jetbrains.buildServer.users.SUser in project teamcity-rest by JetBrains.

the class ChangeStatus method initCounters.

private void initCounters() {
    // This is heavily inspired by ChangeDetailsCalculator, but with some simplifications, so not reusing it here.
    SecurityContext context = myBeanContext.getSingletonService(SecurityContext.class);
    SUser self = (SUser) context.getAuthorityHolder().getAssociatedUser();
    myCriticalCollector = new BuildsCollector(myFields.getNestedField("criticalBuilds"));
    myCompilationErrorCollector = new BuildsCollector(myFields.getNestedField("compilationErrorBuilds"));
    myNewTestsFailedCollector = new BuildsCollector(myFields.getNestedField("newTestsFailedBuilds"));
    myNotCriticalCollector = new BuildsCollector(myFields.getNestedField("notCriticalBuilds"));
    final boolean includePersonalBuilds = self != null && StringUtil.isTrue(self.getPropertyValue(StandardProperties.SHOW_ALL_PERSONAL_BUILDS));
    for (BuildTypeChangeStatus status : myChangeStatus.getBuildTypesStatus().values()) {
        final SBuild firstBuild = status.getFirstBuild();
        if (firstBuild == null) {
            SQueuedBuild queued = status.getQueuedBuild();
            if (queued != null && (includePersonalBuilds || !queued.isPersonal())) {
                myQueuedBuildsCount++;
            }
            if (status.getQueuedBuild() == null) {
                myPendingCount++;
            }
            continue;
        }
        if (firstBuild.isPersonal() && !includePersonalBuilds) {
            continue;
        }
        if (firstBuild.getCanceledInfo() != null) {
            myCancelledCount++;
            continue;
        }
        if (firstBuild.isFinished()) {
            myFinishedBuildsCount++;
            if (status.isSuccessful()) {
                mySuccessfulBuildsCount++;
                // no need to count problems, as our build is green
                continue;
            }
        } else {
            myRunningBuildsCount++;
            Status runningBuildStatus = firstBuild.getBuildStatus();
            if (runningBuildStatus.isSuccessful()) {
                myRunningSuccessfullyCount++;
                // no need to count problems, as our build is green
                continue;
            }
        }
        myFailedBuildsCount++;
        String statusText = BuildStatusText.getBuildStatus(firstBuild, self);
        final BuildPromotionEx buildPromo = (BuildPromotionEx) firstBuild.getBuildPromotion();
        switch(statusText) {
            case BuildStatusText.NEW_TESTS_FAILED:
                myNewTestsFailedCollector.put(buildPromo);
                break;
            case BuildStatusText.CRITICAL_PROBLEM:
                myCriticalCollector.put(buildPromo);
                break;
            case BuildStatusText.COMPILATION_ERROR:
                myCompilationErrorCollector.put(buildPromo);
                break;
            default:
                myNotCriticalCollector.put(buildPromo);
        }
        for (BuildProblem problem : buildPromo.getBuildProblems()) {
            if (problem.isMutedInBuild())
                continue;
            if (problem.getBuildProblemData().getType().equals(BuildProblemData.TC_FAILED_TESTS_TYPE) || ErrorData.isSnapshotDependencyError(problem.getBuildProblemData().getType()))
                continue;
            myTotalProblemCount++;
        }
    }
}
Also used : Status(jetbrains.buildServer.messages.Status) BuildTypeChangeStatus(jetbrains.buildServer.vcs.BuildTypeChangeStatus) SUser(jetbrains.buildServer.users.SUser) BuildTypeChangeStatus(jetbrains.buildServer.vcs.BuildTypeChangeStatus) SecurityContext(jetbrains.buildServer.serverSide.auth.SecurityContext) BuildProblem(jetbrains.buildServer.serverSide.problems.BuildProblem)

Aggregations

SUser (jetbrains.buildServer.users.SUser)125 Test (org.testng.annotations.Test)70 ApiOperation (io.swagger.annotations.ApiOperation)35 BaseFinderTest (jetbrains.buildServer.server.rest.data.BaseFinderTest)35 Build (jetbrains.buildServer.server.rest.model.build.Build)20 BadRequestException (jetbrains.buildServer.server.rest.errors.BadRequestException)18 NotNull (org.jetbrains.annotations.NotNull)18 NotFoundException (jetbrains.buildServer.server.rest.errors.NotFoundException)15 SecurityContextEx (jetbrains.buildServer.serverSide.SecurityContextEx)13 Fields (jetbrains.buildServer.server.rest.model.Fields)12 SUserGroup (jetbrains.buildServer.groups.SUserGroup)11 ProjectEx (jetbrains.buildServer.serverSide.impl.ProjectEx)10 ServiceLocator (jetbrains.buildServer.ServiceLocator)9 BuildTypeImpl (jetbrains.buildServer.serverSide.impl.BuildTypeImpl)9 Nullable (org.jetbrains.annotations.Nullable)9 LocatorProcessException (jetbrains.buildServer.server.rest.errors.LocatorProcessException)8 SecurityContextImpl (jetbrains.buildServer.serverSide.impl.auth.SecurityContextImpl)8 java.util (java.util)7 Collectors (java.util.stream.Collectors)7 jetbrains.buildServer.serverSide (jetbrains.buildServer.serverSide)7