Search in sources :

Example 91 with BadRequestException

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

the class ProjectRequest method createBuildType.

/**
 * Creates a new build configuration by copying existing one.
 *
 * @param projectLocator
 * @param descriptor     reference to the build configuration to copy and copy options.
 *                       e.g. <newBuildTypeDescription name='Conf Name' id='ProjectId_ConfId' copyAllAssociatedSettings='true'><sourceBuildType id='sourceConfId'/></newBuildTypeDescription>
 * @return the build configuration created
 */
@POST
@Path("/{projectLocator}/buildTypes")
@Produces({ "application/xml", "application/json" })
@Consumes({ "application/xml", "application/json" })
@ApiOperation(value = "Add a build configuration to the matching project.", nickname = "addBuildType")
public BuildType createBuildType(@ApiParam(format = LocatorName.PROJECT) @PathParam("projectLocator") String projectLocator, NewBuildTypeDescription descriptor, @QueryParam("fields") String fields) {
    @NotNull SProject project = myProjectFinder.getItem(projectLocator);
    SBuildType resultingBuildType;
    @Nullable final BuildTypeOrTemplate sourceBuildType = descriptor.getSourceBuildTypeOrTemplate(myServiceLocator);
    if (sourceBuildType == null) {
        resultingBuildType = project.createBuildType(descriptor.getId(myServiceLocator, project), descriptor.getName());
    } else {
        if (sourceBuildType.isBuildType()) {
            resultingBuildType = project.copyBuildType(sourceBuildType.getBuildType(), descriptor.getId(myServiceLocator, project), descriptor.getName(), descriptor.getCopyOptions());
        } else {
            throw new BadRequestException("Could not create build type as a copy of a template.");
        }
    }
    resultingBuildType.schedulePersisting("A new build configuration is created");
    return new BuildType(new BuildTypeOrTemplate(resultingBuildType), new Fields(fields), myBeanContext);
}
Also used : BuildTypeOrTemplate(jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate) Fields(jetbrains.buildServer.server.rest.model.Fields) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) BuildType(jetbrains.buildServer.server.rest.model.buildType.BuildType) NotNull(org.jetbrains.annotations.NotNull) Nullable(org.jetbrains.annotations.Nullable) ApiOperation(io.swagger.annotations.ApiOperation)

Example 92 with BadRequestException

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

the class ProjectRequest method setProjectAgentPools.

@POST
@Path("/{projectLocator}/agentPools")
@Produces({ "application/xml", "application/json" })
@Consumes({ "application/xml", "application/json" })
@ApiOperation(value = "Assign the matching project to the agent pool.", nickname = "addAgentPoolsProject")
public AgentPool setProjectAgentPools(@ApiParam(format = LocatorName.PROJECT) @PathParam("projectLocator") String projectLocator, AgentPool pool) {
    SProject project = myProjectFinder.getItem(projectLocator);
    final AgentPoolManager agentPoolManager = myServiceLocator.getSingletonService(AgentPoolManager.class);
    final jetbrains.buildServer.serverSide.agentPools.AgentPool agentPoolFromPosted = pool.getAgentPoolFromPosted(myAgentPoolFinder);
    final int agentPoolId = agentPoolFromPosted.getAgentPoolId();
    try {
        agentPoolManager.associateProjectsWithPool(agentPoolId, singleton(project.getProjectId()));
    } catch (NoSuchAgentPoolException e) {
        throw new BadRequestException("Agent pool with id \'" + agentPoolId + "' is not found.");
    }
    return new AgentPool(agentPoolFromPosted, Fields.LONG, myBeanContext);
}
Also used : NoSuchAgentPoolException(jetbrains.buildServer.serverSide.agentPools.NoSuchAgentPoolException) AgentPoolManager(jetbrains.buildServer.serverSide.agentPools.AgentPoolManager) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) AgentPool(jetbrains.buildServer.server.rest.model.agent.AgentPool) ApiOperation(io.swagger.annotations.ApiOperation)

Example 93 with BadRequestException

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

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

the class ServerRequest method startBackup.

/**
 * @param fileName               relative file name to save backup to (will be saved into
 *                               the default backup directory (<tt>.BuildServer/backup</tt>
 *                               if not overriden in main-config.xml)
 * @param addTimestamp           whether to add timestamp to the file or not
 * @param includeConfigs         whether to include configs into the backup or not
 * @param includeDatabase        whether to include database into the backup or not
 * @param includeBuildLogs       whether to include build logs into the backup or not
 * @param includePersonalChanges whether to include personal changes into the backup or not
 * @return the resulting file name that the backup will be saved to
 */
@POST
@Path("/backup")
@Produces({ "text/plain" })
@ApiOperation(value = "Start a new backup.", nickname = "startBackup")
public String startBackup(@QueryParam("fileName") String fileName, @QueryParam("addTimestamp") Boolean addTimestamp, @QueryParam("includeConfigs") Boolean includeConfigs, @QueryParam("includeDatabase") Boolean includeDatabase, @QueryParam("includeBuildLogs") Boolean includeBuildLogs, @QueryParam("includePersonalChanges") Boolean includePersonalChanges, @QueryParam("includeRunningBuilds") Boolean includeRunningBuilds, @QueryParam("includeSupplimentaryData") Boolean includeSupplimentaryData) {
    BackupProcessManager backupManager = myServiceLocator.getSingletonService(BackupProcessManager.class);
    BackupConfig backupConfig = new BackupConfig();
    if (StringUtil.isNotEmpty(fileName)) {
        if (!TeamCityProperties.getBoolean("rest.request.server.backup.allowAnyTargetPath")) {
            File backupDir = new File(myDataProvider.getBean(ServerPaths.class).getBackupDir());
            try {
                FileSecurityUtil.checkInsideDirectory(FileUtil.resolvePath(backupDir, fileName), backupDir);
            } catch (Exception e) {
                // the message contains absolute paths
                if (myPermissionChecker.hasGlobalPermission(Permission.MANAGE_SERVER_INSTALLATION)) {
                    throw e;
                }
                throw new BadRequestException("Target file name (" + fileName + ") should be relative path.", null);
            }
        }
        if (addTimestamp != null) {
            backupConfig.setFileName(fileName, addTimestamp);
        } else {
            backupConfig.setFileName(fileName);
        }
    } else {
        throw new BadRequestException("No target file name specified.", null);
    }
    if (includeConfigs != null)
        backupConfig.setIncludeConfiguration(includeConfigs);
    if (includeDatabase != null)
        backupConfig.setIncludeDatabase(includeDatabase);
    if (includeBuildLogs != null)
        backupConfig.setIncludeBuildLogs(includeBuildLogs);
    if (includePersonalChanges != null)
        backupConfig.setIncludePersonalChanges(includePersonalChanges);
    if (includeRunningBuilds != null)
        backupConfig.setIncludeRunningBuilds(includeRunningBuilds);
    if (includeSupplimentaryData != null)
        backupConfig.setIncludeSupplementaryData(includeSupplimentaryData);
    try {
        backupManager.startBackup(backupConfig);
    } catch (MaintenanceProcessAlreadyRunningException e) {
        throw new InvalidStateException("Cannot start backup because another maintenance process is in progress", e);
    }
    return backupConfig.getResultFileName();
}
Also used : BackupConfig(jetbrains.buildServer.serverSide.maintenance.BackupConfig) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) MaintenanceProcessAlreadyRunningException(jetbrains.buildServer.serverSide.maintenance.MaintenanceProcessAlreadyRunningException) BackupProcessManager(jetbrains.buildServer.serverSide.maintenance.BackupProcessManager) InvalidStateException(jetbrains.buildServer.server.rest.errors.InvalidStateException) File(java.io.File) MaintenanceProcessAlreadyRunningException(jetbrains.buildServer.serverSide.maintenance.MaintenanceProcessAlreadyRunningException) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) InvalidStateException(jetbrains.buildServer.server.rest.errors.InvalidStateException) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) ApiOperation(io.swagger.annotations.ApiOperation)

Example 95 with BadRequestException

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

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