Search in sources :

Example 21 with NotFoundException

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

the class AvatarRequest method getAvatar.

@GET
@Produces(MediaType.IMAGE_PNG_VALUE)
@Path("/{userLocator}/{size}/avatar.png")
@ApiOperation("Get a users avatar")
public Response getAvatar(@Context HttpServletResponse response, @ApiParam(format = LocatorName.USER) @PathParam("userLocator") String userLocator, @ApiParam(value = "avatar's size", allowableValues = "range[" + MIN_AVATAR_SIZE + ", " + MAX_AVATAR_SIZE + "]") @PathParam("size") Integer size) throws IOException {
    if (size < MIN_AVATAR_SIZE || size > MAX_AVATAR_SIZE) {
        throw new BadRequestException("\"size\" must be bigger or equal than " + MIN_AVATAR_SIZE + " and lower or equal than " + MAX_AVATAR_SIZE);
    }
    final SUser user = myUserFinder.getItem(userLocator);
    final BufferedImage image = myUserAvatarsManager.getAvatar(user, size);
    if (image == null)
        throw new NotFoundException("avatar (username: " + user.getUsername() + ") not found");
    final int avatarCacheLifeTime = getAvatarCacheLifetime();
    response.setHeader(HttpHeaders.CACHE_CONTROL, CACHE_CONTROL_MAX_AGE + avatarCacheLifeTime);
    ImageIO.write(image, "png", response.getOutputStream());
    return Response.ok().build();
}
Also used : SUser(jetbrains.buildServer.users.SUser) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) BufferedImage(java.awt.image.BufferedImage) ApiOperation(io.swagger.annotations.ApiOperation)

Example 22 with NotFoundException

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

the class RoleAssignment method getScope.

// See also jetbrains.buildServer.server.rest.data.UserFinder.RoleEntryDatas.getScope()
@NotNull
public static RoleScope getScope(@NotNull String scopeData, @NotNull final ServiceLocator serviceLocator) {
    if ("g".equalsIgnoreCase(scopeData)) {
        return RoleScope.globalScope();
    }
    if (!scopeData.startsWith("p:")) {
        throw new NotFoundException("Cannot find scope by '" + scopeData + "' Valid formats are: 'g' or 'p:<projectId>'.");
    }
    final String projectString = scopeData.substring(2);
    final EntityId<String> internalId = serviceLocator.getSingletonService(ProjectIdentifiersManager.class).findEntityIdByExternalId(projectString);
    if (internalId == null) {
        // throw new InvalidStateException("Could not find project internal id by external id '" + projectString + "'.");
        // support locator here just in case
        final SProject project = serviceLocator.getSingletonService(ProjectFinder.class).getItem(projectString);
        return RoleScope.projectScope(project.getProjectId());
    }
    return RoleScope.projectScope(internalId.getInternalId());
}
Also used : NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) ProjectFinder(jetbrains.buildServer.server.rest.data.ProjectFinder) SProject(jetbrains.buildServer.serverSide.SProject) ProjectIdentifiersManager(jetbrains.buildServer.serverSide.identifiers.ProjectIdentifiersManager) NotNull(org.jetbrains.annotations.NotNull)

Example 23 with NotFoundException

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

the class ProjectRequest method reloadSettingsFile.

/**
 * Experimental use only!
 */
// until @Path("/{projectLocator}/loadingErrors") is implemented
@GET
@Path("/{projectLocator}/latest")
@Produces({ "application/xml", "application/json" })
@ApiOperation(value = "reloadSettingsFile", hidden = true)
public Project reloadSettingsFile(@ApiParam(format = LocatorName.PROJECT) @PathParam("projectLocator") String projectLocator, @QueryParam("fields") String fields) {
    myPermissionChecker.checkGlobalPermission(Permission.MANAGE_SERVER_INSTALLATION);
    try {
        SProject project = myProjectFinder.getItem(projectLocator);
        String projectConfigFile = project.getConfigurationFile().getAbsolutePath();
        myBeanContext.getSingletonService(ProjectsLoader.class).reloadProjects(emptyList(), Collections.singleton(new File(projectConfigFile)), emptyList());
    } catch (NotFoundException e) {
        // this server doesn't see this project
        if (!projectLocator.contains("id:")) {
            throw e;
        }
        File projectsDir = myServiceLocator.getSingletonService(ServerPaths.class).getProjectsDir();
        File projectDir = new File(projectsDir, projectLocator.substring(projectLocator.indexOf("id:") + 3));
        String projectConfigFile = new File(projectDir, XmlConstants.PROJECT_CONFIG_FILENAME).getAbsolutePath();
        myBeanContext.getSingletonService(ProjectsLoader.class).reloadProjects(singleton(new File(projectConfigFile)), emptyList(), emptyList());
    }
    return new Project(myProjectFinder.getItem(projectLocator), new Fields(fields), myBeanContext);
}
Also used : Fields(jetbrains.buildServer.server.rest.model.Fields) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) ProjectsLoader(jetbrains.buildServer.serverSide.impl.projects.ProjectsLoader) File(java.io.File) ApiOperation(io.swagger.annotations.ApiOperation)

Example 24 with NotFoundException

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

the class ProjectRequest method setDefaultTemplate.

@PUT
@Path("/{projectLocator}/defaultTemplate")
@Consumes({ "application/xml", "application/json" })
@Produces({ "application/xml", "application/json" })
@ApiOperation(value = "Update the default template of the matching project.", nickname = "setDefaultTemplate")
public BuildType setDefaultTemplate(@ApiParam(format = LocatorName.PROJECT) @PathParam("projectLocator") String projectLocator, BuildType defaultTemplate, @QueryParam("fields") String fields) {
    ProjectEx project = (ProjectEx) myProjectFinder.getItem(projectLocator, true);
    if (defaultTemplate == null)
        throw new BadRequestException("No payload found while template is expected");
    BuildTypeOrTemplate newDefaultTemplate = defaultTemplate.getBuildTypeFromPosted(myBuildTypeFinder);
    BuildTypeTemplate result = newDefaultTemplate.getTemplate();
    if (result == null) {
        throw new BadRequestException("Found build type when template is expected: " + LogUtil.describe(newDefaultTemplate.getBuildType()));
    }
    Boolean inherited = newDefaultTemplate.isInherited();
    BuildTypeTemplate currentDefaultTemplate = project.getDefaultTemplate();
    if (inherited == null || !inherited || (currentDefaultTemplate != null && !currentDefaultTemplate.getInternalId().equals(newDefaultTemplate.getInternalId()))) {
        try {
            project.setDefaultTemplate(result);
        } catch (CyclicDependencyFoundException e) {
            throw new BadRequestException(e.getMessage());
        }
        project.schedulePersisting("Default template changed");
    }
    BuildType template = Project.getDefaultTemplate(project, new Fields(fields), myBeanContext);
    if (template == null)
        throw new NotFoundException("No default template present");
    return template;
}
Also used : ProjectEx(jetbrains.buildServer.serverSide.impl.ProjectEx) BuildTypeOrTemplate(jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate) CyclicDependencyFoundException(jetbrains.buildServer.serverSide.dependency.CyclicDependencyFoundException) Fields(jetbrains.buildServer.server.rest.model.Fields) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) BuildType(jetbrains.buildServer.server.rest.model.buildType.BuildType) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) ApiOperation(io.swagger.annotations.ApiOperation)

Example 25 with NotFoundException

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

the class FilesSubResource method getContentByStream.

public static Response.ResponseBuilder getContentByStream(@NotNull final Element element, @NotNull final HttpServletRequest request, @NotNull final StreamingOutputProvider streamingOutputProvider) {
    // TeamCity API: need to lock artifacts while reading???  e.g. see JavaDoc for jetbrains.buildServer.serverSide.artifacts.BuildArtifacts.iterateArtifacts()
    if (!element.isContentAvailable()) {
        throw new NotFoundException("Cannot provide content for '" + element.getFullName() + "' (not a file).");
    }
    final String rangeHeader = request.getHeader(HttpHeaders.RANGE);
    Long fullFileSize = null;
    try {
        final long size = element.getSize();
        if (size >= 0) {
            fullFileSize = size;
        }
    } catch (IllegalStateException e) {
    // just do not set size in the case
    }
    Response.ResponseBuilder builder;
    if (StringUtil.isEmpty(rangeHeader)) {
        builder = Response.ok().entity(streamingOutputProvider.getStreamingOutput(null, null));
        if (fullFileSize != null) {
            builder.header(HttpHeaders.CONTENT_LENGTH, fullFileSize);
        }
    } else {
        if (!streamingOutputProvider.isRangeSupported()) {
            throw new BadRequestException("Ranged requests are not supported for this entity");
        }
        try {
            HttpByteRange range = new HttpByteRange(rangeHeader, fullFileSize);
            // todo: support requests with "Range: bytes=XX-" header and unknown content-length via multipart/byteranges Content-Type including Content-Range fields for each part
            if (range.getRangesCount() > 1) {
                builder = Response.status(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE).entity("Multiple Range header ranges are not (yet) supported");
            } else {
                final HttpByteRange.SimpleRange firstRange = range.getSimpleRangesIterator().next();
                builder = Response.status(HttpServletResponse.SC_PARTIAL_CONTENT);
                final long rangeLength = firstRange.getLength();
                builder.entity(streamingOutputProvider.getStreamingOutput(firstRange.getBeginIndex(), rangeLength));
                builder.header("Content-Range", range.getContentRangeHeaderValue(firstRange));
                if (fullFileSize != null) {
                    builder.header(HttpHeaders.CONTENT_LENGTH, rangeLength);
                }
            }
        } catch (ParseException e) {
            builder = Response.status(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE).entity("Error parsing Range header: " + e.getMessage());
            if (fullFileSize != null) {
                builder.header("Content-Range", HttpByteRange.getContentRangeHeaderValueFor416Response(fullFileSize));
            }
        }
    }
    builder.header("Accept-Ranges", HttpByteRange.RANGE_UNIT_BYTES);
    if (TeamCityProperties.getBooleanOrTrue("rest.build.artifacts.setMimeType")) {
        builder = builder.type(WebUtil.getMimeType(request, element.getName()));
    } else {
        builder = builder.type(MediaType.APPLICATION_OCTET_STREAM_TYPE);
    }
    if (TeamCityProperties.getBooleanOrTrue("rest.build.artifacts.forceContentDisposition.Attachment")) {
        // make sure the file is not displayed in the browser (TW-27206)
        builder = builder.header("Content-Disposition", WebUtil.getContentDispositionValue(request, "attachment", element.getName()));
    } else {
        builder = builder.header("Content-Disposition", WebUtil.getContentDispositionValue(request, null, element.getName()));
    }
    if (element instanceof ArtifactTreeElement) {
        final Long lastModified = ((ArtifactTreeElement) element).getLastModified();
        if (lastModified != null) {
            builder.lastModified(new Date(lastModified));
        }
        final long size = element.getSize();
        // mark ETag as "weak"
        builder.header("ETag", "W/\"" + EncryptUtil.md5((size >= 0 ? String.valueOf(size) : "") + (lastModified != null ? lastModified : "")) + "\"");
    } else {
        final long size = element.getSize();
        if (size >= 0) {
            // mark ETag as "weak"
            builder.header("ETag", "W/\"" + EncryptUtil.md5(String.valueOf(size)) + "\"");
        }
    }
    return builder;
}
Also used : HttpByteRange(jetbrains.buildServer.web.util.HttpByteRange) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) Date(java.util.Date) HttpServletResponse(javax.servlet.http.HttpServletResponse) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) ParseException(java.text.ParseException) ArtifactTreeElement(jetbrains.buildServer.web.artifacts.browser.ArtifactTreeElement)

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