org.eclipse.che.api.core.ConflictException Java Examples

The following examples show how to use org.eclipse.che.api.core.ConflictException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PermissionsService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@POST
@Consumes(APPLICATION_JSON)
@ApiOperation("Store given permissions")
@ApiResponses({
  @ApiResponse(code = 200, message = "The permissions successfully stored"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 404, message = "Domain of permissions is not supported"),
  @ApiResponse(
      code = 409,
      message = "New permissions removes last 'setPermissions' of given instance"),
  @ApiResponse(
      code = 409,
      message = "Given domain requires non nullable value for instance but it is null"),
  @ApiResponse(code = 500, message = "Internal server error occurred during permissions storing")
})
public void storePermissions(
    @ApiParam(value = "The permissions to store", required = true) PermissionsDto permissionsDto)
    throws ServerException, BadRequestException, ConflictException, NotFoundException {
  checkArgument(permissionsDto != null, "Permissions descriptor required");
  checkArgument(!isNullOrEmpty(permissionsDto.getUserId()), "User required");
  checkArgument(!isNullOrEmpty(permissionsDto.getDomainId()), "Domain required");
  instanceValidator.validate(permissionsDto.getDomainId(), permissionsDto.getInstanceId());
  checkArgument(!permissionsDto.getActions().isEmpty(), "One or more actions required");

  permissionsManager.storePermission(permissionsDto);
}
 
Example #2
Source File: LdapSynchronizerService.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@POST
@ApiOperation("Forces immediate users/profiles synchronization")
@ApiResponses({
  @ApiResponse(code = 204, message = "Synchronization successfully started"),
  @ApiResponse(
    code = 409,
    message =
        "Failed to perform synchronization because of "
            + "another in-progress synchronization process"
  )
})
public Response sync() throws ConflictException {
  try {
    synchronizer.syncAllAsynchronously();
  } catch (SyncException x) {
    throw new ConflictException(x.getLocalizedMessage());
  }
  return Response.noContent().build();
}
 
Example #3
Source File: JenkinsWebhookManager.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Handle build failed Jenkins event by performing next operations: 1. Generate factory based on
 * factory, configured in Jenkins connector properties, but with given commit as an endpoint. If
 * the factory for given commit is already exist from previous requests, this step will be
 * skipped. 2. Update Jenkins job description with build failed factory url.
 *
 * @param jenkinsEvent {@link JenkinsEventDto} object that contains information about failed
 *     Jenkins build
 * @throws ServerException when error occurs during handling failed job event
 */
public void handleFailedJobEvent(JenkinsEventDto jenkinsEvent) throws ServerException {
  JenkinsConnector jenkinsConnector =
      jenkinsConnectorFactory
          .create(jenkinsEvent.getJenkinsUrl(), jenkinsEvent.getJobName())
          .updateUrlWithCredentials();
  try {
    String commitId = jenkinsConnector.getCommitId(jenkinsEvent.getBuildId());
    String repositoryUrl = jenkinsEvent.getRepositoryUrl();
    Optional<Factory> existingFailedFactory = findExistingFailedFactory(repositoryUrl, commitId);
    Factory failedFactory =
        existingFailedFactory.isPresent()
            ? existingFailedFactory.get()
            : createFailedFactory(jenkinsConnector.getFactoryId(), repositoryUrl, commitId);
    jenkinsConnector.addFailedBuildFactoryLink(
        baseUrl.substring(0, baseUrl.indexOf("/api")) + "/f?id=" + failedFactory.getId());
  } catch (IOException | NotFoundException | ConflictException e) {
    LOG.warn(e.getMessage());
    throw new ServerException(e.getMessage());
  }
}
 
Example #4
Source File: JenkinsWebhookManager.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
private Factory createFailedFactory(String factoryId, String repositoryUrl, String commitId)
    throws ConflictException, ServerException, NotFoundException {
  FactoryImpl factory = (FactoryImpl) factoryManager.getById(factoryId);
  factory.setName(factory.getName() + "_" + commitId);
  factory
      .getWorkspace()
      .getProjects()
      .stream()
      .filter(project -> project.getSource().getLocation().equals(repositoryUrl))
      .forEach(
          project -> {
            Map<String, String> parameters = project.getSource().getParameters();
            parameters.remove("branch");
            parameters.put("commitId", commitId);
          });
  return factoryManager.saveFactory(factory);
}
 
Example #5
Source File: LimitsCheckingWorkspaceManager.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public WorkspaceImpl startWorkspace(
    String workspaceId, @Nullable String envName, @Nullable Map<String, String> options)
    throws NotFoundException, ServerException, ConflictException {
  WorkspaceImpl workspace = this.getWorkspace(workspaceId);
  String accountId = workspace.getAccount().getId();
  WorkspaceConfigImpl config = workspace.getConfig();

  try (@SuppressWarnings("unused")
      Unlocker u = resourcesLocks.lock(accountId)) {
    checkRuntimeResourceAvailability(accountId);
    if (config != null) {
      checkRamResourcesAvailability(accountId, workspace.getNamespace(), config, envName);
    }

    return super.startWorkspace(workspaceId, envName, options);
  }
}
 
Example #6
Source File: SystemRamCheckingWorkspaceManager.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * One of the checks in {@link #checkSystemRamLimitAndPropagateStart(WorkspaceCallback)} is needed
 * to deny starting workspace, if system RAM limit exceeded. This check may be slow because it is
 * based on request to swarm for memory amount allocated on all nodes, but it can't be performed
 * more than specified times at the same time, and the semaphore is used to control that. The
 * semaphore is a trade off between speed and risk to exceed system RAM limit. In the worst case
 * specified number of permits to start workspace can happen at the same time after the actually
 * system limit allows to start only one workspace, all permits will be allowed to start
 * workspace. If more than specified number of permits to start workspace happens, they will wait
 * in a queue. limits.workspace.start.throughput property configures how many permits can be
 * handled at the same time.
 */
@VisibleForTesting
<T extends WorkspaceImpl> T checkSystemRamLimitAndPropagateLimitedThroughputStart(
    WorkspaceCallback<T> callback) throws ServerException, NotFoundException, ConflictException {
  if (startSemaphore == null) {
    return checkSystemRamLimitAndPropagateStart(callback);
  } else {
    try {
      startSemaphore.acquire();
      return checkSystemRamLimitAndPropagateStart(callback);
    } catch (InterruptedException e) {
      currentThread().interrupt();
      throw new ServerException(e.getMessage(), e);
    } finally {
      startSemaphore.release();
    }
  }
}
 
Example #7
Source File: WorkspaceManager.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a workspace out of a devfile.
 *
 * <p>The devfile should have been validated using the {@link
 * DevfileIntegrityValidator#validateDevfile(Devfile)}. This method does rest of the validation
 * and actually creates the workspace.
 *
 * @param devfile the devfile describing the workspace
 * @param namespace workspace name is unique in this namespace
 * @param attributes workspace instance attributes
 * @param contentProvider the content provider to use for resolving content references in the
 *     devfile
 * @return new workspace instance
 * @throws NullPointerException when either {@code config} or {@code namespace} is null
 * @throws NotFoundException when account with given id was not found
 * @throws ConflictException when any conflict occurs (e.g Workspace with such name already exists
 *     for {@code owner})
 * @throws ServerException when any other error occurs
 * @throws ValidationException when incoming configuration or attributes are not valid
 */
@Traced
public WorkspaceImpl createWorkspace(
    Devfile devfile,
    String namespace,
    Map<String, String> attributes,
    FileContentProvider contentProvider)
    throws ServerException, NotFoundException, ConflictException, ValidationException {
  requireNonNull(devfile, "Required non-null devfile");
  requireNonNull(namespace, "Required non-null namespace");
  validator.validateAttributes(attributes);

  devfile = generateNameIfNeeded(devfile);

  try {
    devfileIntegrityValidator.validateContentReferences(devfile, contentProvider);
  } catch (DevfileFormatException e) {
    throw new ValidationException(e.getMessage(), e);
  }

  WorkspaceImpl workspace =
      doCreateWorkspace(devfile, accountManager.getByName(namespace), attributes, false);
  TracingTags.WORKSPACE_ID.set(workspace.getId());
  return workspace;
}
 
Example #8
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@DELETE
@Path("/{id}")
@ApiOperation(
    value = "Removes the workspace",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 204, message = "The workspace successfully removed"),
  @ApiResponse(code = 403, message = "The user does not have access to remove the workspace"),
  @ApiResponse(code = 404, message = "The workspace doesn't exist"),
  @ApiResponse(code = 409, message = "The workspace is not stopped(has runtime)"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public void delete(@ApiParam("The workspace id") @PathParam("id") String id)
    throws BadRequestException, ServerException, NotFoundException, ConflictException,
        ForbiddenException {
  workspaceManager.removeWorkspace(id);
}
 
Example #9
Source File: OrganizationManager.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates new organization.
 *
 * @param newOrganization organization to create
 * @return created organization
 * @throws NullPointerException when {@code organization} is null
 * @throws NotFoundException when parent organization was not found
 * @throws ConflictException when organization with such id/name already exists
 * @throws ConflictException when specified organization name is reserved
 * @throws ServerException when any other error occurs during organization creation
 */
@Transactional(rollbackOn = {RuntimeException.class, ApiException.class})
public Organization create(Organization newOrganization)
    throws NotFoundException, ConflictException, ServerException {
  requireNonNull(newOrganization, "Required non-null organization");
  requireNonNull(newOrganization.getName(), "Required non-null organization name");

  String qualifiedName;
  if (newOrganization.getParent() != null) {
    final Organization parent = getById(newOrganization.getParent());
    qualifiedName = parent.getQualifiedName() + "/" + newOrganization.getName();
  } else {
    qualifiedName = newOrganization.getName();
  }
  checkNameReservation(qualifiedName);

  final OrganizationImpl organization =
      new OrganizationImpl(
          NameGenerator.generate("organization", 16), qualifiedName, newOrganization.getParent());
  organizationDao.create(organization);
  addFirstMember(organization);
  eventService.publish(new OrganizationPersistedEvent(organization)).propagateException();
  return organization;
}
 
Example #10
Source File: AuditManager.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates file with audit report in plain/text format. The audit report contains information
 * about license, users and their workspaces.
 *
 * @return path of the audit report file
 * @throws ServerException if an error occurs
 * @throws ConflictException if generating report is already in progress
 */
public Path generateAuditReport() throws ServerException, ConflictException {
  if (!inProgress.compareAndSet(false, true)) {
    throw new ConflictException("Generating report is already in progress");
  }

  Path auditReport = null;
  try {
    auditReport = createEmptyAuditReportFile();
    printSystemInfo(auditReport);
    printAllUsersInfo(auditReport);
  } catch (Exception exception) {
    if (auditReport != null) {
      deleteReportDirectory(auditReport);
    }
    LOG.error(exception.getMessage(), exception);
    throw new ServerException(exception.getMessage(), exception);
  } finally {
    inProgress.set(false);
  }

  return auditReport;
}
 
Example #11
Source File: PermissionsManagerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(
    expectedExceptions = ConflictException.class,
    expectedExceptionsMessageRegExp =
        "Can't edit permissions because there is not any another user with permission 'setPermissions'")
public void shouldNotStorePermissionsWhenItRemoveLastSetPermissions() throws Exception {
  final TestPermissionsImpl foreignPermissions =
      new TestPermissionsImpl("user1", "test", "test123", singletonList("read"));
  final TestPermissionsImpl ownPermissions =
      new TestPermissionsImpl("user", "test", "test123", asList("read", "setPermissions"));

  when(permissionsDao.exists("user", "test123", SET_PERMISSIONS)).thenReturn(true);
  doReturn(new Page<>(singletonList(foreignPermissions), 0, 1, 2))
      .doReturn(new Page<>(singletonList(ownPermissions), 1, 1, 2))
      .when(permissionsDao)
      .getByInstance(nullable(String.class), nullable(Integer.class), nullable(Long.class));

  permissionsManager.storePermission(
      new TestPermissionsImpl("user", "test", "test123", singletonList("delete")));
}
 
Example #12
Source File: GetPermissionsFilter.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void filter(GenericResourceMethod genericResourceMethod, Object[] arguments)
    throws BadRequestException, NotFoundException, ConflictException, ForbiddenException,
        ServerException {

  final String methodName = genericResourceMethod.getMethod().getName();
  if (methodName.equals("getUsersPermissions")) {
    instanceValidator.validate(domain, instance);
    if (superPrivilegesChecker.isPrivilegedToManagePermissions(domain)) {
      return;
    }
    final String userId = EnvironmentContext.getCurrent().getSubject().getUserId();
    try {
      permissionsManager.get(userId, domain, instance);
      // user should have ability to see another users' permissions if he has any permission there
    } catch (NotFoundException e) {
      throw new ForbiddenException("User is not authorized to perform this operation");
    }
  }
}
 
Example #13
Source File: RemoteServiceDescriptor.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
public ServiceDescriptor getServiceDescriptor() throws IOException, ServerException {
  if (serviceDescriptor == null) {
    synchronized (this) {
      if (serviceDescriptor == null) {
        try {
          serviceDescriptor =
              requestFactory
                  .fromUrl(baseUrl)
                  .useOptionsMethod()
                  .request()
                  .as(getServiceDescriptorClass(), null);
        } catch (NotFoundException
            | ConflictException
            | UnauthorizedException
            | BadRequestException
            | ForbiddenException e) {
          throw new ServerException(e.getServiceError());
        }
      }
    }
  }
  return serviceDescriptor;
}
 
Example #14
Source File: PermissionsManager.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void checkActionsSupporting(AbstractPermissionsDomain<?> domain, List<String> actions)
    throws ConflictException {
  final Set<String> allowedActions = new HashSet<>(domain.getAllowedActions());
  final Set<String> unsupportedActions =
      actions
          .stream()
          .filter(action -> !allowedActions.contains(action))
          .collect(Collectors.toSet());
  if (!unsupportedActions.isEmpty()) {
    throw new ConflictException(
        "Domain with id '"
            + domain.getId()
            + "' doesn't support following action(s): "
            + unsupportedActions.stream().collect(Collectors.joining(", ")));
  }
}
 
Example #15
Source File: PermissionsManager.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private boolean userHasLastSetPermissions(
    PermissionsDao<? extends AbstractPermissions> storage, String userId, String instanceId)
    throws ServerException, ConflictException, NotFoundException {
  if (!storage.exists(userId, instanceId, SET_PERMISSIONS)) {
    return false;
  }

  for (AbstractPermissions permissions :
      Pages.iterateLazily(
          (maxItems, skipCount) -> storage.getByInstance(instanceId, maxItems, skipCount))) {
    if (!permissions.getUserId().equals(userId)
        && permissions.getActions().contains(SET_PERMISSIONS)) {
      return false;
    }
  }
  return true;
}
 
Example #16
Source File: WorkspaceManager.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void handleStartupSuccess(String workspaceId) {
  try {
    // we need to reload the workspace because the runtimes might have updated it
    WorkspaceImpl workspace = getWorkspace(workspaceId);

    workspace.getAttributes().remove(STOPPED_ATTRIBUTE_NAME);
    workspace.getAttributes().remove(STOPPED_ABNORMALLY_ATTRIBUTE_NAME);
    workspace.getAttributes().remove(ERROR_MESSAGE_ATTRIBUTE_NAME);

    workspaceDao.update(workspace);
  } catch (NotFoundException | ServerException | ConflictException e) {
    LOG.warn(
        String.format(
            "Cannot clear error status status of the workspace %s. Error is: %s",
            workspaceId, e.getMessage()));
  }
}
 
Example #17
Source File: UserDaoTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(expectedExceptions = ConflictException.class)
public void shouldThrowConflictExceptionWhenCreatingUserWithExistingAliases() throws Exception {
  final UserImpl newUser =
      new UserImpl(
          "user123", "[email protected]", "user_name", "password", users[0].getAliases());

  userDao.create(newUser);
}
 
Example #18
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@POST
@Path("/{id}/environment")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Add a new environment to the workspace",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 200, message = "The workspace successfully updated"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 403, message = "The user does not have access to add the environment"),
  @ApiResponse(code = 404, message = "The workspace not found"),
  @ApiResponse(code = 409, message = "Environment with such name already exists"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public WorkspaceDto addEnvironment(
    @ApiParam("The workspace id") @PathParam("id") String id,
    @ApiParam(value = "The new environment", required = true) EnvironmentDto newEnvironment,
    @ApiParam(value = "The name of the environment", required = true) @QueryParam("name")
        String envName)
    throws ServerException, BadRequestException, NotFoundException, ConflictException,
        ForbiddenException {
  requiredNotNull(newEnvironment, "New environment");
  requiredNotNull(envName, "New environment name");
  relativizeRecipeLinks(newEnvironment);
  WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
  if (workspace.getConfig() == null) {
    throw new ConflictException(
        "This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
  }
  workspace.getConfig().getEnvironments().put(envName, new EnvironmentImpl(newEnvironment));
  return asDtoWithLinksAndToken(doUpdate(id, workspace));
}
 
Example #19
Source File: WorkspaceManager.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Removes workspace with specified identifier.
 *
 * <p>
 *
 * <p>Does not remove the workspace if it has the runtime, throws {@link ConflictException} in
 * this case. Won't throw any exception if workspace doesn't exist.
 *
 * @param workspaceId workspace id to remove workspace
 * @throws ConflictException when workspace has runtime
 * @throws ServerException when any server error occurs
 * @throws NullPointerException when {@code workspaceId} is null
 */
@Traced
public void removeWorkspace(String workspaceId) throws ConflictException, ServerException {
  TracingTags.WORKSPACE_ID.set(workspaceId);

  requireNonNull(workspaceId, "Required non-null workspace id");
  if (runtimes.hasRuntime(workspaceId)) {
    throw new ConflictException(
        format("The workspace '%s' is currently running and cannot be removed.", workspaceId));
  }

  Optional<WorkspaceImpl> workspaceOpt = workspaceDao.remove(workspaceId);

  LOG.info("Workspace '{}' removed by user '{}'", workspaceId, sessionUserNameOrUndefined());
}
 
Example #20
Source File: KeycloakUserManager.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Transactional(rollbackOn = {RuntimeException.class, ApiException.class})
protected void doCreate(UserImpl user, boolean isTemporary)
    throws ConflictException, ServerException {
  userDao.create(user);
  eventService.publish(new PostUserPersistedEvent(new UserImpl(user))).propagateException();
  preferencesDao.setPreferences(
      user.getId(),
      ImmutableMap.of(
          "temporary", Boolean.toString(isTemporary),
          "codenvy:created", Long.toString(currentTimeMillis())));
}
 
Example #21
Source File: UserDaoTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(expectedExceptions = ConflictException.class)
public void shouldThrowConflictExceptionWhenCreatingUserWithExistingName() throws Exception {
  final UserImpl newUser =
      new UserImpl(
          "user123",
          "[email protected]",
          users[0].getName(),
          "password",
          asList("google:user123", "github:user123"));

  userDao.create(newUser);
}
 
Example #22
Source File: OrganizationDaoTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(expectedExceptions = ConflictException.class)
public void shouldThrowConflictExceptionOnCreatingOrganizationWithExistingId() throws Exception {
  final OrganizationImpl organization =
      new OrganizationImpl(organizations[0].getId(), "Test", null);

  organizationDao.create(organization);

  assertEquals(organizationDao.getById(organization.getId()), organization);
}
 
Example #23
Source File: JpaOrganizationDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void create(OrganizationImpl organization) throws ServerException, ConflictException {
  requireNonNull(organization, "Required non-null organization");
  try {
    doCreate(organization);
  } catch (DuplicateKeyException e) {
    throw new ConflictException("Organization with such id or name already exists");
  } catch (RuntimeException x) {
    throw new ServerException(x.getLocalizedMessage(), x);
  }
}
 
Example #24
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@PUT
@Path("/{id}/project/{path:.*}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Update the workspace project by replacing it with a new one",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 200, message = "The project successfully updated"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 403, message = "The user does not have access to update the project"),
  @ApiResponse(code = 404, message = "The workspace or the project not found"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public WorkspaceDto updateProject(
    @ApiParam("The workspace id") @PathParam("id") String id,
    @ApiParam("The path to the project") @PathParam("path") String path,
    @ApiParam(value = "The project update", required = true) ProjectConfigDto update)
    throws ServerException, BadRequestException, NotFoundException, ConflictException,
        ForbiddenException {
  requiredNotNull(update, "Project config");
  final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
  if (workspace.getConfig() == null) {
    throw new ConflictException(
        "This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
  }
  final List<ProjectConfigImpl> projects = workspace.getConfig().getProjects();
  final String normalizedPath = path.startsWith("/") ? path : '/' + path;
  if (!projects.removeIf(project -> project.getPath().equals(normalizedPath))) {
    throw new NotFoundException(
        format("Workspace '%s' doesn't contain project with path '%s'", id, normalizedPath));
  }
  projects.add(new ProjectConfigImpl(update));
  return asDtoWithLinksAndToken(doUpdate(id, workspace));
}
 
Example #25
Source File: AuthorizedSubject.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean hasPermission(String domain, String instance, String action) {
  try {
    return permissionChecker.hasPermission(getUserId(), domain, instance, action);
  } catch (NotFoundException nfe) {
    return false;
  } catch (ServerException | ConflictException e) {
    LOG.error(
        format(
            "Can't check permissions for user '%s' and instance '%s' of domain '%s'",
            getUserId(), domain, instance),
        e);
    throw new RuntimeException("Can't check user's permissions", e);
  }
}
 
Example #26
Source File: PermissionsManagerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(
    expectedExceptions = ConflictException.class,
    expectedExceptionsMessageRegExp =
        "Domain with id 'test' doesn't support following action\\(s\\): unsupported")
public void
    shouldThrowConflictExceptionOnActionSupportingCheckingWhenListContainsUnsupportedAction()
        throws Exception {
  permissionsManager.checkActionsSupporting("test", Arrays.asList("write", "use", "unsupported"));
}
 
Example #27
Source File: WorkspaceManagerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(expectedExceptions = ConflictException.class)
public void throwsExceptionWhenRemoveNotStoppedWorkspace() throws Exception {
  final WorkspaceImpl workspace = createAndMockWorkspace();
  when(runtimes.hasRuntime(workspace.getId())).thenReturn(true);

  workspaceManager.removeWorkspace(workspace.getId());
}
 
Example #28
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@DELETE
@Path("/{id}/project/{path:.*}")
@ApiOperation(
    value = "Remove the project from the workspace",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 204, message = "The project successfully removed"),
  @ApiResponse(code = 403, message = "The user does not have access remove the project"),
  @ApiResponse(code = 404, message = "The workspace not found"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public void deleteProject(
    @ApiParam("The workspace id") @PathParam("id") String id,
    @ApiParam("The name of the project to remove") @PathParam("path") String path)
    throws ServerException, BadRequestException, NotFoundException, ConflictException,
        ForbiddenException {
  final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
  if (workspace.getConfig() == null) {
    throw new ConflictException(
        "This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
  }
  final String normalizedPath = path.startsWith("/") ? path : '/' + path;
  if (workspace
      .getConfig()
      .getProjects()
      .removeIf(project -> project.getPath().equals(normalizedPath))) {
    doUpdate(id, workspace);
  }
}
 
Example #29
Source File: PermissionsService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@Path("/{domain}/all")
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Get permissions which are related to specified domain and instance",
    response = PermissionsDto.class,
    responseContainer = "List")
@ApiResponses({
  @ApiResponse(code = 200, message = "The permissions successfully fetched"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 404, message = "Specified domain is unsupported"),
  @ApiResponse(
      code = 409,
      message = "Given domain requires non nullable value for instance but it is null"),
  @ApiResponse(code = 500, message = "Internal server error occurred during permissions fetching")
})
public Response getUsersPermissions(
    @ApiParam(value = "Domain id to retrieve users' permissions") @PathParam("domain")
        String domain,
    @ApiParam(value = "Instance id to retrieve users' permissions") @QueryParam("instance")
        String instance,
    @ApiParam(value = "Max items") @QueryParam("maxItems") @DefaultValue("30") int maxItems,
    @ApiParam(value = "Skip count") @QueryParam("skipCount") @DefaultValue("0") int skipCount)
    throws ServerException, NotFoundException, ConflictException, BadRequestException {
  instanceValidator.validate(domain, instance);
  checkArgument(maxItems >= 0, "The number of items to return can't be negative.");
  checkArgument(skipCount >= 0, "The number of items to skip can't be negative.");

  final Page<AbstractPermissions> permissionsPage =
      permissionsManager.getByInstance(domain, instance, maxItems, skipCount);
  return Response.ok()
      .entity(permissionsPage.getItems(this::toDto))
      .header("Link", createLinkHeader(permissionsPage))
      .build();
}
 
Example #30
Source File: PermissionsService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@Path("/{domain}")
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Get permissions of current user which are related to specified domain and instance",
    response = PermissionsDto.class)
@ApiResponses({
  @ApiResponse(code = 200, message = "The permissions successfully fetched"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 404, message = "Specified domain is unsupported"),
  @ApiResponse(
      code = 404,
      message = "Permissions for current user with specified domain and instance was not found"),
  @ApiResponse(
      code = 409,
      message = "Given domain requires non nullable value for instance but it is null"),
  @ApiResponse(code = 500, message = "Internal server error occurred during permissions fetching")
})
public PermissionsDto getCurrentUsersPermissions(
    @ApiParam(value = "Domain id to retrieve user's permissions") @PathParam("domain")
        String domain,
    @ApiParam(value = "Instance id to retrieve user's permissions") @QueryParam("instance")
        String instance)
    throws BadRequestException, NotFoundException, ConflictException, ServerException {
  instanceValidator.validate(domain, instance);
  return toDto(
      permissionsManager.get(
          EnvironmentContext.getCurrent().getSubject().getUserId(), domain, instance));
}