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);
}
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);
}
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);
}
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();
}
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());
}
Aggregations