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

The following examples show how to use org.eclipse.che.api.core.NotFoundException. 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: KeycloakUserManagerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shoudCreateNewUserIfHeIsNotFoundByIdOrEmail() throws Exception {
  // given
  ArgumentCaptor<UserImpl> captor = ArgumentCaptor.forClass(UserImpl.class);
  when(userDao.getById(eq("id"))).thenThrow(NotFoundException.class);
  when(userDao.getByEmail(eq("[email protected]"))).thenThrow(NotFoundException.class);

  // when
  keycloakUserManager.getOrCreateUser("id", "[email protected]", "name");

  // then
  verify(userDao, times(2)).getById(eq("id"));
  verify(userDao).getByEmail(eq("[email protected]"));

  verify(userDao).create((captor.capture()));
  assertEquals("id", captor.getValue().getId());
  assertEquals("[email protected]", captor.getValue().getEmail());
  assertEquals("name", captor.getValue().getName());
}
 
Example #2
Source File: WorkspaceManager.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void handleStartupError(String workspaceId, Throwable t) {
  try {
    // we need to reload the workspace because the runtimes might have updated it
    WorkspaceImpl workspace = getWorkspace(workspaceId);
    workspace
        .getAttributes()
        .put(
            ERROR_MESSAGE_ATTRIBUTE_NAME,
            t instanceof RuntimeException ? t.getCause().getMessage() : t.getMessage());
    workspace.getAttributes().put(STOPPED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis()));
    workspace.getAttributes().put(STOPPED_ABNORMALLY_ATTRIBUTE_NAME, Boolean.toString(true));
    workspaceDao.update(workspace);
  } catch (NotFoundException | ServerException | ConflictException e) {
    LOG.warn(
        String.format(
            "Cannot set error status of the workspace %s. Error is: %s",
            workspaceId, e.getMessage()));
  }
}
 
Example #3
Source File: UserService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@GET
@Path("/find")
@Produces(APPLICATION_JSON)
@GenerateLink(rel = LINK_REL_USER)
@ApiOperation("Get user by email or name")
@ApiResponses({
  @ApiResponse(code = 200, message = "The response contains requested user entity"),
  @ApiResponse(code = 404, message = "User with requested email/name not found"),
  @ApiResponse(code = 500, message = "Impossible to get user due to internal server error")
})
public UserDto find(
    @ApiParam("User email, if it is set then name shouldn't be") @QueryParam("email")
        String email,
    @ApiParam("User name, if is is set then email shouldn't be") @QueryParam("name") String name)
    throws NotFoundException, ServerException, BadRequestException {
  if (email == null && name == null) {
    throw new BadRequestException("Missed user's email or name");
  }
  if (email != null && name != null) {
    throw new BadRequestException(
        "Expected either user's email or name, while both values received");
  }
  final User user = name == null ? userManager.getByEmail(email) : userManager.getByName(name);
  return linksInjector.injectLinks(asDto(user), getServiceContext());
}
 
Example #4
Source File: ForwardActivityFilter.java    From rh-che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void onEvent(WorkspaceStatusEvent event) {
  String workspaceId = event.getWorkspaceId();
  if (WorkspaceStatus.STOPPING.equals(event.getStatus())) {
    try {
      final WorkspaceImpl workspace = workspaceManager.getWorkspace(workspaceId);
      Runtime runtime = workspace.getRuntime();
      if (runtime != null) {
        String userId = runtime.getOwner();
        callWorkspaceAnalyticsEndpoint(
            userId, workspaceId, "/fabric8-che-analytics/stopped", "notify stop", workspace);
      } else {
        LOG.warn(
            "Received stopping event for workspace {}/{} with id {} but runtime is null",
            workspace.getNamespace(),
            workspace.getConfig().getName(),
            workspaceId);
      }
    } catch (NotFoundException | ServerException e) {
      LOG.warn("", e);
      return;
    }
  }
}
 
Example #5
Source File: GetPermissionsFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldRespond403IfUserDoesNotHaveAnyPermissionsForInstance() throws Exception {
  when(permissionsManager.get("user123", "test", "test123")).thenThrow(new NotFoundException(""));

  final Response response =
      given()
          .auth()
          .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD)
          .contentType("application/json")
          .when()
          .get(SECURE_PATH + "/permissions/test/all?instance=test123");

  assertEquals(response.getStatusCode(), 403);
  assertEquals(unwrapError(response), "User is not authorized to perform this operation");
  verifyZeroInteractions(permissionsService);
  verify(instanceValidator).validate("test", "test123");
}
 
Example #6
Source File: JpaUserDao.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Transactional
protected void doUpdate(UserImpl update) throws NotFoundException {
  final EntityManager manager = managerProvider.get();
  final UserImpl user = manager.find(UserImpl.class, update.getId());
  if (user == null) {
    throw new NotFoundException(
        format("Couldn't update user with id '%s' because it doesn't exist", update.getId()));
  }
  final String password = update.getPassword();
  if (password != null) {
    update.setPassword(encryptor.encrypt(password));
  } else {
    update.setPassword(user.getPassword());
  }
  manager.merge(update);
  manager.flush();
}
 
Example #7
Source File: PermissionsService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@GET
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Get all supported domains or only requested if domain parameter specified",
    response = DomainDto.class,
    responseContainer = "List")
@ApiResponses({
  @ApiResponse(code = 200, message = "The domains successfully fetched"),
  @ApiResponse(code = 404, message = "Requested domain is not supported"),
  @ApiResponse(code = 500, message = "Internal server error occurred during domains fetching")
})
public List<DomainDto> getSupportedDomains(
    @ApiParam("Id of requested domain") @QueryParam("domain") String domainId)
    throws NotFoundException {
  if (isNullOrEmpty(domainId)) {
    return permissionsManager.getDomains().stream().map(this::asDto).collect(Collectors.toList());
  } else {
    return singletonList(asDto(permissionsManager.getDomain(domainId)));
  }
}
 
Example #8
Source File: OrganizationService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@GET
@Produces(APPLICATION_JSON)
@Path("/find")
@ApiOperation(value = "Find organization by name", response = OrganizationDto.class)
@ApiResponses({
  @ApiResponse(code = 200, message = "The organization successfully fetched"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 404, message = "The organization with given name was not found"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public OrganizationDto find(
    @ApiParam(value = "Organization name", required = true) @QueryParam("name")
        String organizationName)
    throws NotFoundException, ServerException, BadRequestException {
  checkArgument(organizationName != null, "Missed organization's name");
  return linksInjector.injectLinks(
      asDto(organizationManager.getByName(organizationName)), getServiceContext());
}
 
Example #9
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 #10
Source File: AbstractJpaPermissionsDao.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Transactional
protected Optional<T> doCreate(T permissions) throws ServerException {
  EntityManager manager = managerProvider.get();
  try {
    final T result =
        getEntity(wildcardToNull(permissions.getUserId()), permissions.getInstanceId());
    final T existing =
        getDomain().newInstance(result.getUserId(), result.getInstanceId(), result.getActions());
    result.getActions().clear();
    result.getActions().addAll(permissions.getActions());
    manager.flush();
    return Optional.of(existing);
  } catch (NotFoundException n) {
    manager.persist(permissions);
    manager.flush();
    return Optional.empty();
  }
}
 
Example #11
Source File: WorkspaceServiceTermination.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void stopRunningAndStartingWorkspacesAsync() {
  for (String workspaceId : runtimes.getActive()) {
    WorkspaceStatus status = runtimes.getStatus(workspaceId);
    if (status == WorkspaceStatus.RUNNING || status == WorkspaceStatus.STARTING) {
      try {
        manager.stopWorkspace(workspaceId, Collections.emptyMap());
      } catch (ServerException | ConflictException | NotFoundException x) {
        if (runtimes.hasRuntime(workspaceId)) {
          LOG.error(
              "Couldn't get the workspace '{}' while it's running, the occurred error: '{}'",
              workspaceId,
              x.getMessage());
        }
      }
    }
  }
}
 
Example #12
Source File: WorkspaceRuntimesTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private WorkspaceImpl mockWorkspaceWithDevfile(RuntimeIdentity identity)
    throws NotFoundException, ServerException {
  DevfileImpl devfile = mock(DevfileImpl.class);

  WorkspaceImpl workspace = mock(WorkspaceImpl.class);
  lenient().when(workspace.getDevfile()).thenReturn(devfile);
  lenient().when(workspace.getId()).thenReturn(identity.getWorkspaceId());
  lenient().when(workspace.getAttributes()).thenReturn(new HashMap<>());

  lenient().when(workspaceDao.get(identity.getWorkspaceId())).thenReturn(workspace);

  WorkspaceConfigImpl convertedConfig = mock(WorkspaceConfigImpl.class);
  EnvironmentImpl environment = mockEnvironment();
  lenient()
      .when(convertedConfig.getEnvironments())
      .thenReturn(ImmutableMap.of(identity.getEnvName(), environment));
  lenient().when(devfileConverter.convert(devfile)).thenReturn(convertedConfig);

  return workspace;
}
 
Example #13
Source File: KeycloakEnvironmentInitializationFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldRetrieveTheEmailWhenItIsNotInJwtToken() throws Exception {

  Map<String, Object> claimParams = new HashMap<>();
  claimParams.put("preferred_username", "username");
  Claims claims = new DefaultClaims(claimParams).setSubject("id");
  DefaultJws<Claims> jws = new DefaultJws<>(new DefaultJwsHeader(), claims, "");
  UserImpl user = new UserImpl("id", "[email protected]", "username");
  keycloakSettingsMap.put(KeycloakConstants.USERNAME_CLAIM_SETTING, "preferred_username");
  // given
  when(tokenExtractor.getToken(any(HttpServletRequest.class))).thenReturn("token");
  when(jwtParser.parseClaimsJws(anyString())).thenReturn(jws);
  when(userManager.getById(anyString())).thenThrow(NotFoundException.class);
  when(userManager.getOrCreateUser(anyString(), anyString(), anyString())).thenReturn(user);
  keycloakAttributes.put("email", "[email protected]");

  try {
    // when
    filter.doFilter(request, response, chain);
  } catch (Exception e) {
    e.printStackTrace();
    throw e;
  }

  verify(userManager).getOrCreateUser("id", "[email protected]", "username");
}
 
Example #14
Source File: InviteService.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@POST
@Consumes(APPLICATION_JSON)
@ApiOperation(
  value = "Invite unregistered user by email " + "or update permissions for already invited user",
  notes = "Invited user will receive email notification only on invitation creation"
)
@ApiResponses({
  @ApiResponse(code = 204, message = "The invitation successfully created/updated"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 409, message = "User with specified email is already registered"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public void invite(@ApiParam(value = "The invite to store", required = true) InviteDto inviteDto)
    throws BadRequestException, NotFoundException, ConflictException, ServerException {
  checkArgument(inviteDto != null, "Invite required");
  checkArgument(!isNullOrEmpty(inviteDto.getEmail()), "Email required");
  checkArgument(!isNullOrEmpty(inviteDto.getDomainId()), "Domain id required");
  checkArgument(!isNullOrEmpty(inviteDto.getInstanceId()), "Instance id required");
  checkArgument(!inviteDto.getActions().isEmpty(), "One or more actions required");
  emailValidator.validateUserMail(inviteDto.getEmail());

  inviteManager.store(inviteDto);
}
 
Example #15
Source File: KeycloakServiceClient.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets auth token from given identity provider.
 *
 * @param oauthProvider provider name
 * @return KeycloakTokenResponse token response
 * @throws ForbiddenException when HTTP request was forbidden
 * @throws BadRequestException when HTTP request considered as bad
 * @throws IOException when unable to parse error response
 * @throws NotFoundException when requested URL not found
 * @throws ServerException when other error occurs
 * @throws UnauthorizedException when no token present for user or user not linked to provider
 */
public KeycloakTokenResponse getIdentityProviderToken(String oauthProvider)
    throws ForbiddenException, BadRequestException, IOException, NotFoundException,
        ServerException, UnauthorizedException {
  String url =
      UriBuilder.fromUri(keycloakSettings.get().get(AUTH_SERVER_URL_SETTING))
          .path("/realms/{realm}/broker/{provider}/token")
          .build(keycloakSettings.get().get(REALM_SETTING), oauthProvider)
          .toString();
  try {
    String response = doRequest(url, HttpMethod.GET, null);
    // Successful answer is not a json, but key=value&foo=bar format pairs
    return DtoFactory.getInstance()
        .createDtoFromJson(toJson(response), KeycloakTokenResponse.class);
  } catch (BadRequestException e) {
    if (assotiateUserPattern.matcher(e.getMessage()).matches()) {
      // If user has no link with identity provider yet,
      // we should threat this as unauthorized and send to OAuth login page.
      throw new UnauthorizedException(e.getMessage());
    }
    throw e;
  }
}
 
Example #16
Source File: ProfileService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@DELETE
@Path("/attributes")
@GenerateLink(rel = LINK_REL_CURRENT_PROFILE_ATTRIBUTES)
@Consumes(APPLICATION_JSON)
@ApiOperation(
    value = "Remove profile attributes which names are equal to given",
    notes =
        "If names list is not send, all the attributes will be removed, "
            + "if there are no attributes which names equal to some of the given names, "
            + "then those names are skipped.")
@ApiResponses({
  @ApiResponse(code = 204, message = "Attributes successfully removed"),
  @ApiResponse(code = 500, message = "Couldn't remove attributes due to internal server error")
})
public void removeAttributes(
    @ApiParam("The names of the profile attributes to remove") List<String> names)
    throws NotFoundException, ServerException {
  final Profile profile = profileManager.getById(userId());
  final Map<String, String> attributes = profile.getAttributes();
  if (names == null) {
    attributes.clear();
  } else {
    names.forEach(attributes::remove);
  }
  profileManager.update(profile);
}
 
Example #17
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@DELETE
@Path("/{id}/environment/{name}")
@ApiOperation(
    value = "Remove the environment from the workspace",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 204, message = "The environment successfully removed"),
  @ApiResponse(code = 403, message = "The user does not have access remove the environment"),
  @ApiResponse(code = 404, message = "The workspace not found"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public void deleteEnvironment(
    @ApiParam("The workspace id") @PathParam("id") String id,
    @ApiParam("The name of the environment") @PathParam("name") String envName)
    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.");
  }
  if (workspace.getConfig().getEnvironments().remove(envName) != null) {
    doUpdate(id, workspace);
  }
}
 
Example #18
Source File: KeycloakUserManagerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shoudRecreateUserIfHeIsntFoundByIdButFoundByEmail() throws Exception {
  // given
  UserImpl newUserImpl = new UserImpl("id", "[email protected]", "name");
  UserImpl oldUserImpl = new UserImpl("oldId", "[email protected]", "name");
  ArgumentCaptor<UserImpl> captor = ArgumentCaptor.forClass(UserImpl.class);
  when(userDao.getById(eq("id"))).thenThrow(NotFoundException.class);
  when(userDao.getByEmail(eq("[email protected]"))).thenReturn(oldUserImpl);

  // when
  keycloakUserManager.getOrCreateUser("id", "[email protected]", "name");

  // then
  verify(userDao, times(2)).getById(eq("id"));
  verify(userDao).getByEmail(eq("[email protected]"));

  verify(userDao).remove(eq(oldUserImpl.getId()));

  verify(userDao).create((captor.capture()));
  assertEquals(newUserImpl.getId(), captor.getValue().getId());
  assertEquals(newUserImpl.getEmail(), captor.getValue().getEmail());
  assertEquals(newUserImpl.getName(), captor.getValue().getName());
}
 
Example #19
Source File: HostedWorkspaceActivityManager.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected long getIdleTimeout(String workspaceId) throws NotFoundException, ServerException {
  WorkspaceImpl workspace = workspaceManager.getWorkspace(workspaceId);
  Account account = accountManager.getByName(workspace.getNamespace());
  List<? extends Resource> availableResources =
      resourceUsageManager.getAvailableResources(account.getId());
  Optional<? extends Resource> timeoutOpt =
      availableResources
          .stream()
          .filter(resource -> TimeoutResourceType.ID.equals(resource.getType()))
          .findAny();

  if (timeoutOpt.isPresent()) {
    return timeoutOpt.get().getAmount() * 60 * 1000;
  } else {
    return -1;
  }
}
 
Example #20
Source File: HostedMachineProviderImpl.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected String getUserToken(String wsId) {
  String userToken = null;
  try {
    userToken =
        tokenRegistry.getOrCreateToken(
            EnvironmentContext.getCurrent().getSubject().getUserId(), wsId);
  } catch (NotFoundException ignore) {
  }
  return MoreObjects.firstNonNull(userToken, "");
}
 
Example #21
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@PUT
@Path("/{id}/environment/{name}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Update the workspace environment by replacing it with a new one",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 200, message = "The environment 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 environment"),
  @ApiResponse(code = 404, message = "The workspace or the environment not found"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public WorkspaceDto updateEnvironment(
    @ApiParam("The workspace id") @PathParam("id") String id,
    @ApiParam("The name of the environment") @PathParam("name") String envName,
    @ApiParam(value = "The environment update", required = true) EnvironmentDto update)
    throws ServerException, BadRequestException, NotFoundException, ConflictException,
        ForbiddenException {
  requiredNotNull(update, "Environment description");
  relativizeRecipeLinks(update);
  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.");
  }
  EnvironmentImpl previous =
      workspace.getConfig().getEnvironments().put(envName, new EnvironmentImpl(update));
  if (previous == null) {
    throw new NotFoundException(
        format("Workspace '%s' doesn't contain environment '%s'", id, envName));
  }
  return asDtoWithLinksAndToken(doUpdate(id, workspace));
}
 
Example #22
Source File: LimitsCheckingWorkspaceManager.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@Traced
public WorkspaceImpl createWorkspace(
    WorkspaceConfig config, String namespace, @Nullable Map<String, String> attributes)
    throws ServerException, ConflictException, NotFoundException, ValidationException {
  checkMaxEnvironmentRam(config);
  String accountId = accountManager.getByName(namespace).getId();
  try (@SuppressWarnings("unused")
      Unlocker u = resourcesLocks.lock(accountId)) {
    checkWorkspaceResourceAvailability(accountId);

    return super.createWorkspace(config, namespace, attributes);
  }
}
 
Example #23
Source File: AbstractJpaPermissionsDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void remove(String userId, String instanceId) throws ServerException, NotFoundException {
  requireNonNull(instanceId, "Instance identifier required");
  requireNonNull(userId, "User identifier required");
  try {
    doRemove(userId, instanceId);
  } catch (RuntimeException x) {
    throw new ServerException(x.getLocalizedMessage(), x);
  }
}
 
Example #24
Source File: JpaEntitiesCascadeRemovalTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private static <T> T notFoundToNull(Callable<T> action) throws Exception {
  try {
    return action.call();
  } catch (NotFoundException x) {
    return null;
  }
}
 
Example #25
Source File: FactoryPermissionsFilter.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void checkSubjectIsCreator(String factoryId, Subject currentSubject, String action)
    throws NotFoundException, ServerException, ForbiddenException {
  Factory factory = factoryManager.getById(factoryId);
  String creatorId = factory.getCreator().getUserId();
  if (!creatorId.equals(currentSubject.getUserId())) {
    throw new ForbiddenException("It is not allowed to " + action + " foreign factory");
  }
}
 
Example #26
Source File: AbstractJpaPermissionsDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Transactional
protected void doRemove(String userId, String instanceId)
    throws ServerException, NotFoundException {
  final T entity = getEntity(wildcardToNull(userId), instanceId);
  EntityManager manager = managerProvider.get();
  manager.remove(entity);
  manager.flush();
}
 
Example #27
Source File: WorkspaceRuntimesTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(
    expectedExceptions = ServerException.class,
    expectedExceptionsMessageRegExp =
        "Workspace configuration is missing for the runtime 'workspace123:my-env'. Runtime won't be recovered")
public void runtimeIsNotRecoveredIfNoWorkspaceFound() throws Exception {
  RuntimeIdentity identity =
      new RuntimeIdentityImpl("workspace123", "my-env", "myId", "infraNamespace");
  when(workspaceDao.get(identity.getWorkspaceId())).thenThrow(new NotFoundException("no!"));

  // try recover
  runtimes.recoverOne(infrastructure, identity);

  assertFalse(runtimes.hasRuntime(identity.getWorkspaceId()));
}
 
Example #28
Source File: PasswordServiceTest.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void shouldSetResponseStatus404IfUserIsNotRegistered() throws Exception {
  doThrow(NotFoundException.class).when(userManager).getByEmail(eq(USER_EMAIL));

  Response response =
      given().pathParam("username", USER_EMAIL).when().post(SERVICE_PATH + "/recover/{username}");

  assertEquals(response.statusCode(), 404);
  assertEquals(
      unwrapDto(response, ServiceError.class).getMessage(),
      "User " + USER_EMAIL + " is not registered in the system.");
  verifyZeroInteractions(mailSender);
  verifyZeroInteractions(recoveryStorage);
}
 
Example #29
Source File: JpaUserDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@Transactional
public UserImpl getById(String id) throws NotFoundException, ServerException {
  requireNonNull(id, "Required non-null id");
  try {
    final UserImpl user = managerProvider.get().find(UserImpl.class, id);
    if (user == null) {
      throw new NotFoundException(format("User with id '%s' doesn't exist", id));
    }
    return erasePassword(user);
  } catch (RuntimeException x) {
    throw new ServerException(x.getLocalizedMessage(), x);
  }
}
 
Example #30
Source File: KeycloakUserManager.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Optional<User> getUserByEmail(String email) throws ServerException {
  try {
    return Optional.of(getByEmail(email));
  } catch (NotFoundException e) {
    return Optional.empty();
  }
}