Search in sources :

Example 21 with BadRequestException

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

the class ProjectRequest method createProject.

@POST
@Consumes({ "application/xml", "application/json" })
@Produces({ "application/xml", "application/json" })
@ApiOperation(value = "Create a new project.", nickname = "addProject")
public Project createProject(NewProjectDescription descriptor) {
    if (StringUtil.isEmpty(descriptor.name)) {
        throw new BadRequestException("Project name cannot be empty.");
    }
    SProject resultingProject;
    @Nullable SProject sourceProject = descriptor.getSourceProject(myServiceLocator);
    final ProjectManager projectManager = myDataProvider.getServer().getProjectManager();
    final SProject parentProject = descriptor.getParentProject(myServiceLocator);
    if (sourceProject == null) {
        resultingProject = parentProject.createProject(descriptor.getId(myServiceLocator), descriptor.name);
    } else {
        final CopyOptions copyOptions = descriptor.getCopyOptions();
        // see also getExampleNewProjectDescription which prepares NewProjectDescription
        copyOptions.addProjectExternalIdMapping(Collections.singletonMap(sourceProject.getExternalId(), descriptor.getId(myServiceLocator)));
        copyOptions.setGenerateExternalIdsBasedOnOriginalExternalIds(ID_GENERATION_FLAG);
        if (descriptor.name != null)
            copyOptions.setNewProjectName(descriptor.name);
        try {
            resultingProject = projectManager.copyProject(sourceProject, parentProject, copyOptions);
        } catch (MaxNumberOfBuildTypesReachedException e) {
            throw new BadRequestException("Build configurations number limit is reached", e);
        } catch (NotAllIdentifiersMappedException e) {
            throw new BadRequestException("Not all ids are mapped", e);
        } catch (InvalidNameException e) {
            throw new BadRequestException("Invalid name", e);
        } catch (DuplicateExternalIdException e) {
            throw new BadRequestException("Duplicate id", e);
        }
        try {
            if (descriptor.name != null)
                resultingProject.setName(descriptor.name);
            // todo: TeamCity api: is this necessary? http://youtrack.jetbrains.com/issue/TW-28495
            resultingProject.setExternalId(descriptor.getId(myServiceLocator));
        } catch (InvalidIdentifierException | DuplicateExternalIdException e) {
            processCreatedProjectFinalizationError(resultingProject, projectManager, e);
        } catch (AccessDeniedException e) {
            LOG.debug(() -> "Got access denied while setting project parameters. This is most probably because the token permissions don't propagate to a newly created child project", e);
        }
    }
    try {
        resultingProject.schedulePersisting("A new project was created");
    } catch (PersistFailedException e) {
        processCreatedProjectFinalizationError(resultingProject, projectManager, e);
    }
    return new Project(resultingProject, Fields.LONG, myBeanContext);
}
Also used : AccessDeniedException(jetbrains.buildServer.serverSide.auth.AccessDeniedException) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) DuplicateExternalIdException(jetbrains.buildServer.serverSide.identifiers.DuplicateExternalIdException) Nullable(org.jetbrains.annotations.Nullable) ApiOperation(io.swagger.annotations.ApiOperation)

Example 22 with BadRequestException

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

the class ProjectRequest method setProjectsOrder.

/**
 * Put empty collection to remove custom ordering
 */
@PUT
@Path("/{projectLocator}/order/projects")
@Consumes({ "application/xml", "application/json" })
@Produces({ "application/xml", "application/json" })
@ApiOperation(value = "Update custom ordering of subprojects of the matching project.", nickname = "setSubprojectsOrder")
public Projects setProjectsOrder(@ApiParam(format = LocatorName.PROJECT) @PathParam("projectLocator") String projectLocator, Projects projects, @QueryParam("field") String fields) {
    SProject project = myProjectFinder.getItem(projectLocator);
    LinkedHashSet<String> ids = new LinkedHashSet<>();
    if (projects.projects != null) {
        for (Project postedProject : projects.projects) {
            final String locatorFromPosted = postedProject.getLocatorFromPosted();
            List<SProject> items = myProjectFinder.getItems(project, locatorFromPosted).myEntries;
            if (items.isEmpty()) {
                throw new BadRequestException("No direct sub-projects in project found by locator '" + locatorFromPosted + "'");
            }
            for (SProject item : items) {
                ids.add(item.getProjectId());
            }
        }
    }
    ((ProjectEx) project).setOwnProjectsOrder(new ArrayList<>(ids));
    return new Projects(((ProjectEx) project).getOwnProjectsOrder(), null, new Fields(fields), myBeanContext);
}
Also used : ProjectEx(jetbrains.buildServer.serverSide.impl.ProjectEx) Fields(jetbrains.buildServer.server.rest.model.Fields) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) ApiOperation(io.swagger.annotations.ApiOperation)

Example 23 with BadRequestException

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

the class ServerRequest method addLicenseKeys.

/**
 * Adds newline-delimited list of license keys to the server or returns textual description is there are not valid keys
 */
@POST
@Path(LICENSING_KEYS)
@Consumes({ "text/plain" })
@Produces({ "application/xml", "application/json" })
@ApiOperation(value = "Add license keys.", nickname = "addLicenseKeys")
public LicenseKeyEntities addLicenseKeys(final String licenseKeyCodes, @QueryParam("fields") String fields) {
    myDataProvider.checkGlobalPermission(Permission.CHANGE_SERVER_SETTINGS);
    LicenseKeysManager licenseKeysManager = myBeanContext.getSingletonService(BuildServerEx.class).getLicenseKeysManager();
    List<String> keysToAdd = Stream.of(DELIMITERS.split(licenseKeyCodes)).map(String::trim).filter(s -> !StringUtil.isEmpty(s)).collect(Collectors.toList());
    // TeamCity API issue: why return good keys?
    List<LicenseKey> validatedKeys = licenseKeysManager.validateKeys(keysToAdd);
    if (!validatedKeys.isEmpty()) {
        // is there a way to return entity with not 200 result code???
        StringBuilder resultMessage = new StringBuilder();
        resultMessage.append("Invalid keys:\n");
        boolean invalidKeysFound = false;
        for (LicenseKey validatedKey : validatedKeys) {
            invalidKeysFound = invalidKeysFound || !validatedKey.isValid();
            String validateError = validatedKey.getValidateError();
            resultMessage.append(validatedKey.getKey()).append(" - ").append(validateError).append("\n");
        }
        if (invalidKeysFound) {
            throw new BadRequestException(resultMessage.toString());
        }
    }
    return new LicenseKeyEntities(licenseKeysManager.addKeys(keysToAdd), null, null, new Fields(fields), myBeanContext);
}
Also used : WebUtil(jetbrains.buildServer.web.util.WebUtil) DataProvider(jetbrains.buildServer.server.rest.data.DataProvider) Fields(jetbrains.buildServer.server.rest.model.Fields) ServerMetricsReader(jetbrains.buildServer.metrics.ServerMetricsReader) Loggers(jetbrains.buildServer.log.Loggers) Date(java.util.Date) Server(jetbrains.buildServer.server.rest.model.server.Server) MaintenanceProcessAlreadyRunningException(jetbrains.buildServer.serverSide.maintenance.MaintenanceProcessAlreadyRunningException) Metrics(jetbrains.buildServer.server.rest.model.metrics.Metrics) SimpleDateFormat(java.text.SimpleDateFormat) LicenseKeyEntities(jetbrains.buildServer.server.rest.model.server.LicenseKeyEntities) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) Element(jetbrains.buildServer.util.browser.Element) ApiOperation(io.swagger.annotations.ApiOperation) FileUtil(jetbrains.buildServer.util.FileUtil) HttpServletRequest(javax.servlet.http.HttpServletRequest) BackupProcessManager(jetbrains.buildServer.serverSide.maintenance.BackupProcessManager) StringUtil(jetbrains.buildServer.util.StringUtil) Api(io.swagger.annotations.Api) PluginInfos(jetbrains.buildServer.server.rest.model.plugin.PluginInfos) LicensingData(jetbrains.buildServer.server.rest.model.server.LicensingData) PermissionChecker(jetbrains.buildServer.server.rest.data.PermissionChecker) Context(javax.ws.rs.core.Context) LicenseKeyEntity(jetbrains.buildServer.server.rest.model.server.LicenseKeyEntity) ServiceLocator(jetbrains.buildServer.ServiceLocator) jetbrains.buildServer.serverSide(jetbrains.buildServer.serverSide) ApiUrlBuilder(jetbrains.buildServer.server.rest.ApiUrlBuilder) BackupConfig(jetbrains.buildServer.serverSide.maintenance.BackupConfig) Collectors(java.util.stream.Collectors) BeanFactory(jetbrains.buildServer.server.rest.util.BeanFactory) File(java.io.File) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) Stream(java.util.stream.Stream) BuildArtifactsFinder(jetbrains.buildServer.server.rest.data.BuildArtifactsFinder) InvalidStateException(jetbrains.buildServer.server.rest.errors.InvalidStateException) javax.ws.rs(javax.ws.rs) Util(jetbrains.buildServer.server.rest.model.Util) Permission(jetbrains.buildServer.serverSide.auth.Permission) FileSecurityUtil(jetbrains.buildServer.controllers.FileSecurityUtil) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) Pattern(java.util.regex.Pattern) BeanContext(jetbrains.buildServer.server.rest.util.BeanContext) NotNull(org.jetbrains.annotations.NotNull) BackupProcess(jetbrains.buildServer.serverSide.maintenance.BackupProcess) Fields(jetbrains.buildServer.server.rest.model.Fields) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) LicenseKeyEntities(jetbrains.buildServer.server.rest.model.server.LicenseKeyEntities) ApiOperation(io.swagger.annotations.ApiOperation)

Example 24 with BadRequestException

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

the class VcsRootInstanceRequest method scheduleCheckingForChanges.

@POST
@Path("/commitHookNotification")
@Produces({ "text/plain" })
@ApiOperation(value = "Send the commit hook notification.", nickname = "triggerCommitHookNotification")
public Response scheduleCheckingForChanges(@ApiParam(format = LocatorName.VCS_ROOT_INSTANCE) @QueryParam("locator") final String vcsRootInstancesLocator, @QueryParam("okOnNothingFound") final Boolean okOnNothingFound, @Context @NotNull final BeanContext beanContext) {
    if (StringUtil.isEmpty(vcsRootInstancesLocator)) {
        throw new BadRequestException("No 'locator' parameter provided, should be not empty VCS root instances locator");
    }
    Date requestStartTime = new Date();
    PagedSearchResult<jetbrains.buildServer.vcs.VcsRootInstance> vcsRootInstances = null;
    boolean nothingFound;
    try {
        vcsRootInstances = myVcsRootInstanceFinder.getItems(vcsRootInstancesLocator);
        nothingFound = vcsRootInstances.myEntries.isEmpty();
    } catch (NotFoundException e) {
        nothingFound = true;
    }
    if (nothingFound) {
        Response.ResponseBuilder responseBuilder;
        if (okOnNothingFound != null && okOnNothingFound) {
            responseBuilder = Response.status(Response.Status.OK);
        } else {
            responseBuilder = Response.status(Response.Status.NOT_FOUND);
        }
        return responseBuilder.entity("No VCS roots are found for locator '" + vcsRootInstancesLocator + "' with current user " + myBeanContext.getSingletonService(PermissionChecker.class).getCurrentUserDescription() + ". Check locator and permissions using '" + API_VCS_ROOT_INSTANCES_URL + "?locator=" + Locator.HELP_DIMENSION + "' URL.").build();
    }
    myDataProvider.getChangesCheckingService().forceCheckingFor(vcsRootInstances.myEntries, OperationRequestor.COMMIT_HOOK);
    StringBuilder okMessage = new StringBuilder();
    okMessage.append("Scheduled checking for changes for");
    if (vcsRootInstances.isNextPageAvailable()) {
        okMessage.append(" first ").append(vcsRootInstances.myActualCount).append(" VCS roots.");
        if (vcsRootInstances.myCount != null && vcsRootInstances.myActualCount >= vcsRootInstances.myCount) {
            okMessage.append(" You can add '" + PagerData.COUNT + ":X' to cover more roots.");
        }
        if (vcsRootInstances.myLookupLimit != null && vcsRootInstances.myLookupLimitReached) {
            okMessage.append(" You can add '" + FinderImpl.DIMENSION_LOOKUP_LIMIT + ":X' to cover more roots.");
        }
    } else {
        okMessage.append(" ").append(vcsRootInstances.myEntries.size()).append(" VCS roots.");
    }
    // format supported by TimeWithPrecision, can later be used in filtering
    okMessage.append(" (Server time: ").append(ISODateTimeFormat.basicDateTime().print(requestStartTime.getTime())).append(")");
    // can also add "in XX projects"
    return Response.status(Response.Status.ACCEPTED).entity(okMessage.toString()).build();
}
Also used : Response(javax.ws.rs.core.Response) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) Date(java.util.Date) VcsRootInstance(jetbrains.buildServer.server.rest.model.change.VcsRootInstance) ApiOperation(io.swagger.annotations.ApiOperation)

Example 25 with BadRequestException

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

the class UserRequest method putUserProperty.

@PUT
@Path("/{userLocator}/properties/{name}")
@Consumes("text/plain")
@Produces("text/plain")
@ApiOperation(value = "Update a property of the matching user.", nickname = "setUserProperty")
public String putUserProperty(@ApiParam(format = LocatorName.USER) @PathParam("userLocator") String userLocator, @PathParam("name") String name, String newValue) {
    SUser user = myUserFinder.getItem(userLocator, true);
    if (StringUtil.isEmpty(name)) {
        throw new BadRequestException("Property name cannot be empty.");
    }
    user.setUserProperty(new SimplePropertyKey(name), newValue);
    return BuildTypeUtil.getParameter(name, User.getProperties(myUserFinder.getItem(userLocator, true)), false, true, myBeanContext.getServiceLocator());
}
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