Search in sources :

Example 26 with NotFoundException

use of jetbrains.buildServer.server.rest.errors.NotFoundException in project teamcity-rest by JetBrains.

the class FilesSubResource method getContent.

@GET
@Path(FilesSubResource.CONTENT + "{path:(/.*)?}")
@Produces({ MediaType.WILDCARD })
@ApiOperation(value = "getContent", hidden = true)
public Response getContent(@PathParam("path") final String path, @QueryParam("responseBuilder") final String responseBuilder, @Context HttpServletRequest request, @Context HttpServletResponse response) {
    final String preprocessedPath = myProvider.preprocess(StringUtil.removeLeadingSlash(path));
    final Element initialElement = myProvider.getElement(preprocessedPath);
    if (!initialElement.isContentAvailable()) {
        throw new NotFoundException("Cannot provide content for '" + initialElement.getFullName() + "'. To get children use '" + fileApiUrlBuilder(null, myUrlPrefix).getChildrenHref(initialElement) + "'.");
    }
    String contentResponseBuilder = getSetting("rest.files.contentResponseBuilder", "coreWithDownloadProcessor", "responseBuilder", responseBuilder, true, "rest", "core", "coreWithDownloadProcessor");
    if ("rest".equals(contentResponseBuilder)) {
        // pre-2017.1 way of downloading files
        final Response.ResponseBuilder builder = getContent(initialElement, request);
        myProvider.fileContentServed(preprocessedPath, request);
        setCacheControl(request, response);
        return builder.build();
    } else if ("core".equals(contentResponseBuilder)) {
        processCoreDownload(initialElement, request, response);
    } else if ("coreWithDownloadProcessor".equals(contentResponseBuilder)) {
        if (!(myProvider instanceof DownloadProcessor) || !((DownloadProcessor) myProvider).processDownload(initialElement, request, response)) {
            processCoreDownload(initialElement, request, response);
        }
    } else {
        throw new BadRequestException("Unknown responseBuilder: '" + contentResponseBuilder + "'. Supported values are: '" + "rest" + "', '" + "core" + "', '" + "coreWithDownloadProcessor" + "'");
    }
    // todo: register only if no errors occurred?
    myProvider.fileContentServed(preprocessedPath, request);
    if (!response.isCommitted()) {
        // let Jersey know what the response should be, otherwise 304 responses can turn to 204
        return Response.status(response.getStatus()).build();
    }
    return null;
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpDownloadProcessor(jetbrains.buildServer.controllers.HttpDownloadProcessor) ArchiveElement(jetbrains.buildServer.server.rest.data.ArchiveElement) Element(jetbrains.buildServer.util.browser.Element) ArtifactElement(jetbrains.buildServer.web.artifacts.browser.ArtifactElement) ArtifactTreeElement(jetbrains.buildServer.web.artifacts.browser.ArtifactTreeElement) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) ApiOperation(io.swagger.annotations.ApiOperation)

Example 27 with NotFoundException

use of jetbrains.buildServer.server.rest.errors.NotFoundException in project teamcity-rest by JetBrains.

the class BuildTypeRequest method serveBuildTypeTemplate.

/**
 * @Deprecated Use .../templates instead
 */
@GET
@Path("/{btLocator}/template")
@Produces({ "application/xml", "application/json" })
@ApiOperation(hidden = true, value = "Use .../templates instead")
public BuildType serveBuildTypeTemplate(@ApiParam(format = LocatorName.BUILD_TYPE) @PathParam("btLocator") String buildTypeLocator, @QueryParam("fields") String fields) {
    SBuildType buildType = myBuildTypeFinder.getBuildType(null, buildTypeLocator, true);
    final BuildTypeTemplate template;
    try {
        template = buildType.getTemplate();
    } catch (BuildTypeTemplateNotFoundException e) {
        throw new AuthorizationFailedException("The template is not accessible. Cross-hierarchy template use?");
    }
    if (template == null) {
        // todo: how to report it duly?
        throw new NotFoundException("No template associated.");
    }
    return new BuildType(new BuildTypeOrTemplate(template), new Fields(fields), myBeanContext);
}
Also used : BuildTypeOrTemplate(jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate) AuthorizationFailedException(jetbrains.buildServer.server.rest.errors.AuthorizationFailedException) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) ApiOperation(io.swagger.annotations.ApiOperation)

Example 28 with NotFoundException

use of jetbrains.buildServer.server.rest.errors.NotFoundException in project teamcity-rest by JetBrains.

the class ChangeRequest method getFilteredFiles.

/**
 * Experimental support only!
 * todo: Is it better to have this somewhere in Change model? E.g. fields=change(files($filterByBuildType(<buildTypeId>),name,...)))
 * @since 2021.1.1
 */
@GET
@Path("/{changeLocator}/files")
@Produces({ "application/xml", "application/json" })
@ApiOperation(value = "Get files of the matching change filtered by relation to a given buildType.", nickname = "getFilteredFiles", hidden = true)
public FileChanges getFilteredFiles(@ApiParam(format = LocatorName.CHANGE) @PathParam("changeLocator") String changeLocatorString, @QueryParam("buildTypeId") String builtTypeId, @QueryParam("fields") String fields) {
    Locator changeLocator = Locator.createPotentiallyEmptyLocator(changeLocatorString);
    SVcsModification change = myChangeFinder.getItem(changeLocator.getStringRepresentation()).getSVcsModification();
    if (builtTypeId == null) {
        // Convenience method, same as Change.getFileChanges()
        ChangeStatusProvider myStatusProvider = myServiceLocator.getSingletonService(ChangeStatusProvider.class);
        ChangeStatus changeStatus = myStatusProvider.getMergedChangeStatus(change);
        return new FileChanges(new ArrayList<>(changeStatus.getMergedVcsModificationInfo().getChangedFiles()), new Fields(fields));
    }
    SBuildType buildType = myBuildTypeFinder.getItem(builtTypeId).getBuildType();
    if (buildType == null) {
        throw new NotFoundException("Build type not found.");
    }
    if (change.getRelatedConfigurations().stream().noneMatch(relatedBt -> relatedBt.getExternalId().equals(buildType.getExternalId()))) {
        ChangeStatusProvider myStatusProvider = myServiceLocator.getSingletonService(ChangeStatusProvider.class);
        ChangeStatus changeStatus = myStatusProvider.getMergedChangeStatus(change);
        return new FileChanges(new ArrayList<>(changeStatus.getMergedVcsModificationInfo().getChangedFiles()), new Fields(fields));
    }
    return new FileChanges(change.getFilteredChanges(buildType), new Fields(fields));
}
Also used : SVcsModification(jetbrains.buildServer.vcs.SVcsModification) ChangeStatus(jetbrains.buildServer.vcs.ChangeStatus) ServiceLocator(jetbrains.buildServer.ServiceLocator) Locator(jetbrains.buildServer.server.rest.data.Locator) Fields(jetbrains.buildServer.server.rest.model.Fields) SBuildType(jetbrains.buildServer.serverSide.SBuildType) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) ChangeStatusProvider(jetbrains.buildServer.vcs.ChangeStatusProvider) ApiOperation(io.swagger.annotations.ApiOperation)

Example 29 with NotFoundException

use of jetbrains.buildServer.server.rest.errors.NotFoundException in project teamcity-rest by JetBrains.

the class UserRequest method removeGroup.

@DELETE
@Path("/{userLocator}/groups/{groupLocator}")
@ApiOperation(value = "Remove the matching user from the specific group.", nickname = "removeUserFromGroup")
public void removeGroup(@ApiParam(format = LocatorName.USER) @PathParam("userLocator") String userLocator, @PathParam("groupLocator") String groupLocator, @QueryParam("fields") String fields) {
    if (TeamCityProperties.getBooleanOrTrue(UserFinder.REST_CHECK_ADDITIONAL_PERMISSIONS_ON_USERS_AND_GROUPS)) {
        myUserFinder.checkViewAllUsersPermission();
    }
    SUser user = myUserFinder.getItem(userLocator, true);
    SUserGroup group = myBeanContext.getSingletonService(UserGroupFinder.class).getGroup(groupLocator);
    if (!user.getUserGroups().contains(group)) {
        throw new NotFoundException("User does not belong to the group");
    }
    group.removeUser(user);
}
Also used : SUser(jetbrains.buildServer.users.SUser) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) SUserGroup(jetbrains.buildServer.groups.SUserGroup) ApiOperation(io.swagger.annotations.ApiOperation)

Example 30 with NotFoundException

use of jetbrains.buildServer.server.rest.errors.NotFoundException in project teamcity-rest by JetBrains.

the class UserRequest method createToken.

@POST
@Path("/{userLocator}/tokens")
@Produces({ "application/xml", "application/json" })
@ApiOperation(value = "Create a new authentication token for the matching user.", nickname = "addUserToken")
public Token createToken(Token token, @PathParam("userLocator") String userLocator, @QueryParam("fields") String fields) {
    if (token.getName() == null) {
        throw new BadRequestException("name cannot be empty");
    }
    if (TeamCityProperties.getBooleanOrTrue(UserFinder.REST_CHECK_ADDITIONAL_PERMISSIONS_ON_USERS_AND_GROUPS)) {
        myUserFinder.checkViewAllUsersPermission();
    }
    final TokenAuthenticationModel tokenAuthenticationModel = myBeanContext.getSingletonService(TokenAuthenticationModel.class);
    final SUser user = myUserFinder.getItem(userLocator, true);
    try {
        final AuthenticationToken authenticationToken;
        if (token.getPermissionRestrictions() != null) {
            final List<PermissionRestriction> permissionRestrictions = token.getPermissionRestrictions().myPermissionRestrictions;
            if (permissionRestrictions == null) {
                throw new IllegalArgumentException("Malformed permission restrictions");
            }
            final Map<RoleScope, Permissions> restrictions = new HashMap<>();
            for (PermissionRestriction permissionRestriction : permissionRestrictions) {
                final RoleScope roleScope;
                if (BooleanUtils.isTrue(permissionRestriction.isGlobalScope)) {
                    roleScope = RoleScope.globalScope();
                } else if (permissionRestriction.project != null && permissionRestriction.project.id != null) {
                    final SProject project = myBeanContext.getSingletonService(ProjectManager.class).findProjectByExternalId(permissionRestriction.project.id);
                    if (project == null) {
                        throw new NotFoundException("Project not found for external id [" + permissionRestriction.project.id + "]");
                    }
                    roleScope = RoleScope.projectScope(project.getProjectId());
                } else {
                    throw new IllegalArgumentException("Malformed permission restrictions, either isGlobalScope should be set to true or project should not be null");
                }
                if (permissionRestriction.permission == null || permissionRestriction.permission.id == null) {
                    throw new IllegalArgumentException("Permission should not be null");
                }
                try {
                    final Permission permission = Permission.valueOf(permissionRestriction.permission.id.toUpperCase());
                    if (roleScope.isGlobal()) {
                        if (!user.isPermissionGrantedGlobally(permission)) {
                            throw new AuthorizationFailedException("User don't have " + permission + " to be restricted globally");
                        }
                    } else {
                        if (!(user.isPermissionGrantedGlobally(permission) || user.isPermissionGrantedForProject(roleScope.getProjectId(), permission))) {
                            throw new AuthorizationFailedException("User don't have permission " + permission + " to be restricted on project [" + roleScope.getProjectId() + "]");
                        }
                    }
                    restrictions.merge(roleScope, new Permissions(permission), Permissions::mergeWith);
                } catch (IllegalArgumentException e) {
                    throw new BadRequestException("Permission not found for input [" + permissionRestriction.permission.name + "]");
                }
            }
            if (permissionRestrictions.isEmpty()) {
                throw new BadRequestException("Malformed permission restrictions");
            }
            authenticationToken = tokenAuthenticationModel.createToken(user.getId(), token.getName(), token.getExpirationTime(), new AuthenticationToken.PermissionsRestriction(restrictions));
        } else {
            authenticationToken = tokenAuthenticationModel.createToken(user.getId(), token.getName(), token.getExpirationTime());
        }
        return new Token(authenticationToken, authenticationToken.getValue(), new Fields(fields), myBeanContext);
    } catch (AuthenticationTokenStorage.CreationException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : HashMap(java.util.HashMap) SUser(jetbrains.buildServer.users.SUser) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) SProject(jetbrains.buildServer.serverSide.SProject) Fields(jetbrains.buildServer.server.rest.model.Fields) AuthorizationFailedException(jetbrains.buildServer.server.rest.errors.AuthorizationFailedException) Permission(jetbrains.buildServer.serverSide.auth.Permission) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) ApiOperation(io.swagger.annotations.ApiOperation)

Aggregations

NotFoundException (jetbrains.buildServer.server.rest.errors.NotFoundException)47 BadRequestException (jetbrains.buildServer.server.rest.errors.BadRequestException)26 ApiOperation (io.swagger.annotations.ApiOperation)19 NotNull (org.jetbrains.annotations.NotNull)14 BuildTypeOrTemplate (jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate)13 ServiceLocator (jetbrains.buildServer.ServiceLocator)10 SUser (jetbrains.buildServer.users.SUser)10 SVcsRoot (jetbrains.buildServer.vcs.SVcsRoot)10 Nullable (org.jetbrains.annotations.Nullable)8 LocatorProcessException (jetbrains.buildServer.server.rest.errors.LocatorProcessException)7 AuthorizationFailedException (jetbrains.buildServer.server.rest.errors.AuthorizationFailedException)5 Fields (jetbrains.buildServer.server.rest.model.Fields)5 Converter (jetbrains.buildServer.util.Converter)4 RevisionsNotFoundException (jetbrains.buildServer.vcs.impl.RevisionsNotFoundException)4 Logger (com.intellij.openapi.diagnostic.Logger)3 java.util (java.util)3 Collectors (java.util.stream.Collectors)3 SUserGroup (jetbrains.buildServer.groups.SUserGroup)3 SArtifactDependency (jetbrains.buildServer.serverSide.artifacts.SArtifactDependency)3 Permission (jetbrains.buildServer.serverSide.auth.Permission)3