Search in sources :

Example 96 with BadRequestException

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

the class FilesSubResource method getChildren.

@GET
@Path(FilesSubResource.CHILDREN + "{path:(/.*)?}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "getChildren", hidden = true)
public Files getChildren(@PathParam("path") @DefaultValue("") final String path, @QueryParam("basePath") final String basePath, @QueryParam("locator") final String locator, @QueryParam("fields") String fields) {
    if (!myArchiveBrowsingSupported && locator != null) {
        final Boolean browseArchives = new Locator(locator).getSingleDimensionValueAsBoolean(BuildArtifactsFinder.ARCHIVES_DIMENSION_NAME);
        if (browseArchives != null && browseArchives) {
            throw new BadRequestException("Archive browsing is not supported for this request, remove '" + BuildArtifactsFinder.ARCHIVES_DIMENSION_NAME + "' dimension");
        }
    }
    final FileApiUrlBuilder builder = fileApiUrlBuilder(locator, myUrlPrefix);
    final Element rootElement = myProvider.getElement(myProvider.preprocess(StringUtil.removeLeadingSlash(path)));
    return new Files(null, new Files.DefaultFilesProvider(builder, myBeanContext) {

        @Override
        @NotNull
        public List<? extends Element> getItems() {
            return BuildArtifactsFinder.getItems(rootElement, myProvider.preprocess(basePath), locator, builder, myBeanContext.getServiceLocator());
        }
    }, new Fields(fields), myBeanContext);
}
Also used : Locator(jetbrains.buildServer.server.rest.data.Locator) FileApiUrlBuilder(jetbrains.buildServer.server.rest.model.files.FileApiUrlBuilder) Fields(jetbrains.buildServer.server.rest.model.Fields) 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) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) List(java.util.List) Files(jetbrains.buildServer.server.rest.model.files.Files) NotNull(org.jetbrains.annotations.NotNull) ApiOperation(io.swagger.annotations.ApiOperation)

Example 97 with BadRequestException

use of jetbrains.buildServer.server.rest.errors.BadRequestException 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 98 with BadRequestException

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

the class TwoFactorRequest method confirmTwoFactor.

@POST
@Path("/confirm")
@ApiOperation(value = "Confirm 2FA secret key", nickname = "confirm2FA")
public void confirmTwoFactor(@QueryParam("uuid") String uuid, @QueryParam("password") int password, @Context HttpServletRequest request) {
    if (uuid == null) {
        throw new BadRequestException("Missing parameter 'uuid'");
    }
    try {
        myKeysUpdater.confirmCredentials(myUserFinder.getCurrentUser(), UUID.fromString(uuid), password);
        // TODO: attempt to prevent instant kick after enabled 2FA without context request
        TwoFactorAuthUtil.setTwoFactorCompletion(request);
    } catch (TwoFactorConfirmationException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : TwoFactorConfirmationException(jetbrains.buildServer.serverSide.auth.impl.TwoFactorConfirmationException) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) ApiOperation(io.swagger.annotations.ApiOperation)

Example 99 with BadRequestException

use of jetbrains.buildServer.server.rest.errors.BadRequestException 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)

Example 100 with BadRequestException

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

the class UserRequest method removeUserProperty.

@DELETE
@Path("/{userLocator}/properties/{name}")
@ApiOperation(value = "Remove a property of the matching user.", nickname = "removeUserProperty")
public void removeUserProperty(@ApiParam(format = LocatorName.USER) @PathParam("userLocator") String userLocator, @PathParam("name") String name) {
    SUser user = myUserFinder.getItem(userLocator, true);
    if (StringUtil.isEmpty(name)) {
        throw new BadRequestException("Property name cannot be empty.");
    }
    user.deleteUserProperty(new SimplePropertyKey(name));
}
Also used : SimplePropertyKey(jetbrains.buildServer.users.SimplePropertyKey) SUser(jetbrains.buildServer.users.SUser) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) ApiOperation(io.swagger.annotations.ApiOperation)

Aggregations

BadRequestException (jetbrains.buildServer.server.rest.errors.BadRequestException)128 NotNull (org.jetbrains.annotations.NotNull)52 ApiOperation (io.swagger.annotations.ApiOperation)39 NotFoundException (jetbrains.buildServer.server.rest.errors.NotFoundException)35 ServiceLocator (jetbrains.buildServer.ServiceLocator)28 BuildTypeOrTemplate (jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate)22 Nullable (org.jetbrains.annotations.Nullable)22 SUser (jetbrains.buildServer.users.SUser)19 Fields (jetbrains.buildServer.server.rest.model.Fields)17 LocatorProcessException (jetbrains.buildServer.server.rest.errors.LocatorProcessException)16 Collectors (java.util.stream.Collectors)10 SProject (jetbrains.buildServer.serverSide.SProject)9 StringUtil (jetbrains.buildServer.util.StringUtil)9 Date (java.util.Date)8 jetbrains.buildServer.serverSide (jetbrains.buildServer.serverSide)8 java.util (java.util)7 Locator (jetbrains.buildServer.server.rest.data.Locator)7 OperationException (jetbrains.buildServer.server.rest.errors.OperationException)7 PagerData (jetbrains.buildServer.server.rest.model.PagerData)7 Permission (jetbrains.buildServer.serverSide.auth.Permission)7