store(WorkerImpl worker) throws ServerException;
-
- /**
- * Gets worker by user and workspace
- *
- * @param workspaceId workspace identifier
- * @param userId user identifier
- * @return worker instance, never null
- * @throws NullPointerException when {@code workspace} or {@code user} is null
- * @throws NotFoundException when worker with given {@code workspace} and {@code user} was not
- * found
- * @throws ServerException when any other error occurs during worker fetching
- */
- WorkerImpl getWorker(String workspaceId, String userId) throws ServerException, NotFoundException;
-
- /**
- * Removes worker
- *
- * Doesn't throw an exception when worker with given {@code workspace} and {@code user} does
- * not exist
- *
- * @param workspaceId workspace identifier
- * @param userId user identifier
- * @throws NullPointerException when {@code workspace} or {@code user} is null
- * @throws ServerException when any other error occurs during worker removing
- */
- void removeWorker(String workspaceId, String userId) throws ServerException;
-
- /**
- * Gets workers by workspace
- *
- * @param workspaceId workspace identifier
- * @param maxItems the maximum number of workers to return
- * @param skipCount the number of workers to skip
- * @return list of workers instance
- * @throws NullPointerException when {@code workspace} is null
- * @throws ServerException when any other error occurs during worker fetching
- */
- Page getWorkers(String workspaceId, int maxItems, long skipCount)
- throws ServerException;
-
- /**
- * Gets workers by user
- *
- * @param userId workspace identifier
- * @return list of workers instance
- * @throws NullPointerException when {@code user} is null
- * @throws ServerException when any other error occurs during worker fetching
- */
- List getWorkersByUser(String userId) throws ServerException;
-}
diff --git a/multiuser/permission/che-multiuser-permission-workspace/src/main/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/JpaWorkerDao.java b/multiuser/permission/che-multiuser-permission-workspace/src/main/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/JpaWorkerDao.java
deleted file mode 100644
index 68fabf1149..0000000000
--- a/multiuser/permission/che-multiuser-permission-workspace/src/main/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/JpaWorkerDao.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.multiuser.permission.workspace.server.spi.jpa;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static java.lang.String.format;
-import static java.util.Objects.requireNonNull;
-import static java.util.stream.Collectors.toList;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.inject.persist.Transactional;
-import jakarta.annotation.PostConstruct;
-import jakarta.annotation.PreDestroy;
-import java.util.List;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.persistence.EntityManager;
-import javax.persistence.NoResultException;
-import org.eclipse.che.api.core.NotFoundException;
-import org.eclipse.che.api.core.Page;
-import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.api.core.notification.EventService;
-import org.eclipse.che.api.user.server.event.BeforeUserRemovedEvent;
-import org.eclipse.che.api.workspace.server.event.BeforeWorkspaceRemovedEvent;
-import org.eclipse.che.commons.annotation.Nullable;
-import org.eclipse.che.core.db.cascade.CascadeEventSubscriber;
-import org.eclipse.che.multiuser.api.permission.server.AbstractPermissionsDomain;
-import org.eclipse.che.multiuser.api.permission.server.jpa.AbstractJpaPermissionsDao;
-import org.eclipse.che.multiuser.permission.workspace.server.model.impl.WorkerImpl;
-import org.eclipse.che.multiuser.permission.workspace.server.spi.WorkerDao;
-
-/**
- * JPA based implementation of worker DAO.
- *
- * @author Max Shaposhnik
- */
-@Singleton
-public class JpaWorkerDao extends AbstractJpaPermissionsDao implements WorkerDao {
-
- @Inject
- public JpaWorkerDao(AbstractPermissionsDomain supportedDomain) {
- super(supportedDomain);
- }
-
- @Override
- public WorkerImpl getWorker(String workspaceId, String userId)
- throws ServerException, NotFoundException {
- return new WorkerImpl(get(userId, workspaceId));
- }
-
- @Override
- public void removeWorker(String workspaceId, String userId) throws ServerException {
- try {
- super.remove(userId, workspaceId);
- } catch (NotFoundException e) {
- throw new ServerException(e);
- }
- }
-
- @Override
- public Page getWorkers(String workspaceId, int maxItems, long skipCount)
- throws ServerException {
- return getByInstance(workspaceId, maxItems, skipCount);
- }
-
- @Override
- public List getWorkersByUser(String userId) throws ServerException {
- return getByUser(userId);
- }
-
- @Override
- public WorkerImpl get(String userId, String instanceId)
- throws ServerException, NotFoundException {
- requireNonNull(instanceId, "Workspace identifier required");
- requireNonNull(userId, "User identifier required");
- try {
- return new WorkerImpl(getEntity(wildcardToNull(userId), instanceId));
- } catch (RuntimeException x) {
- throw new ServerException(x.getLocalizedMessage(), x);
- }
- }
-
- @Override
- public List getByUser(String userId) throws ServerException {
- requireNonNull(userId, "User identifier required");
- return doGetByUser(wildcardToNull(userId)).stream().map(WorkerImpl::new).collect(toList());
- }
-
- @Override
- @Transactional
- public Page getByInstance(String instanceId, int maxItems, long skipCount)
- throws ServerException {
- requireNonNull(instanceId, "Workspace identifier required");
- checkArgument(
- skipCount <= Integer.MAX_VALUE,
- "The number of items to skip can't be greater than " + Integer.MAX_VALUE);
-
- try {
- final EntityManager entityManager = managerProvider.get();
- final List workers =
- entityManager
- .createNamedQuery("Worker.getByWorkspaceId", WorkerImpl.class)
- .setParameter("workspaceId", instanceId)
- .setMaxResults(maxItems)
- .setFirstResult((int) skipCount)
- .getResultList()
- .stream()
- .map(WorkerImpl::new)
- .collect(toList());
- final Long workersCount =
- entityManager
- .createNamedQuery("Worker.getCountByWorkspaceId", Long.class)
- .setParameter("workspaceId", instanceId)
- .getSingleResult();
- return new Page<>(workers, skipCount, maxItems, workersCount);
- } catch (RuntimeException e) {
- throw new ServerException(e.getLocalizedMessage(), e);
- }
- }
-
- @Override
- protected WorkerImpl getEntity(String userId, String instanceId)
- throws NotFoundException, ServerException {
- try {
- return doGet(userId, instanceId);
- } catch (NoResultException e) {
- throw new NotFoundException(
- format("Worker of workspace '%s' with id '%s' was not found.", instanceId, userId));
- } catch (RuntimeException e) {
- throw new ServerException(e.getMessage(), e);
- }
- }
-
- @Transactional
- protected WorkerImpl doGet(String userId, String instanceId) {
- return managerProvider
- .get()
- .createNamedQuery("Worker.getByUserAndWorkspaceId", WorkerImpl.class)
- .setParameter("workspaceId", instanceId)
- .setParameter("userId", userId)
- .getSingleResult();
- }
-
- @Transactional
- protected List doGetByUser(@Nullable String userId) throws ServerException {
- try {
- return managerProvider
- .get()
- .createNamedQuery("Worker.getByUserId", WorkerImpl.class)
- .setParameter("userId", userId)
- .getResultList();
- } catch (RuntimeException e) {
- throw new ServerException(e.getLocalizedMessage(), e);
- }
- }
-
- @Singleton
- public static class RemoveWorkersBeforeWorkspaceRemovedEventSubscriber
- extends CascadeEventSubscriber {
- private static final int PAGE_SIZE = 100;
-
- @Inject private EventService eventService;
- @Inject private WorkerDao workerDao;
-
- @PostConstruct
- public void subscribe() {
- eventService.subscribe(this, BeforeWorkspaceRemovedEvent.class);
- }
-
- @PreDestroy
- public void unsubscribe() {
- eventService.unsubscribe(this, BeforeWorkspaceRemovedEvent.class);
- }
-
- @Override
- public void onCascadeEvent(BeforeWorkspaceRemovedEvent event) throws Exception {
- removeWorkers(event.getWorkspace().getId(), PAGE_SIZE);
- }
-
- @VisibleForTesting
- void removeWorkers(String workspaceId, int pageSize) throws ServerException {
- Page workersPage;
- do {
- // skip count always equals to 0 because elements will be shifted after removing previous
- // items
- workersPage = workerDao.getWorkers(workspaceId, pageSize, 0);
- for (WorkerImpl worker : workersPage.getItems()) {
- workerDao.removeWorker(worker.getInstanceId(), worker.getUserId());
- }
- } while (workersPage.hasNextPage());
- }
- }
-
- @Singleton
- public static class RemoveWorkersBeforeUserRemovedEventSubscriber
- extends CascadeEventSubscriber {
- @Inject private EventService eventService;
- @Inject private WorkerDao dao;
-
- @PostConstruct
- public void subscribe() {
- eventService.subscribe(this, BeforeUserRemovedEvent.class);
- }
-
- @PreDestroy
- public void unsubscribe() {
- eventService.unsubscribe(this, BeforeUserRemovedEvent.class);
- }
-
- @Override
- public void onCascadeEvent(BeforeUserRemovedEvent event) throws Exception {
- for (WorkerImpl worker : dao.getWorkersByUser(event.getUser().getId())) {
- dao.removeWorker(worker.getInstanceId(), worker.getUserId());
- }
- }
- }
-}
diff --git a/multiuser/permission/che-multiuser-permission-workspace/src/main/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/MultiuserJpaWorkspaceDao.java b/multiuser/permission/che-multiuser-permission-workspace/src/main/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/MultiuserJpaWorkspaceDao.java
index 46fd0384f1..8d52b9e5df 100644
--- a/multiuser/permission/che-multiuser-permission-workspace/src/main/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/MultiuserJpaWorkspaceDao.java
+++ b/multiuser/permission/che-multiuser-permission-workspace/src/main/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/MultiuserJpaWorkspaceDao.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
+ * Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
@@ -13,17 +13,10 @@ package org.eclipse.che.multiuser.permission.workspace.server.spi.jpa;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
-import static java.util.Map.of;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
-import static org.eclipse.che.api.core.Pages.iterate;
-import static org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STOPPED;
-import static org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STOPPING;
-import static org.eclipse.che.api.workspace.shared.Constants.REMOVE_WORKSPACE_AFTER_STOP;
import com.google.inject.persist.Transactional;
-import jakarta.annotation.PostConstruct;
-import jakarta.annotation.PreDestroy;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@@ -32,21 +25,15 @@ import javax.inject.Provider;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
-import org.eclipse.che.account.event.BeforeAccountRemovedEvent;
import org.eclipse.che.api.core.ConflictException;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.Page;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.core.notification.EventService;
-import org.eclipse.che.api.workspace.server.WorkspaceManager;
-import org.eclipse.che.api.workspace.server.event.BeforeWorkspaceRemovedEvent;
import org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl;
import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl;
import org.eclipse.che.api.workspace.server.spi.WorkspaceDao;
import org.eclipse.che.api.workspace.shared.event.WorkspaceRemovedEvent;
-import org.eclipse.che.commons.env.EnvironmentContext;
-import org.eclipse.che.core.db.cascade.CascadeEventSubscriber;
-import org.eclipse.che.core.db.jpa.DuplicateKeyException;
/**
* JPA based implementation of {@link WorkspaceDao}.
@@ -75,11 +62,6 @@ public class MultiuserJpaWorkspaceDao implements WorkspaceDao {
requireNonNull(workspace, "Required non-null workspace");
try {
doCreate(workspace);
- } catch (DuplicateKeyException dkEx) {
- throw new ConflictException(
- format(
- "Workspace with id '%s' or name '%s' in namespace '%s' already exists",
- workspace.getId(), workspace.getName(), workspace.getNamespace()));
} catch (RuntimeException x) {
throw new ServerException(x.getMessage(), x);
}
@@ -92,11 +74,6 @@ public class MultiuserJpaWorkspaceDao implements WorkspaceDao {
requireNonNull(update, "Required non-null update");
try {
return new WorkspaceImpl(doUpdate(update));
- } catch (DuplicateKeyException dkEx) {
- throw new ConflictException(
- format(
- "Workspace with name '%s' in namespace '%s' already exists",
- update.getName(), update.getNamespace()));
} catch (RuntimeException x) {
throw new ServerException(x.getMessage(), x);
}
@@ -270,9 +247,6 @@ public class MultiuserJpaWorkspaceDao implements WorkspaceDao {
return Optional.empty();
}
final EntityManager manager = managerProvider.get();
- eventService
- .publish(new BeforeWorkspaceRemovedEvent(new WorkspaceImpl(workspace)))
- .propagateException();
manager.remove(workspace);
manager.flush();
return Optional.of(workspace);
@@ -291,83 +265,4 @@ public class MultiuserJpaWorkspaceDao implements WorkspaceDao {
manager.flush();
return merged;
}
-
- @Singleton
- public static class RemoveWorkspaceBeforeAccountRemovedEventSubscriber
- extends CascadeEventSubscriber {
-
- @Inject private EventService eventService;
- @Inject private WorkspaceManager workspaceManager;
-
- @PostConstruct
- public void subscribe() {
- eventService.subscribe(this, BeforeAccountRemovedEvent.class);
- }
-
- @PreDestroy
- public void unsubscribe() {
- eventService.unsubscribe(this, BeforeAccountRemovedEvent.class);
- }
-
- @Override
- public void onCascadeEvent(BeforeAccountRemovedEvent event) throws Exception {
- boolean nonStoppedExists = false;
- for (WorkspaceImpl workspace :
- iterate(
- (maxItems, skipCount) ->
- workspaceManager.getByNamespace(
- event.getAccount().getName(), false, maxItems, skipCount))) {
- if (STOPPED.equals(workspace.getStatus())) {
- workspaceManager.removeWorkspace(workspace.getId());
- continue;
- }
-
- nonStoppedExists = true;
-
- if (STOPPING.equals(workspace.getStatus())) {
- // it's not possible to forcibly stop workspace. Continue check other and fail after this
- // to retry
- continue;
- }
-
- // workspace is RUNNING or STARTING. It's needed to stop them and remove after
- tryStopAndRemoveWithSA(workspace);
- }
-
- if (!nonStoppedExists) {
- // all workspace are already removed
- return;
- }
-
- // There is at least one workspace that was marked to be stop/removed after stop.
- // It's needed to check if it's finished already
- for (WorkspaceImpl workspace :
- iterate(
- (maxItems, skipCount) ->
- workspaceManager.getByNamespace(
- event.getAccount().getName(), false, maxItems, skipCount))) {
- if (!STOPPED.equals(workspace.getStatus())) {
- throw new ConflictException("User has workspace that is not stopped yet. Try again");
- }
- }
- // Every workspace that was marked as to remove after stop is already removed
- }
-
- /**
- * Going to reset EnvironmentContext, in this case Service Account(SA) credentials will be used
- * for stopping workspace. If SA have required permissions workspace will be stopped otherwise
- * exception thrown.
- */
- private void tryStopAndRemoveWithSA(WorkspaceImpl workspace)
- throws ServerException, NotFoundException, ConflictException {
- EnvironmentContext current = EnvironmentContext.getCurrent();
- try {
- EnvironmentContext.reset();
- // Stop workspace and remove it after it was stopped
- workspaceManager.stopWorkspace(workspace.getId(), of(REMOVE_WORKSPACE_AFTER_STOP, "true"));
- } finally {
- EnvironmentContext.setCurrent(current);
- }
- }
- }
}
diff --git a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/jpa/MultiuserJpaWorkspaceDaoTest.java b/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/jpa/MultiuserJpaWorkspaceDaoTest.java
deleted file mode 100644
index eebd31c7ab..0000000000
--- a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/jpa/MultiuserJpaWorkspaceDaoTest.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.multiuser.permission.workspace.server.jpa;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import com.google.inject.Guice;
-import com.google.inject.Injector;
-import java.util.Arrays;
-import java.util.List;
-import javax.persistence.EntityManager;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl;
-import org.eclipse.che.commons.test.tck.TckResourcesCleaner;
-import org.eclipse.che.multiuser.permission.workspace.server.model.impl.WorkerImpl;
-import org.eclipse.che.multiuser.permission.workspace.server.spi.jpa.MultiuserJpaWorkspaceDao;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-/** @author Max Shaposhnik */
-public class MultiuserJpaWorkspaceDaoTest {
- private TckResourcesCleaner tckResourcesCleaner;
- private EntityManager manager;
- private MultiuserJpaWorkspaceDao dao;
-
- private AccountImpl account;
- private WorkerImpl[] workers;
- private UserImpl[] users;
- private WorkspaceImpl[] workspaces;
-
- @BeforeClass
- public void setupEntities() throws Exception {
- workers =
- new WorkerImpl[] {
- new WorkerImpl("ws1", "user1", Arrays.asList("read", "use", "search")),
- new WorkerImpl("ws2", "user1", Arrays.asList("read", "search")),
- new WorkerImpl("ws3", "user1", Arrays.asList("none", "run")),
- new WorkerImpl("ws1", "user2", Arrays.asList("read", "use"))
- };
-
- users =
- new UserImpl[] {
- new UserImpl("user1", "user1@com.com", "usr1"),
- new UserImpl("user2", "user2@com.com", "usr2")
- };
-
- account = new AccountImpl("account1", "accountName", "test");
-
- workspaces =
- new WorkspaceImpl[] {
- new WorkspaceImpl(
- "ws1",
- account,
- new WorkspaceConfigImpl("wrksp1", "", "cfg1", null, null, null, null)),
- new WorkspaceImpl(
- "ws2",
- account,
- new WorkspaceConfigImpl("wrksp2", "", "cfg2", null, null, null, null)),
- new WorkspaceImpl(
- "ws3", account, new WorkspaceConfigImpl("wrksp3", "", "cfg3", null, null, null, null))
- };
- Injector injector = Guice.createInjector(new WorkspaceTckModule());
- manager = injector.getInstance(EntityManager.class);
- dao = injector.getInstance(MultiuserJpaWorkspaceDao.class);
- tckResourcesCleaner = injector.getInstance(TckResourcesCleaner.class);
- }
-
- @BeforeMethod
- public void setUp() throws Exception {
- manager.getTransaction().begin();
- manager.persist(account);
-
- for (UserImpl user : users) {
- manager.persist(user);
- }
-
- for (WorkspaceImpl ws : workspaces) {
- manager.persist(ws);
- }
-
- for (WorkerImpl worker : workers) {
- manager.persist(worker);
- }
- manager.getTransaction().commit();
- manager.clear();
- }
-
- @AfterMethod
- public void cleanup() {
- manager.getTransaction().begin();
-
- manager
- .createQuery("SELECT e FROM Worker e", WorkerImpl.class)
- .getResultList()
- .forEach(manager::remove);
-
- manager
- .createQuery("SELECT w FROM Workspace w", WorkspaceImpl.class)
- .getResultList()
- .forEach(manager::remove);
-
- manager
- .createQuery("SELECT u FROM Usr u", UserImpl.class)
- .getResultList()
- .forEach(manager::remove);
-
- manager
- .createQuery("SELECT a FROM Account a", AccountImpl.class)
- .getResultList()
- .forEach(manager::remove);
- manager.getTransaction().commit();
- }
-
- @Test
- public void shouldGetTotalWorkspaceCount() throws ServerException {
- assertEquals(dao.getWorkspacesTotalCount(), 3);
- }
-
- @AfterClass
- public void shutdown() throws Exception {
- tckResourcesCleaner.clean();
- }
-
- @Test
- public void shouldFindStackByPermissions() throws Exception {
- List results = dao.getWorkspaces(users[0].getId(), 30, 0).getItems();
- assertEquals(results.size(), 2);
- assertTrue(results.contains(workspaces[0]));
- assertTrue(results.contains(workspaces[1]));
- }
-}
diff --git a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/jpa/WorkspaceTckModule.java b/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/jpa/WorkspaceTckModule.java
deleted file mode 100644
index 02fa438828..0000000000
--- a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/jpa/WorkspaceTckModule.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.multiuser.permission.workspace.server.jpa;
-
-import com.google.inject.TypeLiteral;
-import java.util.Collection;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.api.workspace.server.devfile.SerializableConverter;
-import org.eclipse.che.api.workspace.server.jpa.JpaWorkspaceDao;
-import org.eclipse.che.api.workspace.server.model.impl.CommandImpl;
-import org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl;
-import org.eclipse.che.api.workspace.server.model.impl.MachineConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.RecipeImpl;
-import org.eclipse.che.api.workspace.server.model.impl.ServerConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.SourceStorageImpl;
-import org.eclipse.che.api.workspace.server.model.impl.VolumeImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ActionImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ComponentImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.DevfileImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.EndpointImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.EntrypointImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.EnvImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ProjectImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.SourceImpl;
-import org.eclipse.che.api.workspace.server.spi.WorkspaceDao;
-import org.eclipse.che.commons.test.db.H2DBTestServer;
-import org.eclipse.che.commons.test.db.H2JpaCleaner;
-import org.eclipse.che.commons.test.db.PersistTestModuleBuilder;
-import org.eclipse.che.commons.test.tck.TckModule;
-import org.eclipse.che.commons.test.tck.TckResourcesCleaner;
-import org.eclipse.che.commons.test.tck.repository.JpaTckRepository;
-import org.eclipse.che.commons.test.tck.repository.TckRepository;
-import org.eclipse.che.commons.test.tck.repository.TckRepositoryException;
-import org.eclipse.che.core.db.DBInitializer;
-import org.eclipse.che.core.db.h2.jpa.eclipselink.H2ExceptionHandler;
-import org.eclipse.che.core.db.schema.SchemaInitializer;
-import org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer;
-import org.eclipse.che.multiuser.api.permission.server.AbstractPermissionsDomain;
-import org.eclipse.che.multiuser.permission.workspace.server.model.impl.WorkerImpl;
-import org.eclipse.che.multiuser.permission.workspace.server.spi.WorkerDao;
-import org.eclipse.che.multiuser.permission.workspace.server.spi.jpa.JpaWorkerDao;
-import org.eclipse.che.multiuser.permission.workspace.server.spi.tck.WorkerDaoTest;
-import org.h2.Driver;
-
-/** @author Yevhenii Voevodin */
-public class WorkspaceTckModule extends TckModule {
-
- @Override
- protected void configure() {
- H2DBTestServer server = H2DBTestServer.startDefault();
- install(
- new PersistTestModuleBuilder()
- .setDriver(Driver.class)
- .runningOn(server)
- .addEntityClasses(
- AccountImpl.class,
- UserImpl.class,
- WorkspaceImpl.class,
- WorkspaceConfigImpl.class,
- ProjectConfigImpl.class,
- EnvironmentImpl.class,
- WorkerImpl.class,
- MachineConfigImpl.class,
- SourceStorageImpl.class,
- ServerConfigImpl.class,
- CommandImpl.class,
- RecipeImpl.class,
- VolumeImpl.class,
- // devfile
- ActionImpl.class,
- org.eclipse.che.api.workspace.server.model.impl.devfile.CommandImpl.class,
- ComponentImpl.class,
- DevfileImpl.class,
- EndpointImpl.class,
- EntrypointImpl.class,
- EnvImpl.class,
- ProjectImpl.class,
- SourceImpl.class,
- org.eclipse.che.api.workspace.server.model.impl.devfile.VolumeImpl.class)
- .addEntityClass(
- "org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl$Attribute")
- .addClass(SerializableConverter.class)
- .setExceptionHandler(H2ExceptionHandler.class)
- .build());
- bind(DBInitializer.class).asEagerSingleton();
- bind(SchemaInitializer.class)
- .toInstance(new FlywaySchemaInitializer(server.getDataSource(), "che-schema"));
- bind(TckResourcesCleaner.class).toInstance(new H2JpaCleaner(server));
-
- bind(new TypeLiteral>() {})
- .toInstance(new JpaTckRepository<>(AccountImpl.class));
- bind(new TypeLiteral>() {}).toInstance(new WorkspaceRepository());
- bind(new TypeLiteral>() {})
- .toInstance(new JpaTckRepository<>(UserImpl.class));
- bind(new TypeLiteral>() {})
- .toInstance(new JpaTckRepository<>(WorkerImpl.class));
-
- bind(new TypeLiteral>() {})
- .to(WorkerDaoTest.TestDomain.class);
-
- bind(WorkerDao.class).to(JpaWorkerDao.class);
- bind(WorkspaceDao.class).to(JpaWorkspaceDao.class);
- }
-
- private static class WorkspaceRepository extends JpaTckRepository {
- public WorkspaceRepository() {
- super(WorkspaceImpl.class);
- }
-
- @Override
- public void createAll(Collection extends WorkspaceImpl> entities)
- throws TckRepositoryException {
- for (WorkspaceImpl entity : entities) {
- entity.getConfig().getProjects().forEach(ProjectConfigImpl::prePersistAttributes);
- }
- super.createAll(entities);
- }
- }
-}
diff --git a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/JpaTckModule.java b/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/JpaTckModule.java
deleted file mode 100644
index 6d0b6ed62b..0000000000
--- a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/JpaTckModule.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.multiuser.permission.workspace.server.spi.jpa;
-
-import com.google.inject.TypeLiteral;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.api.workspace.server.devfile.SerializableConverter;
-import org.eclipse.che.api.workspace.server.model.impl.CommandImpl;
-import org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl;
-import org.eclipse.che.api.workspace.server.model.impl.MachineConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.RecipeImpl;
-import org.eclipse.che.api.workspace.server.model.impl.ServerConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.SourceStorageImpl;
-import org.eclipse.che.api.workspace.server.model.impl.VolumeImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ActionImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ComponentImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.DevfileImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.EndpointImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.EntrypointImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.EnvImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ProjectImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.SourceImpl;
-import org.eclipse.che.commons.test.db.H2DBTestServer;
-import org.eclipse.che.commons.test.db.H2JpaCleaner;
-import org.eclipse.che.commons.test.db.PersistTestModuleBuilder;
-import org.eclipse.che.commons.test.tck.TckModule;
-import org.eclipse.che.commons.test.tck.TckResourcesCleaner;
-import org.eclipse.che.commons.test.tck.repository.JpaTckRepository;
-import org.eclipse.che.commons.test.tck.repository.TckRepository;
-import org.eclipse.che.core.db.DBInitializer;
-import org.eclipse.che.core.db.h2.jpa.eclipselink.H2ExceptionHandler;
-import org.eclipse.che.core.db.schema.SchemaInitializer;
-import org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer;
-import org.eclipse.che.multiuser.api.permission.server.AbstractPermissionsDomain;
-import org.eclipse.che.multiuser.permission.workspace.server.model.impl.WorkerImpl;
-import org.eclipse.che.multiuser.permission.workspace.server.spi.WorkerDao;
-import org.eclipse.che.multiuser.permission.workspace.server.spi.tck.WorkerDaoTest;
-import org.h2.Driver;
-
-/** @author Yevhenii Voevodin */
-public class JpaTckModule extends TckModule {
-
- @Override
- protected void configure() {
- H2DBTestServer server = H2DBTestServer.startDefault();
- install(
- new PersistTestModuleBuilder()
- .setDriver(Driver.class)
- .runningOn(server)
- .addEntityClasses(
- AccountImpl.class,
- UserImpl.class,
- WorkspaceImpl.class,
- WorkspaceConfigImpl.class,
- ProjectConfigImpl.class,
- EnvironmentImpl.class,
- WorkerImpl.class,
- MachineConfigImpl.class,
- SourceStorageImpl.class,
- ServerConfigImpl.class,
- CommandImpl.class,
- RecipeImpl.class,
- VolumeImpl.class,
- // devfile
- ActionImpl.class,
- org.eclipse.che.api.workspace.server.model.impl.devfile.CommandImpl.class,
- ComponentImpl.class,
- DevfileImpl.class,
- EndpointImpl.class,
- EntrypointImpl.class,
- EnvImpl.class,
- ProjectImpl.class,
- SourceImpl.class,
- org.eclipse.che.api.workspace.server.model.impl.devfile.VolumeImpl.class)
- .addEntityClass(
- "org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl$Attribute")
- .addClass(SerializableConverter.class)
- .setExceptionHandler(H2ExceptionHandler.class)
- .build());
-
- bind(new TypeLiteral>() {})
- .to(WorkerDaoTest.TestDomain.class);
-
- bind(WorkerDao.class).to(JpaWorkerDao.class);
- bind(new TypeLiteral>() {})
- .toInstance(new JpaTckRepository<>(WorkerImpl.class));
- bind(new TypeLiteral>() {})
- .toInstance(new JpaTckRepository<>(UserImpl.class));
- bind(new TypeLiteral>() {})
- .toInstance(new JpaTckRepository<>(AccountImpl.class));
-
- bind(new TypeLiteral>() {})
- .toInstance(new JpaTckRepository<>(WorkspaceImpl.class));
-
- bind(SchemaInitializer.class)
- .toInstance(new FlywaySchemaInitializer(server.getDataSource(), "che-schema"));
- bind(DBInitializer.class).asEagerSingleton();
- bind(TckResourcesCleaner.class).toInstance(new H2JpaCleaner(server));
- }
-}
diff --git a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/JpaWorkerDaoTest.java b/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/JpaWorkerDaoTest.java
deleted file mode 100644
index 3d8117317d..0000000000
--- a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/JpaWorkerDaoTest.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.multiuser.permission.workspace.server.spi.jpa;
-
-import static org.eclipse.che.inject.Matchers.names;
-import static org.eclipse.che.multiuser.api.permission.server.AbstractPermissionsDomain.SET_PERMISSIONS;
-
-import com.google.inject.Guice;
-import com.google.inject.Injector;
-import com.google.inject.matcher.Matchers;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import javax.persistence.EntityManager;
-import org.aopalliance.intercept.MethodInterceptor;
-import org.eclipse.che.account.shared.model.Account;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl;
-import org.eclipse.che.commons.test.tck.TckModule;
-import org.eclipse.che.commons.test.tck.TckResourcesCleaner;
-import org.eclipse.che.multiuser.permission.workspace.server.model.impl.WorkerImpl;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class JpaWorkerDaoTest {
-
- private JpaWorkerDao workerDao;
- private EntityManager manager;
- private TckResourcesCleaner tckResourcesCleaner;
-
- @BeforeMethod
- private void setUpManager() {
- final Injector injector =
- Guice.createInjector(new JpaTckModule(), new ExceptionEntityManagerModule());
- manager = injector.getInstance(EntityManager.class);
- workerDao = injector.getInstance(JpaWorkerDao.class);
- tckResourcesCleaner = injector.getInstance(TckResourcesCleaner.class);
- }
-
- @AfterMethod
- private void cleanup() {
- manager.getTransaction().begin();
- final List entities = new ArrayList<>();
- entities.addAll(manager.createQuery("SELECT w FROM Worker w").getResultList());
- entities.addAll(manager.createQuery("SELECT w FROM Workspace w").getResultList());
- entities.addAll(manager.createQuery("SELECT u FROM Usr u").getResultList());
- entities.addAll(manager.createQuery("SELECT a FROM Account a").getResultList());
- for (Object entity : entities) {
- manager.remove(entity);
- }
- manager.getTransaction().commit();
- tckResourcesCleaner.clean();
- }
-
- @Test(
- expectedExceptions = ServerException.class,
- expectedExceptionsMessageRegExp = "Database exception")
- public void shouldThrowServerExceptionOnExistsWhenRuntimeExceptionOccursInDoGetMethod()
- throws Exception {
-
- final Account account = new AccountImpl("accountId", "namespace", "test");
- final WorkspaceImpl workspace =
- WorkspaceImpl.builder().setId("workspaceId").setAccount(account).build();
-
- // Persist the account
- manager.getTransaction().begin();
- manager.persist(account);
- manager.getTransaction().commit();
- manager.clear();
-
- // Persist the workspace
- manager.getTransaction().begin();
- manager.persist(workspace);
- manager.getTransaction().commit();
- manager.clear();
- final UserImpl user = new UserImpl("user0", "user0@com.com", "usr0");
- // Persist the user
- manager.getTransaction().begin();
- manager.persist(user);
- manager.getTransaction().commit();
- manager.clear();
-
- // Persist the worker
- WorkerImpl worker =
- new WorkerImpl("workspaceId", "user0", Collections.singletonList(SET_PERMISSIONS));
- manager.getTransaction().begin();
- manager.persist(worker);
- manager.getTransaction().commit();
- manager.clear();
-
- workerDao.exists("user0", "workspaceId", SET_PERMISSIONS);
- }
-
- public class ExceptionEntityManagerModule extends TckModule {
-
- @Override
- protected void configure() {
- MethodInterceptor interceptor = new EntityManagerExceptionInterceptor();
- requestInjection(interceptor);
- bindInterceptor(Matchers.subclassesOf(JpaWorkerDao.class), names("doGet"), interceptor);
- }
- }
-}
diff --git a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/RemoveWorkersBeforeWorkspaceRemovedEventSubscriberTest.java b/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/RemoveWorkersBeforeWorkspaceRemovedEventSubscriberTest.java
deleted file mode 100644
index ac0cf559b3..0000000000
--- a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/RemoveWorkersBeforeWorkspaceRemovedEventSubscriberTest.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (c) 2012-2018 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.multiuser.permission.workspace.server.spi.jpa;
-
-import static org.testng.AssertJUnit.assertEquals;
-
-import com.google.inject.Guice;
-import com.google.inject.Injector;
-import java.util.Arrays;
-import java.util.stream.Stream;
-import javax.persistence.EntityManager;
-import org.eclipse.che.account.shared.model.Account;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.api.workspace.server.jpa.JpaWorkspaceDao;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl;
-import org.eclipse.che.commons.test.tck.TckResourcesCleaner;
-import org.eclipse.che.multiuser.permission.workspace.server.model.impl.WorkerImpl;
-import org.eclipse.che.multiuser.permission.workspace.server.spi.jpa.JpaWorkerDao.RemoveWorkersBeforeWorkspaceRemovedEventSubscriber;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-/**
- * Tests for {@link RemoveWorkersBeforeWorkspaceRemovedEventSubscriber}
- *
- * @author Sergii Leschenko
- */
-public class RemoveWorkersBeforeWorkspaceRemovedEventSubscriberTest {
- private TckResourcesCleaner tckResourcesCleaner;
- private EntityManager manager;
- private JpaWorkerDao workerDao;
- private JpaWorkspaceDao workspaceDao;
-
- private RemoveWorkersBeforeWorkspaceRemovedEventSubscriber subscriber;
-
- private WorkspaceImpl workspace;
- private WorkerImpl[] workers;
- private UserImpl[] users;
- private Account account;
-
- @BeforeClass
- public void setupEntities() throws Exception {
- account = new AccountImpl("account1", "accountName", "test");
-
- users =
- new UserImpl[] {
- new UserImpl("user1", "user1@com.com", "usr1"),
- new UserImpl("user2", "user2@com.com", "usr2")
- };
-
- workspace =
- new WorkspaceImpl(
- "ws1", account, new WorkspaceConfigImpl("", "", "cfg1", null, null, null, null));
-
- workers =
- new WorkerImpl[] {
- new WorkerImpl("ws1", "user1", Arrays.asList("read", "use", "run")),
- new WorkerImpl("ws1", "user2", Arrays.asList("read", "use"))
- };
-
- Injector injector = Guice.createInjector(new JpaTckModule());
-
- manager = injector.getInstance(EntityManager.class);
- workerDao = injector.getInstance(JpaWorkerDao.class);
- workspaceDao = injector.getInstance(JpaWorkspaceDao.class);
- subscriber = injector.getInstance(RemoveWorkersBeforeWorkspaceRemovedEventSubscriber.class);
- subscriber.subscribe();
- tckResourcesCleaner = injector.getInstance(TckResourcesCleaner.class);
- }
-
- @BeforeMethod
- public void setUp() throws Exception {
- manager.getTransaction().begin();
- manager.persist(account);
- manager.persist(workspace);
- Stream.of(users).forEach(manager::persist);
- Stream.of(workers).forEach(manager::persist);
- manager.getTransaction().commit();
- manager.clear();
- }
-
- @AfterMethod
- public void cleanup() {
- manager.getTransaction().begin();
-
- manager
- .createQuery("SELECT e FROM Worker e", WorkerImpl.class)
- .getResultList()
- .forEach(manager::remove);
-
- manager
- .createQuery("SELECT w FROM Workspace w", WorkspaceImpl.class)
- .getResultList()
- .forEach(manager::remove);
-
- manager
- .createQuery("SELECT u FROM Usr u", UserImpl.class)
- .getResultList()
- .forEach(manager::remove);
-
- manager
- .createQuery("SELECT a FROM Account a", AccountImpl.class)
- .getResultList()
- .forEach(manager::remove);
- manager.getTransaction().commit();
- }
-
- @AfterClass
- public void shutdown() throws Exception {
- subscriber.unsubscribe();
- tckResourcesCleaner.clean();
- }
-
- @Test
- public void shouldRemoveAllWorkersWhenWorkspaceIsRemoved() throws Exception {
- workspaceDao.remove(workspace.getId());
-
- assertEquals(workerDao.getWorkers(workspace.getId(), 1, 0).getTotalItemsCount(), 0);
- }
-
- @Test
- public void shouldRemoveAllWorkersWhenPageSizeEqualsToOne() throws Exception {
- subscriber.removeWorkers(workspace.getId(), 1);
-
- assertEquals(workerDao.getWorkers(workspace.getId(), 1, 0).getTotalItemsCount(), 0);
- }
-}
diff --git a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/RemoveWorkspaceBeforeAccountRemovedEventSubscriberTest.java b/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/RemoveWorkspaceBeforeAccountRemovedEventSubscriberTest.java
deleted file mode 100644
index 5c02b9ed0c..0000000000
--- a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/jpa/RemoveWorkspaceBeforeAccountRemovedEventSubscriberTest.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.multiuser.permission.workspace.server.spi.jpa;
-
-import static java.util.Map.of;
-import static org.eclipse.che.api.workspace.shared.Constants.REMOVE_WORKSPACE_AFTER_STOP;
-import static org.mockito.ArgumentMatchers.anyBoolean;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.lenient;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.util.Arrays;
-import org.eclipse.che.account.event.BeforeAccountRemovedEvent;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.core.ConflictException;
-import org.eclipse.che.api.core.Page;
-import org.eclipse.che.api.core.model.workspace.Runtime;
-import org.eclipse.che.api.core.model.workspace.WorkspaceStatus;
-import org.eclipse.che.api.core.notification.EventService;
-import org.eclipse.che.api.workspace.server.WorkspaceManager;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl;
-import org.eclipse.che.commons.env.EnvironmentContext;
-import org.eclipse.che.commons.lang.NameGenerator;
-import org.eclipse.che.commons.subject.Subject;
-import org.eclipse.che.commons.subject.SubjectImpl;
-import org.eclipse.che.multiuser.permission.workspace.server.spi.jpa.MultiuserJpaWorkspaceDao.RemoveWorkspaceBeforeAccountRemovedEventSubscriber;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.testng.MockitoTestNGListener;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Listeners;
-import org.testng.annotations.Test;
-
-/** Tests for {@link RemoveWorkspaceBeforeAccountRemovedEventSubscriber} */
-@Listeners(MockitoTestNGListener.class)
-public class RemoveWorkspaceBeforeAccountRemovedEventSubscriberTest {
- @Mock private EventService eventService;
- @Mock private WorkspaceManager workspaceManager;
-
- @InjectMocks RemoveWorkspaceBeforeAccountRemovedEventSubscriber subscriber;
-
- private static final String user = NameGenerator.generate("user", 6);
- private static final String otherUser = NameGenerator.generate("otherUser", 6);
- private static final Subject SUBJECT = new SubjectImpl("user", user, "token", false);
- private final String workspaceId = NameGenerator.generate("workspace", 6);
- private AccountImpl account;
- private WorkspaceImpl workspace;
-
- @BeforeMethod
- public void setUp() throws Exception {
- account = new AccountImpl("id", "name", "test");
- workspace = new WorkspaceImpl(workspaceId, account, new WorkspaceConfigImpl());
- lenient()
- .when(workspaceManager.getByNamespace(anyString(), anyBoolean(), anyInt(), anyLong()))
- .thenReturn(new Page<>(Arrays.asList(workspace), 0, 1, 1));
- }
-
- @Test
- public void shouldSubscribeItself() {
- subscriber.subscribe();
-
- verify(eventService).subscribe(eq(subscriber), eq(BeforeAccountRemovedEvent.class));
- }
-
- @Test
- public void shouldUnsubscribeItself() {
- subscriber.unsubscribe();
-
- verify(eventService).unsubscribe(eq(subscriber), eq(BeforeAccountRemovedEvent.class));
- }
-
- @Test
- public void shouldRemoveStoppedWorkspace() throws Exception {
- workspace.setStatus(WorkspaceStatus.STOPPED);
- subscriber.onCascadeEvent(new BeforeAccountRemovedEvent(account));
-
- verify(workspaceManager).removeWorkspace(workspaceId);
- }
-
- @Test
- public void shouldStopAndRemoveRunningWorkspaceByOwner() throws Exception {
- workspace.setStatus(WorkspaceStatus.RUNNING);
- EnvironmentContext.getCurrent().setSubject(SUBJECT);
-
- doAnswer(
- invocation -> {
- workspace.setStatus(WorkspaceStatus.STOPPED);
- return null;
- })
- .when(workspaceManager)
- .stopWorkspace(workspaceId, of(REMOVE_WORKSPACE_AFTER_STOP, "true"));
-
- subscriber.onCascadeEvent(new BeforeAccountRemovedEvent(account));
-
- verify(workspaceManager).stopWorkspace(workspaceId, of(REMOVE_WORKSPACE_AFTER_STOP, "true"));
- }
-
- @Test
- public void shouldStopAndRemoveStartingWorkspaceByOwner() throws Exception {
- workspace.setStatus(WorkspaceStatus.STARTING);
- EnvironmentContext.getCurrent().setSubject(SUBJECT);
-
- doAnswer(
- invocation -> {
- workspace.setStatus(WorkspaceStatus.STOPPED);
- return null;
- })
- .when(workspaceManager)
- .stopWorkspace(workspaceId, of(REMOVE_WORKSPACE_AFTER_STOP, "true"));
-
- subscriber.onCascadeEvent(new BeforeAccountRemovedEvent(account));
-
- verify(workspaceManager).stopWorkspace(workspaceId, of(REMOVE_WORKSPACE_AFTER_STOP, "true"));
- }
-
- @Test
- public void shouldStopAndRemoveWorkspaceByAdmin() throws Exception {
- workspace.setStatus(WorkspaceStatus.STARTING);
- EnvironmentContext.getCurrent().setSubject(SUBJECT);
-
- doAnswer(
- invocation -> {
- workspace.setStatus(WorkspaceStatus.STOPPED);
- return null;
- })
- .when(workspaceManager)
- .stopWorkspace(workspaceId, of(REMOVE_WORKSPACE_AFTER_STOP, "true"));
-
- subscriber.onCascadeEvent(new BeforeAccountRemovedEvent(account));
-
- verify(workspaceManager).stopWorkspace(workspaceId, of(REMOVE_WORKSPACE_AFTER_STOP, "true"));
- }
-
- @Test(expectedExceptions = ConflictException.class)
- public void shouldThrowExceptionIfWorkspaceStopping() throws Exception {
- workspace.setStatus(WorkspaceStatus.STARTING);
- Runtime runtime = mock(Runtime.class);
- when(runtime.getOwner()).thenReturn(otherUser);
- workspace.setRuntime(runtime);
- EnvironmentContext.getCurrent().setSubject(SUBJECT);
-
- subscriber.onCascadeEvent(new BeforeAccountRemovedEvent(account));
-
- verify(workspaceManager).stopWorkspace(workspaceId, of(REMOVE_WORKSPACE_AFTER_STOP, "true"));
- }
-}
diff --git a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/tck/WorkerDaoTest.java b/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/tck/WorkerDaoTest.java
deleted file mode 100644
index f367e47b12..0000000000
--- a/multiuser/permission/che-multiuser-permission-workspace/src/test/java/org/eclipse/che/multiuser/permission/workspace/server/spi/tck/WorkerDaoTest.java
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.multiuser.permission.workspace.server.spi.tck;
-
-import static org.testng.Assert.*;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-import javax.inject.Inject;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.core.NotFoundException;
-import org.eclipse.che.api.core.Page;
-import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl;
-import org.eclipse.che.commons.test.tck.TckListener;
-import org.eclipse.che.commons.test.tck.repository.TckRepository;
-import org.eclipse.che.commons.test.tck.repository.TckRepositoryException;
-import org.eclipse.che.multiuser.api.permission.server.AbstractPermissionsDomain;
-import org.eclipse.che.multiuser.permission.workspace.server.model.impl.WorkerImpl;
-import org.eclipse.che.multiuser.permission.workspace.server.spi.WorkerDao;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Listeners;
-import org.testng.annotations.Test;
-
-/**
- * Compatibility test for {@link WorkerDao}
- *
- * @author Max Shaposhnik
- */
-@Listeners(TckListener.class)
-@Test(suiteName = "WorkerDaoTck")
-public class WorkerDaoTest {
-
- @Inject private WorkerDao workerDao;
-
- @Inject private TckRepository workerRepository;
-
- @Inject private TckRepository userRepository;
-
- @Inject private TckRepository accountRepository;
-
- @Inject private TckRepository workspaceRepository;
-
- WorkerImpl[] workers;
-
- @BeforeMethod
- public void setUp() throws TckRepositoryException {
- workers =
- new WorkerImpl[] {
- new WorkerImpl("ws1", "user1", Arrays.asList("read", "use", "run")),
- new WorkerImpl("ws1", "user2", Arrays.asList("read", "use")),
- new WorkerImpl("ws2", "user1", Arrays.asList("read", "run")),
- new WorkerImpl("ws2", "user2", Arrays.asList("read", "use", "run", "configure")),
- new WorkerImpl("ws2", "user0", Arrays.asList("read", "use", "run", "configure"))
- };
-
- final UserImpl[] users =
- new UserImpl[] {
- new UserImpl("user0", "user0@com.com", "usr0"),
- new UserImpl("user1", "user1@com.com", "usr1"),
- new UserImpl("user2", "user2@com.com", "usr2")
- };
- userRepository.createAll(Arrays.asList(users));
-
- AccountImpl account = new AccountImpl("account1", "accountName", "test");
- accountRepository.createAll(Collections.singletonList(account));
- workspaceRepository.createAll(
- Arrays.asList(
- new WorkspaceImpl(
- "ws0",
- account,
- new WorkspaceConfigImpl("ws-name0", "", "cfg0", null, null, null, null)),
- new WorkspaceImpl(
- "ws1",
- account,
- new WorkspaceConfigImpl("ws-name1", "", "cfg1", null, null, null, null)),
- new WorkspaceImpl(
- "ws2",
- account,
- new WorkspaceConfigImpl("ws-name2", "", "cfg2", null, null, null, null))));
-
- workerRepository.createAll(
- Stream.of(workers).map(WorkerImpl::new).collect(Collectors.toList()));
- }
-
- @AfterMethod
- public void cleanUp() throws TckRepositoryException {
- workerRepository.removeAll();
- workspaceRepository.removeAll();
- userRepository.removeAll();
- accountRepository.removeAll();
- }
-
- /* WorkerDao.store() tests */
- @Test
- public void shouldStoreWorker() throws Exception {
- WorkerImpl worker = new WorkerImpl("ws0", "user0", Arrays.asList("read", "use", "run"));
- workerDao.store(worker);
- Assert.assertEquals(workerDao.getWorker("ws0", "user0"), new WorkerImpl(worker));
- }
-
- @Test
- public void shouldReplaceExistingWorkerOnStoring() throws Exception {
- WorkerImpl replace = new WorkerImpl("ws1", "user1", Collections.singletonList("read"));
- workerDao.store(replace);
- Assert.assertEquals(workerDao.getWorker("ws1", "user1"), replace);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowExceptionWhenStoringArgumentIsNull() throws Exception {
- workerDao.store(null);
- }
-
- /* WorkerDao.getWorker() tests */
- @Test
- public void shouldGetWorkerByWorkspaceIdAndUserId() throws Exception {
- Assert.assertEquals(workerDao.getWorker("ws1", "user1"), workers[0]);
- Assert.assertEquals(workerDao.getWorker("ws2", "user2"), workers[3]);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowExceptionWhenGetWorkerWorkspaceIdArgumentIsNull() throws Exception {
- workerDao.getWorker(null, "user1");
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowExceptionWhenGetWorkerUserIdArgumentIsNull() throws Exception {
- workerDao.getWorker("ws1", null);
- }
-
- @Test(expectedExceptions = NotFoundException.class)
- public void shouldThrowNotFoundExceptionOnGetIfWorkerWithSuchWorkspaceIdOrUserIdDoesNotExist()
- throws Exception {
- workerDao.getWorker("ws9", "user1");
- }
-
- /* WorkerDao.getWorkers() tests */
- @Test
- public void shouldGetWorkersByWorkspaceId() throws Exception {
- Page workersPage = workerDao.getWorkers("ws2", 1, 1);
-
- final List fetchedWorkers = workersPage.getItems();
- assertEquals(workersPage.getTotalItemsCount(), 3);
- assertEquals(workersPage.getItemsCount(), 1);
- assertTrue(
- fetchedWorkers.contains(workers[2])
- ^ fetchedWorkers.contains(workers[3])
- ^ fetchedWorkers.contains(workers[4]));
- }
-
- @Test
- public void shouldGetWorkersByUserId() throws Exception {
- List actual = workerDao.getWorkersByUser("user1");
- List expected = Arrays.asList(workers[0], workers[2]);
- assertEquals(actual.size(), expected.size());
- assertTrue(new HashSet<>(actual).equals(new HashSet<>(expected)));
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowExceptionWhenGetWorkersByWorkspaceArgumentIsNull() throws Exception {
- workerDao.getWorkers(null, 1, 0);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowExceptionWhenGetWorkersByUserArgumentIsNull() throws Exception {
- workerDao.getWorkersByUser(null);
- }
-
- @Test
- public void shouldReturnEmptyListIfWorkersWithSuchWorkspaceIdDoesNotFound() throws Exception {
- assertEquals(0, workerDao.getWorkers("unexisted_ws", 1, 0).getItemsCount());
- }
-
- @Test
- public void shouldReturnEmptyListIfWorkersWithSuchUserIdDoesNotFound() throws Exception {
- assertEquals(0, workerDao.getWorkersByUser("unexisted_user").size());
- }
-
- /* WorkerDao.removeWorker() tests */
- @Test
- public void shouldRemoveWorker() throws Exception {
- workerDao.removeWorker("ws1", "user1");
- assertEquals(1, workerDao.getWorkersByUser("user1").size());
- assertNull(notFoundToNull(() -> workerDao.getWorker("ws1", "user1")));
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowExceptionWhenRemoveWorkerWorkspaceIdArgumentIsNull() throws Exception {
- workerDao.removeWorker(null, "user1");
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowExceptionWhenRemoveWorkerUserIdArgumentIsNull() throws Exception {
- workerDao.removeWorker("ws1", null);
- }
-
- @Test(expectedExceptions = ServerException.class)
- public void shouldThrowNotFoundExceptionOnRemoveIfWorkerWithSuchWorkspaceIdDoesNotExist()
- throws Exception {
- workerDao.removeWorker("unexisted_ws", "user1");
- }
-
- @Test(expectedExceptions = ServerException.class)
- public void shouldThrowNotFoundExceptionOnRemoveIfWorkerWithSuchUserIdDoesNotExist()
- throws Exception {
- workerDao.removeWorker("ws1", "unexisted_user");
- }
-
- public static class TestDomain extends AbstractPermissionsDomain {
- public TestDomain() {
- super("workspace", Arrays.asList("read", "write", "use", "delete"));
- }
-
- @Override
- protected WorkerImpl doCreateInstance(
- String userId, String instanceId, List allowedActions) {
- return new WorkerImpl(userId, instanceId, allowedActions);
- }
- }
-
- private static T notFoundToNull(Callable action) throws Exception {
- try {
- return action.call();
- } catch (NotFoundException x) {
- return null;
- }
- }
-}
diff --git a/multiuser/pom.xml b/multiuser/pom.xml
index 0d85c0dc26..276fcd35a4 100644
--- a/multiuser/pom.xml
+++ b/multiuser/pom.xml
@@ -31,7 +31,6 @@
keycloak
machine-auth
personal-account
- integration-tests
oidc
diff --git a/pom.xml b/pom.xml
index 471c1c5899..92409d614e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -37,7 +37,6 @@
wsmaster
multiuser
infrastructures
- wsmaster/integration-tests
assembly
diff --git a/wsmaster/che-core-api-account/pom.xml b/wsmaster/che-core-api-account/pom.xml
index eac294c4ca..0ca867e766 100644
--- a/wsmaster/che-core-api-account/pom.xml
+++ b/wsmaster/che-core-api-account/pom.xml
@@ -22,10 +22,6 @@
che-core-api-account
Che Core :: API :: Account
-
- com.google.inject
- guice
-
jakarta.inject
jakarta.inject-api
@@ -47,11 +43,6 @@
guice-persist
provided
-
- org.eclipse.che.core
- che-core-db
- provided
-
org.eclipse.persistence
jakarta.persistence
@@ -82,11 +73,6 @@
che-core-commons-test
test
-
- org.eclipse.che.core
- che-core-db-vendor-h2
- test
-
org.eclipse.che.core
che-core-sql-schema
diff --git a/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/api/AccountManager.java b/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/api/AccountManager.java
index 667dc796a2..2ab1ff39dc 100644
--- a/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/api/AccountManager.java
+++ b/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/api/AccountManager.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2022 Red Hat, Inc.
+ * Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
@@ -15,10 +15,7 @@ import static java.util.Objects.requireNonNull;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.eclipse.che.account.event.BeforeAccountRemovedEvent;
import org.eclipse.che.account.shared.model.Account;
-import org.eclipse.che.account.spi.AccountDao;
-import org.eclipse.che.account.spi.AccountImpl;
import org.eclipse.che.api.core.ConflictException;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.ServerException;
@@ -32,13 +29,10 @@ import org.eclipse.che.api.core.notification.EventService;
@Deprecated
@Singleton
public class AccountManager {
-
- private final AccountDao accountDao;
private final EventService eventService;
@Inject
- public AccountManager(AccountDao accountDao, EventService eventService) {
- this.accountDao = accountDao;
+ public AccountManager(EventService eventService) {
this.eventService = eventService;
}
@@ -65,7 +59,6 @@ public class AccountManager {
*/
public void update(Account account) throws NotFoundException, ConflictException, ServerException {
requireNonNull(account, "Required non-null account");
- accountDao.update(new AccountImpl(account));
}
/**
@@ -79,7 +72,7 @@ public class AccountManager {
*/
public Account getById(String id) throws NotFoundException, ServerException {
requireNonNull(id, "Required non-null account id");
- return accountDao.getById(id);
+ return null;
}
/**
@@ -93,7 +86,7 @@ public class AccountManager {
*/
public Account getByName(String name) throws NotFoundException, ServerException {
requireNonNull(name, "Required non-null account name");
- return accountDao.getByName(name);
+ return null;
}
/**
@@ -105,12 +98,5 @@ public class AccountManager {
*/
public void remove(String id) throws ServerException {
requireNonNull(id, "Required non-null account id");
- try {
- AccountImpl toRemove = accountDao.getById(id);
- eventService.publish(new BeforeAccountRemovedEvent(toRemove)).propagateException();
- accountDao.remove(id);
- } catch (NotFoundException ignored) {
- // account is already removed
- }
}
}
diff --git a/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/api/AccountModule.java b/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/api/AccountModule.java
deleted file mode 100644
index 3d40459885..0000000000
--- a/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/api/AccountModule.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) 2012-2018 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.account.api;
-
-import com.google.inject.AbstractModule;
-import org.eclipse.che.account.spi.AccountDao;
-import org.eclipse.che.account.spi.jpa.JpaAccountDao;
-
-/** @author Sergii Leschenko */
-public class AccountModule extends AbstractModule {
- @Override
- protected void configure() {
- bind(AccountDao.class).to(JpaAccountDao.class);
- }
-}
diff --git a/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/event/BeforeAccountRemovedEvent.java b/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/event/BeforeAccountRemovedEvent.java
deleted file mode 100644
index 7c7b9b8e01..0000000000
--- a/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/event/BeforeAccountRemovedEvent.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2012-2018 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.account.event;
-
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.core.db.cascade.event.RemoveEvent;
-
-/**
- * Published before {@link AccountImpl account} removed.
- *
- * @author Antona Korneta
- */
-public class BeforeAccountRemovedEvent extends RemoveEvent {
-
- private final AccountImpl account;
-
- public BeforeAccountRemovedEvent(AccountImpl account) {
- this.account = account;
- }
-
- /** Returns account which is going to be removed. */
- public AccountImpl getAccount() {
- return account;
- }
-}
diff --git a/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/spi/jpa/JpaAccountDao.java b/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/spi/jpa/JpaAccountDao.java
deleted file mode 100644
index 15e75a15c7..0000000000
--- a/wsmaster/che-core-api-account/src/main/java/org/eclipse/che/account/spi/jpa/JpaAccountDao.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (c) 2012-2018 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.account.spi.jpa;
-
-import static java.lang.String.format;
-import static java.util.Objects.requireNonNull;
-
-import com.google.inject.persist.Transactional;
-import javax.inject.Inject;
-import javax.inject.Provider;
-import javax.inject.Singleton;
-import javax.persistence.EntityManager;
-import javax.persistence.NoResultException;
-import org.eclipse.che.account.spi.AccountDao;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.core.ConflictException;
-import org.eclipse.che.api.core.NotFoundException;
-import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.core.db.jpa.DuplicateKeyException;
-
-/**
- * JPA based implementation of {@link AccountDao}.
- *
- * @author Sergii Leschenko
- */
-@Singleton
-public class JpaAccountDao implements AccountDao {
- private final Provider managerProvider;
-
- @Inject
- public JpaAccountDao(Provider managerProvider) {
- this.managerProvider = managerProvider;
- }
-
- @Override
- public void create(AccountImpl account) throws ConflictException, ServerException {
- requireNonNull(account, "Required non-null account");
- try {
- doCreate(account);
- } catch (DuplicateKeyException e) {
- throw new ConflictException("Account with such id or name already exists");
- } catch (RuntimeException e) {
- throw new ServerException(e.getLocalizedMessage(), e);
- }
- }
-
- @Override
- public void update(AccountImpl account)
- throws NotFoundException, ConflictException, ServerException {
- requireNonNull(account, "Required non-null account");
- try {
- doUpdate(account);
- } catch (DuplicateKeyException x) {
- throw new ConflictException("Account with such name already exists");
- } catch (RuntimeException x) {
- throw new ServerException(x.getLocalizedMessage(), x);
- }
- }
-
- @Override
- @Transactional
- public AccountImpl getById(String id) throws NotFoundException, ServerException {
- requireNonNull(id, "Required non-null account id");
- final EntityManager manager = managerProvider.get();
- try {
- AccountImpl account = manager.find(AccountImpl.class, id);
- if (account == null) {
- throw new NotFoundException(format("Account with id '%s' was not found", id));
- }
- return account;
- } catch (RuntimeException x) {
- throw new ServerException(x.getLocalizedMessage(), x);
- }
- }
-
- @Override
- @Transactional
- public AccountImpl getByName(String name) throws ServerException, NotFoundException {
- requireNonNull(name, "Required non-null account name");
- final EntityManager manager = managerProvider.get();
- try {
- return manager
- .createNamedQuery("Account.getByName", AccountImpl.class)
- .setParameter("name", name)
- .getSingleResult();
- } catch (NoResultException e) {
- throw new NotFoundException(String.format("Account with name '%s' was not found", name));
- } catch (RuntimeException e) {
- throw new ServerException(e.getLocalizedMessage(), e);
- }
- }
-
- @Override
- public void remove(String id) throws ServerException {
- requireNonNull(id, "Required non-null account id");
- try {
- doRemove(id);
- } catch (RuntimeException e) {
- throw new ServerException(e.getLocalizedMessage(), e);
- }
- }
-
- @Transactional
- protected void doCreate(AccountImpl account) {
- final EntityManager manager = managerProvider.get();
- manager.persist(account);
- manager.flush();
- }
-
- @Transactional
- protected void doUpdate(AccountImpl update) throws NotFoundException {
- final EntityManager manager = managerProvider.get();
- final AccountImpl account = manager.find(AccountImpl.class, update.getId());
- if (account == null) {
- throw new NotFoundException(
- format("Couldn't update account with id '%s' because it doesn't exist", update.getId()));
- }
- manager.merge(update);
- manager.flush();
- }
-
- @Transactional
- protected void doRemove(String id) {
- final EntityManager manager = managerProvider.get();
- AccountImpl account = manager.find(AccountImpl.class, id);
- if (account != null) {
- manager.remove(account);
- manager.flush();
- }
- }
-}
diff --git a/wsmaster/che-core-api-account/src/test/java/org/eclipse/che/account/spi/tck/AccountDaoTest.java b/wsmaster/che-core-api-account/src/test/java/org/eclipse/che/account/spi/tck/AccountDaoTest.java
deleted file mode 100644
index 053c4f241f..0000000000
--- a/wsmaster/che-core-api-account/src/test/java/org/eclipse/che/account/spi/tck/AccountDaoTest.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (c) 2012-2018 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.account.spi.tck;
-
-import static java.util.Arrays.asList;
-import static org.testng.Assert.assertEquals;
-
-import javax.inject.Inject;
-import org.eclipse.che.account.spi.AccountDao;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.core.ConflictException;
-import org.eclipse.che.api.core.NotFoundException;
-import org.eclipse.che.commons.lang.NameGenerator;
-import org.eclipse.che.commons.test.tck.TckListener;
-import org.eclipse.che.commons.test.tck.repository.TckRepository;
-import org.eclipse.che.commons.test.tck.repository.TckRepositoryException;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Listeners;
-import org.testng.annotations.Test;
-
-/**
- * Tests {@link AccountDao} contract.
- *
- * @author Sergii Leschenko
- */
-@Listeners(TckListener.class)
-@Test(suiteName = AccountDaoTest.SUITE_NAME)
-public class AccountDaoTest {
- public static final String SUITE_NAME = "AccountDaoTck";
-
- private AccountImpl[] accounts;
-
- @Inject private AccountDao accountDao;
-
- @Inject private TckRepository accountRepo;
-
- @BeforeMethod
- private void setUp() throws TckRepositoryException {
- accounts = new AccountImpl[2];
-
- accounts[0] = new AccountImpl(NameGenerator.generate("account", 10), "test1", "test");
- accounts[1] = new AccountImpl(NameGenerator.generate("account", 10), "test2", "test");
-
- accountRepo.createAll(asList(accounts));
- }
-
- @AfterMethod
- private void cleanup() throws TckRepositoryException {
- accountRepo.removeAll();
- }
-
- @Test(dependsOnMethods = "shouldGetAccountById")
- public void shouldCreateAccount() throws Exception {
- AccountImpl toCreate = new AccountImpl("account123", "test123", "test");
-
- accountDao.create(toCreate);
-
- assertEquals(toCreate, accountDao.getById(toCreate.getId()));
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnCreatingNullAccount() throws Exception {
- accountDao.create(null);
- }
-
- @Test(dependsOnMethods = "shouldGetAccountById")
- public void shouldUpdateAccount() throws Exception {
- AccountImpl account = accounts[0];
- account.setName("newName");
- account.setType("newType");
-
- accountDao.update(account);
-
- assertEquals(account, accountDao.getById(account.getId()));
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnUpdatingNullAccount() throws Exception {
- accountDao.update(null);
- }
-
- @Test(expectedExceptions = ConflictException.class)
- public void shouldThrowConflictExceptionWhenUpdatingAccountWithExistingName() throws Exception {
- AccountImpl account = accounts[0];
- account.setName(accounts[1].getName());
-
- accountDao.update(account);
- }
-
- @Test(expectedExceptions = ConflictException.class)
- public void shouldThrowConflictExceptionWhenCreatingAccountWithExistingName() throws Exception {
- AccountImpl account =
- new AccountImpl(NameGenerator.generate("account", 5), accounts[0].getName(), "test");
-
- accountDao.create(account);
- }
-
- @Test(expectedExceptions = NotFoundException.class)
- public void shouldThrowNotFoundExceptionWhenUpdatingNonExistingAccount() throws Exception {
- AccountImpl account = accounts[0];
- account.setId("nonExisting");
-
- accountDao.update(account);
- }
-
- @Test
- public void shouldGetAccountById() throws Exception {
- final AccountImpl account = accounts[0];
-
- final AccountImpl found = accountDao.getById(account.getId());
-
- assertEquals(account, found);
- }
-
- @Test(expectedExceptions = NotFoundException.class)
- public void shouldThrowNotFoundExceptionOnGettingNonExistingAccountById() throws Exception {
- accountDao.getById("non-existing-account");
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnGettingAccountByNullId() throws Exception {
- accountDao.getById(null);
- }
-
- @Test
- public void shouldGetAccountByName() throws Exception {
- final AccountImpl account = accounts[0];
-
- final AccountImpl found = accountDao.getByName(account.getName());
-
- assertEquals(account, found);
- }
-
- @Test(expectedExceptions = NotFoundException.class)
- public void shouldThrowNotFoundExceptionOnGettingNonExistingAccountByName() throws Exception {
- accountDao.getByName("non-existing-account");
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnGettingAccountByNullName() throws Exception {
- accountDao.getByName(null);
- }
-
- @Test(
- dependsOnMethods = "shouldThrowNotFoundExceptionOnGettingNonExistingAccountById",
- expectedExceptions = NotFoundException.class)
- public void shouldRemoveAccount() throws Exception {
- String toRemove = accounts[0].getId();
-
- accountDao.remove(toRemove);
-
- accountDao.getById(toRemove);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnRemovingAccountByNullId() throws Exception {
- accountDao.remove(null);
- }
-}
diff --git a/wsmaster/che-core-api-account/src/test/java/org/eclipse/che/account/spi/tck/jpa/AccountJpaTckModule.java b/wsmaster/che-core-api-account/src/test/java/org/eclipse/che/account/spi/tck/jpa/AccountJpaTckModule.java
deleted file mode 100644
index 450b439e86..0000000000
--- a/wsmaster/che-core-api-account/src/test/java/org/eclipse/che/account/spi/tck/jpa/AccountJpaTckModule.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2012-2018 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.account.spi.tck.jpa;
-
-import com.google.inject.TypeLiteral;
-import org.eclipse.che.account.spi.AccountDao;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.account.spi.jpa.JpaAccountDao;
-import org.eclipse.che.commons.test.db.H2DBTestServer;
-import org.eclipse.che.commons.test.db.H2JpaCleaner;
-import org.eclipse.che.commons.test.db.PersistTestModuleBuilder;
-import org.eclipse.che.commons.test.tck.TckModule;
-import org.eclipse.che.commons.test.tck.TckResourcesCleaner;
-import org.eclipse.che.commons.test.tck.repository.JpaTckRepository;
-import org.eclipse.che.commons.test.tck.repository.TckRepository;
-import org.eclipse.che.core.db.DBInitializer;
-import org.eclipse.che.core.db.h2.jpa.eclipselink.H2ExceptionHandler;
-import org.eclipse.che.core.db.schema.SchemaInitializer;
-import org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer;
-import org.h2.Driver;
-
-/**
- * @author Sergii Leschenko
- * @author Yevhenii Voevodin
- */
-public class AccountJpaTckModule extends TckModule {
- @Override
- protected void configure() {
- H2DBTestServer server = H2DBTestServer.startDefault();
- install(
- new PersistTestModuleBuilder()
- .setDriver(Driver.class)
- .runningOn(server)
- .addEntityClass(AccountImpl.class)
- .setExceptionHandler(H2ExceptionHandler.class)
- .build());
- bind(DBInitializer.class).asEagerSingleton();
- bind(SchemaInitializer.class)
- .toInstance(new FlywaySchemaInitializer(server.getDataSource(), "che-schema"));
- bind(TckResourcesCleaner.class).toInstance(new H2JpaCleaner(server));
-
- bind(new TypeLiteral>() {})
- .toInstance(new JpaTckRepository<>(AccountImpl.class));
-
- bind(AccountDao.class).to(JpaAccountDao.class);
- }
-}
diff --git a/wsmaster/che-core-api-devfile/pom.xml b/wsmaster/che-core-api-devfile/pom.xml
index ffa187cce2..b99e4e3398 100644
--- a/wsmaster/che-core-api-devfile/pom.xml
+++ b/wsmaster/che-core-api-devfile/pom.xml
@@ -35,14 +35,6 @@
com.google.inject
guice
-
- com.google.inject.extensions
- guice-persist
-
-
- jakarta.annotation
- jakarta.annotation-api
-
jakarta.inject
jakarta.inject-api
@@ -87,14 +79,6 @@
org.eclipse.che.core
che-core-commons-lang
-
- org.eclipse.che.core
- che-core-db
-
-
- org.slf4j
- slf4j-api
-
org.eclipse.persistence
jakarta.persistence
@@ -130,11 +114,6 @@
che-core-commons-test
test
-
- org.eclipse.che.core
- che-core-db-vendor-h2
- test
-
org.eclipse.che.core
che-core-sql-schema
diff --git a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/RemoveUserDevfileBeforeAccountRemovedEventSubscriber.java b/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/RemoveUserDevfileBeforeAccountRemovedEventSubscriber.java
deleted file mode 100644
index af3d7380e5..0000000000
--- a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/RemoveUserDevfileBeforeAccountRemovedEventSubscriber.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.api.devfile.server;
-
-import static org.eclipse.che.api.core.Pages.iterate;
-
-import jakarta.annotation.PostConstruct;
-import jakarta.annotation.PreDestroy;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import org.eclipse.che.account.event.BeforeAccountRemovedEvent;
-import org.eclipse.che.api.core.model.workspace.devfile.UserDevfile;
-import org.eclipse.che.api.core.notification.EventService;
-import org.eclipse.che.core.db.cascade.CascadeEventSubscriber;
-
-/**
- * An event listener that is removing all {@link UserDevfile}s that belong to the account that is
- * going to be removed.
- */
-@Singleton
-public class RemoveUserDevfileBeforeAccountRemovedEventSubscriber
- extends CascadeEventSubscriber {
-
- private final EventService eventService;
- private final UserDevfileManager userDevfileManager;
-
- @Inject
- public RemoveUserDevfileBeforeAccountRemovedEventSubscriber(
- EventService eventService, UserDevfileManager userDevfileManager) {
- this.eventService = eventService;
- this.userDevfileManager = userDevfileManager;
- }
-
- @PostConstruct
- public void subscribe() {
- eventService.subscribe(this, BeforeAccountRemovedEvent.class);
- }
-
- @PreDestroy
- public void unsubscribe() {
- eventService.unsubscribe(this, BeforeAccountRemovedEvent.class);
- }
-
- @Override
- public void onCascadeEvent(BeforeAccountRemovedEvent event) throws Exception {
- for (UserDevfile userDevfile :
- iterate(
- (maxItems, skipCount) ->
- userDevfileManager.getByNamespace(
- event.getAccount().getName(), maxItems, skipCount))) {
- userDevfileManager.removeUserDevfile(userDevfile.getId());
- }
- }
-}
diff --git a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/UserDevfileManager.java b/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/UserDevfileManager.java
deleted file mode 100644
index f6d5b3a7bc..0000000000
--- a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/UserDevfileManager.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.api.devfile.server;
-
-import static java.lang.String.format;
-import static java.util.Objects.requireNonNull;
-
-import com.google.common.annotations.Beta;
-import java.util.List;
-import java.util.Optional;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import org.eclipse.che.account.api.AccountManager;
-import org.eclipse.che.api.core.ConflictException;
-import org.eclipse.che.api.core.NotFoundException;
-import org.eclipse.che.api.core.Page;
-import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.api.core.model.workspace.devfile.Devfile;
-import org.eclipse.che.api.core.model.workspace.devfile.UserDevfile;
-import org.eclipse.che.api.core.notification.EventService;
-import org.eclipse.che.api.devfile.server.model.impl.UserDevfileImpl;
-import org.eclipse.che.api.devfile.server.spi.UserDevfileDao;
-import org.eclipse.che.api.devfile.shared.event.DevfileCreatedEvent;
-import org.eclipse.che.api.devfile.shared.event.DevfileUpdatedEvent;
-import org.eclipse.che.commons.env.EnvironmentContext;
-import org.eclipse.che.commons.lang.NameGenerator;
-import org.eclipse.che.commons.lang.Pair;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/** Facade for {@link UserDevfile} related operations. */
-@Beta
-@Singleton
-public class UserDevfileManager {
- private static final Logger LOG = LoggerFactory.getLogger(UserDevfileManager.class);
- private final UserDevfileDao userDevfileDao;
- private final EventService eventService;
- private final AccountManager accountManager;
-
- @Inject
- public UserDevfileManager(
- AccountManager accountManager, UserDevfileDao userDevfileDao, EventService eventService) {
- this.accountManager = accountManager;
- this.userDevfileDao = userDevfileDao;
- this.eventService = eventService;
- }
-
- /**
- * Stores {@link Devfile} instance
- *
- * @param userDevfile instance of user devfile which would be stored
- * @return new persisted devfile instance
- * @throws ConflictException when any conflict occurs (e.g Devfile with such name already exists
- * for {@code owner})
- * @throws NullPointerException when {@code devfile} is null
- * @throws ServerException when any other error occurs
- */
- public UserDevfile createDevfile(UserDevfile userDevfile)
- throws ServerException, NotFoundException, ConflictException {
- requireNonNull(userDevfile, "Required non-null userdevfile");
- requireNonNull(userDevfile.getDevfile(), "Required non-null devfile");
- String name =
- userDevfile.getName() != null
- ? userDevfile.getName()
- : NameGenerator.generate("devfile-", 5);
- UserDevfile result =
- userDevfileDao.create(
- new UserDevfileImpl(
- NameGenerator.generate("id-", 16),
- accountManager.getByName(
- EnvironmentContext.getCurrent().getSubject().getUserName()),
- name,
- userDevfile.getDescription(),
- userDevfile.getDevfile()));
- LOG.debug(
- "UserDevfile '{}' with id '{}' created by user '{}'",
- result.getName(),
- result.getId(),
- EnvironmentContext.getCurrent().getSubject().getUserName());
- eventService.publish(new DevfileCreatedEvent(result));
- return result;
- }
-
- /**
- * Gets UserDevfile by given id.
- *
- * @param id userdevfile identifier
- * @return userdevfile instance
- * @throws NullPointerException when {@code id} is null
- * @throws NotFoundException when userdevfile with given id not found
- * @throws ServerException when any server errors occurs
- */
- public UserDevfile getById(String id) throws NotFoundException, ServerException {
- requireNonNull(id);
- Optional result = userDevfileDao.getById(id);
- return result.orElseThrow(
- () -> new NotFoundException(format("Devfile with id '%s' doesn't exist", id)));
- }
-
- /**
- * Gets list of UserDevfiles in given namespace.
- *
- * @param namespace devfiles namespace
- * @return list of devfiles in given namespace. Always returns list(even when there are no devfile
- * in given namespace), never null
- * @throws NullPointerException when {@code namespace} is null
- * @throws ServerException when any other error occurs during workspaces fetching
- */
- public Page getByNamespace(String namespace, int maxItems, long skipCount)
- throws ServerException {
- requireNonNull(namespace, "Required non-null namespace");
- final Page devfilesPage =
- userDevfileDao.getByNamespace(namespace, maxItems, skipCount);
- return devfilesPage;
- }
- /**
- * Updates an existing user devfile in accordance to the new configuration.
- *
- * Note: Replace strategy is used for user devfile update, it means that existing devfile data
- * will be replaced with given {@code update}.
- *
- * @param update user devfile update
- * @return updated user devfile
- * @throws NullPointerException when {@code update} is null
- * @throws ConflictException when any conflict occurs.
- * @throws NotFoundException when user devfile with given id not found
- * @throws ServerException when any server error occurs
- */
- public UserDevfile updateUserDevfile(UserDevfile update)
- throws ConflictException, NotFoundException, ServerException {
- requireNonNull(update);
- Optional result = userDevfileDao.update(update);
- UserDevfile devfile =
- result.orElseThrow(
- () ->
- new NotFoundException(
- format("Devfile with id '%s' doesn't exist", update.getId())));
- LOG.debug(
- "UserDevfile '{}' with id '{}' update by user '{}'",
- devfile.getName(),
- devfile.getId(),
- EnvironmentContext.getCurrent().getSubject().getUserName());
- eventService.publish(new DevfileUpdatedEvent(devfile));
- return devfile;
- }
-
- /**
- * Removes stored {@link UserDevfile} by given id.
- *
- * @param id user devfile identifier
- * @throws NullPointerException when {@code id} is null
- * @throws ServerException when any server errors occurs
- */
- public void removeUserDevfile(String id) throws ServerException {
- requireNonNull(id);
- userDevfileDao.remove(id);
- LOG.debug(
- "UserDevfile with id '{}' removed by user '{}'",
- id,
- EnvironmentContext.getCurrent().getSubject().getUserName());
- }
-
- /**
- * Gets list of devfiles. Parameters, returned values and possible exceptions are the same as in
- * {@link UserDevfileDao#getDevfiles(int, int, List, List)}
- */
- public Page getUserDevfiles(
- int maxItems,
- int skipCount,
- List> filter,
- List> order)
- throws ServerException {
- return userDevfileDao.getDevfiles(maxItems, skipCount, filter, order);
- }
-}
diff --git a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/event/BeforeDevfileRemovedEvent.java b/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/event/BeforeDevfileRemovedEvent.java
deleted file mode 100644
index 18c9d9e0a9..0000000000
--- a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/event/BeforeDevfileRemovedEvent.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.api.devfile.server.event;
-
-import org.eclipse.che.api.core.model.workspace.devfile.UserDevfile;
-import org.eclipse.che.api.core.notification.EventOrigin;
-import org.eclipse.che.api.devfile.server.model.impl.UserDevfileImpl;
-import org.eclipse.che.core.db.cascade.event.RemoveEvent;
-
-/** Published before {@link UserDevfile user devfile} removed. */
-@EventOrigin("user")
-public class BeforeDevfileRemovedEvent extends RemoveEvent {
-
- private final UserDevfileImpl userDevfile;
-
- public BeforeDevfileRemovedEvent(UserDevfileImpl userDevfile) {
- this.userDevfile = userDevfile;
- }
-
- /** Returns user which is going to be removed. */
- public UserDevfileImpl getUserDevfile() {
- return userDevfile;
- }
-}
diff --git a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/jpa/JpaUserDevfileDao.java b/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/jpa/JpaUserDevfileDao.java
deleted file mode 100644
index c2215ae47d..0000000000
--- a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/jpa/JpaUserDevfileDao.java
+++ /dev/null
@@ -1,401 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.api.devfile.server.jpa;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static java.lang.String.format;
-import static java.util.Collections.emptyList;
-import static java.util.Objects.requireNonNull;
-import static java.util.stream.Collectors.toList;
-import static org.eclipse.che.api.devfile.server.jpa.JpaUserDevfileDao.UserDevfileSearchQueryBuilder.newBuilder;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Supplier;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.inject.persist.Transactional;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.StringJoiner;
-import java.util.stream.Collectors;
-import javax.inject.Inject;
-import javax.inject.Provider;
-import javax.inject.Singleton;
-import javax.persistence.EntityManager;
-import javax.persistence.TypedQuery;
-import org.eclipse.che.account.shared.model.Account;
-import org.eclipse.che.account.spi.AccountDao;
-import org.eclipse.che.api.core.ConflictException;
-import org.eclipse.che.api.core.NotFoundException;
-import org.eclipse.che.api.core.Page;
-import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.api.core.model.workspace.devfile.UserDevfile;
-import org.eclipse.che.api.core.notification.EventService;
-import org.eclipse.che.api.devfile.server.event.BeforeDevfileRemovedEvent;
-import org.eclipse.che.api.devfile.server.model.impl.UserDevfileImpl;
-import org.eclipse.che.api.devfile.server.spi.UserDevfileDao;
-import org.eclipse.che.commons.lang.Pair;
-import org.eclipse.che.core.db.jpa.DuplicateKeyException;
-import org.eclipse.che.core.db.jpa.IntegrityConstraintViolationException;
-
-/** JPA based implementation of {@link UserDevfileDao}. */
-@Singleton
-@Beta
-public class JpaUserDevfileDao implements UserDevfileDao {
-
- protected final Provider managerProvider;
- protected final AccountDao accountDao;
- protected final EventService eventService;
- /** sorting order that would be used by default during search. */
- public static final List> DEFAULT_ORDER =
- ImmutableList.of(new Pair<>("id", "ASC"));
- /** Set of field that is eligible to use for search. */
- public static final Set VALID_SEARCH_FIELDS = ImmutableSet.of("name");
- /** Set of field that is eligible to use for sorting during search. */
- public static final Set VALID_ORDER_FIELDS = ImmutableSet.of("id", "name");
-
- @Inject
- public JpaUserDevfileDao(
- Provider managerProvider, AccountDao accountDao, EventService eventService) {
- this.managerProvider = managerProvider;
- this.accountDao = accountDao;
- this.eventService = eventService;
- }
-
- @Override
- public UserDevfile create(UserDevfile userDevfile) throws ConflictException, ServerException {
- requireNonNull(userDevfile);
- try {
- Account account = accountDao.getByName(userDevfile.getNamespace());
- UserDevfileImpl userDevfileImpl = new UserDevfileImpl(userDevfile, account);
- doCreate(userDevfileImpl);
- return userDevfileImpl;
- } catch (DuplicateKeyException ex) {
- throw new ConflictException(
- format(
- "Devfile with name '%s' already exists in the specified account '%s'",
- userDevfile.getName(), userDevfile.getNamespace()));
- } catch (IntegrityConstraintViolationException ex) {
- throw new ConflictException(
- "Could not create devfile with creator that refers to a non-existent user");
- } catch (RuntimeException ex) {
- throw new ServerException(ex.getMessage(), ex);
- } catch (NotFoundException e) {
- throw new ConflictException(
- format(
- "Not able to create devfile in requested namespace %s bacause it is not found",
- userDevfile.getNamespace()));
- }
- }
-
- @Override
- public Optional update(UserDevfile userDevfile)
- throws ConflictException, ServerException, NotFoundException {
- requireNonNull(userDevfile);
- try {
- Account account = accountDao.getByName(userDevfile.getNamespace());
- return doUpdate(new UserDevfileImpl(userDevfile, account)).map(UserDevfileImpl::new);
- } catch (DuplicateKeyException ex) {
- throw new ConflictException(
- format(
- "Devfile with name '%s' already exists in current account '%s'",
- userDevfile.getName(), userDevfile.getNamespace()));
- } catch (RuntimeException ex) {
- throw new ServerException(ex.getLocalizedMessage(), ex);
- }
- }
-
- @Override
- public void remove(String id) throws ServerException {
- requireNonNull(id);
- try {
- doRemove(id);
- } catch (RuntimeException ex) {
- throw new ServerException(ex.getLocalizedMessage(), ex);
- }
- }
-
- @Override
- @Transactional(rollbackOn = {ServerException.class, RuntimeException.class})
- public Optional getById(String id) throws ServerException {
- requireNonNull(id);
- try {
- final UserDevfileImpl devfile = managerProvider.get().find(UserDevfileImpl.class, id);
- if (devfile == null) {
- return Optional.empty();
- }
- return Optional.of(new UserDevfileImpl(devfile));
- } catch (RuntimeException ex) {
- throw new ServerException(ex.getLocalizedMessage(), ex);
- }
- }
-
- @Transactional(rollbackOn = {ServerException.class, RuntimeException.class})
- @Override
- public Page getByNamespace(String namespace, int maxItems, long skipCount)
- throws ServerException {
- requireNonNull(namespace, "Required non-null namespace");
- try {
- final EntityManager manager = managerProvider.get();
- final List list =
- manager
- .createNamedQuery("UserDevfile.getByNamespace", UserDevfileImpl.class)
- .setParameter("namespace", namespace)
- .setMaxResults(maxItems)
- .setFirstResult((int) skipCount)
- .getResultList()
- .stream()
- .map(UserDevfileImpl::new)
- .collect(Collectors.toList());
- final long count =
- manager
- .createNamedQuery("UserDevfile.getByNamespaceCount", Long.class)
- .setParameter("namespace", namespace)
- .getSingleResult();
- return new Page<>(list, skipCount, maxItems, count);
- } catch (RuntimeException x) {
- throw new ServerException(x.getLocalizedMessage(), x);
- }
- }
-
- @Override
- @Transactional(rollbackOn = {ServerException.class})
- public Page getDevfiles(
- int maxItems,
- int skipCount,
- List> filter,
- List> order)
- throws ServerException {
-
- checkArgument(maxItems > 0, "The number of items has to be positive.");
- checkArgument(
- skipCount >= 0,
- "The number of items to skip can't be negative or greater than " + Integer.MAX_VALUE);
-
- return doGetDevfiles(
- maxItems, skipCount, filter, order, () -> newBuilder(managerProvider.get()));
- }
-
- @Transactional(rollbackOn = {ServerException.class})
- protected Page doGetDevfiles(
- int maxItems,
- int skipCount,
- List> filter,
- List> order,
- Supplier queryBuilderSupplier)
- throws ServerException {
- if (filter != null && !filter.isEmpty()) {
- List> invalidFilter =
- filter.stream()
- .filter(p -> !VALID_SEARCH_FIELDS.contains(p.first.toLowerCase()))
- .collect(toList());
- if (!invalidFilter.isEmpty()) {
- throw new IllegalArgumentException(
- "Filtering allowed only by " + VALID_SEARCH_FIELDS + " but got: " + invalidFilter);
- }
- }
- List> effectiveOrder = DEFAULT_ORDER;
- if (order != null && !order.isEmpty()) {
- List> invalidOrder =
- order.stream()
- .filter(p -> !VALID_ORDER_FIELDS.contains(p.first.toLowerCase()))
- .collect(toList());
- if (!invalidOrder.isEmpty()) {
- throw new IllegalArgumentException(
- "Order allowed only by " + VALID_ORDER_FIELDS + "¬ but got: " + invalidOrder);
- }
-
- List> invalidSortOrder =
- order.stream()
- .filter(p -> !p.second.equalsIgnoreCase("asc") && !p.second.equalsIgnoreCase("desc"))
- .collect(Collectors.toList());
- if (!invalidSortOrder.isEmpty()) {
- throw new IllegalArgumentException(
- "Invalid sort order direction. Possible values are 'asc' or 'desc' but got: "
- + invalidSortOrder);
- }
- effectiveOrder = order;
- }
- try {
- final long count =
- queryBuilderSupplier.get().withFilter(filter).buildCountQuery().getSingleResult();
-
- if (count == 0) {
- return new Page<>(emptyList(), skipCount, maxItems, count);
- }
- List result =
- queryBuilderSupplier
- .get()
- .withFilter(filter)
- .withOrder(effectiveOrder)
- .withMaxItems(maxItems)
- .withSkipCount(skipCount)
- .buildSelectItemsQuery()
- .getResultList()
- .stream()
- .map(UserDevfileImpl::new)
- .collect(toList());
- return new Page<>(result, skipCount, maxItems, count);
-
- } catch (RuntimeException x) {
- throw new ServerException(x.getLocalizedMessage(), x);
- }
- }
-
- @Override
- @Transactional
- public long getTotalCount() throws ServerException {
- try {
- return managerProvider
- .get()
- .createNamedQuery("UserDevfile.getTotalCount", Long.class)
- .getSingleResult();
- } catch (RuntimeException x) {
- throw new ServerException(x.getLocalizedMessage(), x);
- }
- }
-
- @Transactional
- protected void doCreate(UserDevfileImpl devfile) {
- final EntityManager manager = managerProvider.get();
- manager.persist(devfile);
- manager.flush();
- }
-
- @Transactional
- protected Optional doUpdate(UserDevfileImpl update) {
- final EntityManager manager = managerProvider.get();
- if (manager.find(UserDevfileImpl.class, update.getId()) == null) {
- return Optional.empty();
- }
- UserDevfileImpl merged = manager.merge(update);
- manager.flush();
- return Optional.of(merged);
- }
-
- @Transactional(rollbackOn = {RuntimeException.class, ServerException.class})
- protected void doRemove(String id) throws ServerException {
- final EntityManager manager = managerProvider.get();
- final UserDevfileImpl devfile = manager.find(UserDevfileImpl.class, id);
- if (devfile != null) {
- eventService
- .publish(new BeforeDevfileRemovedEvent(new UserDevfileImpl(devfile)))
- .propagateException();
- manager.remove(devfile);
- manager.flush();
- }
- }
-
- public static class UserDevfileSearchQueryBuilder {
- protected EntityManager entityManager;
- protected int maxItems;
- protected int skipCount;
- protected String filter;
- protected Map params;
- protected String order;
-
- public UserDevfileSearchQueryBuilder(EntityManager entityManager) {
- this.entityManager = entityManager;
- this.params = new HashMap<>();
- this.filter = "";
- this.order = "";
- }
-
- public static UserDevfileSearchQueryBuilder newBuilder(EntityManager entityManager) {
- return new JpaUserDevfileDao.UserDevfileSearchQueryBuilder(entityManager);
- }
-
- public UserDevfileSearchQueryBuilder withMaxItems(int maxItems) {
- this.maxItems = maxItems;
- return this;
- }
-
- public UserDevfileSearchQueryBuilder withSkipCount(int skipCount) {
- this.skipCount = skipCount;
- return this;
- }
-
- public UserDevfileSearchQueryBuilder withFilter(List> filter) {
- if (filter == null || filter.isEmpty()) {
- return this;
- }
- final StringJoiner matcher = new StringJoiner(" AND ", " WHERE ", " ");
- int i = 0;
- for (Pair attribute : filter) {
- if (!VALID_SEARCH_FIELDS.contains(attribute.first.toLowerCase())) {
- throw new IllegalArgumentException(
- "Filtering allowed only by " + VALID_SEARCH_FIELDS + " but got: " + attribute.first);
- }
- final String parameterName = "parameterName" + i++;
- if (attribute.second.startsWith("like:")) {
- params.put(parameterName, attribute.second.substring(5));
- matcher.add("userdevfile." + attribute.first + " LIKE :" + parameterName);
- } else {
- params.put(parameterName, attribute.second);
- matcher.add("userdevfile." + attribute.first + " = :" + parameterName);
- }
- }
- this.filter = matcher.toString();
- return this;
- }
-
- public UserDevfileSearchQueryBuilder withOrder(List> order) {
- if (order == null || order.isEmpty()) {
- return this;
- }
- final StringJoiner matcher = new StringJoiner(", ", " ORDER BY ", " ");
- for (Pair pair : order) {
- if (!VALID_ORDER_FIELDS.contains(pair.first.toLowerCase())) {
- throw new IllegalArgumentException(
- "Order allowed only by " + VALID_ORDER_FIELDS + " but got: " + pair.first);
- }
- matcher.add("userdevfile." + pair.first + " " + pair.second);
- }
- this.order = matcher.toString();
-
- return this;
- }
-
- public TypedQuery buildCountQuery() {
- StringBuilder query =
- new StringBuilder()
- .append("SELECT ")
- .append(" COUNT(userdevfile) ")
- .append("FROM UserDevfile userdevfile")
- .append(filter);
- TypedQuery typedQuery = entityManager.createQuery(query.toString(), Long.class);
- params.forEach((k, v) -> typedQuery.setParameter(k, v));
- return typedQuery;
- }
-
- public TypedQuery buildSelectItemsQuery() {
-
- StringBuilder query =
- new StringBuilder()
- .append("SELECT ")
- .append(" userdevfile ")
- .append("FROM UserDevfile userdevfile")
- .append(filter)
- .append(order);
- TypedQuery typedQuery =
- entityManager
- .createQuery(query.toString(), UserDevfileImpl.class)
- .setFirstResult(skipCount)
- .setMaxResults(maxItems);
- params.forEach((k, v) -> typedQuery.setParameter(k, v));
- return typedQuery;
- }
- }
-}
diff --git a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/jpa/UserDevfileJpaModule.java b/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/jpa/UserDevfileJpaModule.java
deleted file mode 100644
index f3d392e4c6..0000000000
--- a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/jpa/UserDevfileJpaModule.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.api.devfile.server.jpa;
-
-import com.google.common.annotations.Beta;
-import com.google.inject.AbstractModule;
-import org.eclipse.che.api.devfile.server.RemoveUserDevfileBeforeAccountRemovedEventSubscriber;
-import org.eclipse.che.api.devfile.server.spi.UserDevfileDao;
-
-@Beta
-public class UserDevfileJpaModule extends AbstractModule {
- @Override
- protected void configure() {
- bind(UserDevfileDao.class).to(JpaUserDevfileDao.class);
- bind(RemoveUserDevfileBeforeAccountRemovedEventSubscriber.class).asEagerSingleton();
- }
-}
diff --git a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/spi/UserDevfileDao.java b/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/spi/UserDevfileDao.java
deleted file mode 100644
index 7785bf7e68..0000000000
--- a/wsmaster/che-core-api-devfile/src/main/java/org/eclipse/che/api/devfile/server/spi/UserDevfileDao.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.api.devfile.server.spi;
-
-import com.google.common.annotations.Beta;
-import java.util.List;
-import java.util.Optional;
-import org.eclipse.che.api.core.ConflictException;
-import org.eclipse.che.api.core.NotFoundException;
-import org.eclipse.che.api.core.Page;
-import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.api.core.model.workspace.devfile.UserDevfile;
-import org.eclipse.che.commons.lang.Pair;
-
-/** Defines data access object contract for {@code UserDevfileImpl}. */
-@Beta
-public interface UserDevfileDao {
-
- /**
- * Creates Devfile.
- *
- * @param devfile devfile to create
- * @return created devfile
- * @throws NullPointerException when {@code devfile} is null
- * @throws ServerException when any other error occurs
- * @throws ConflictException when required namespace is not found.
- */
- UserDevfile create(UserDevfile devfile) throws ServerException, ConflictException;
-
- /**
- * Updates devfile to the new entity, using replacement strategy.
- *
- * @param devfile devfile to update
- * @return updated devfile
- * @throws NullPointerException when {@code devfile} is null
- * @throws ConflictException when any conflict situation occurs
- * @throws ServerException when any other error occurs
- */
- Optional update(UserDevfile devfile)
- throws ConflictException, ServerException, NotFoundException;
-
- /**
- * Removes devfile.
- *
- * @param id devfile identifier
- * @throws NullPointerException when {@code id} is null
- * @throws ServerException when any other error occurs
- */
- void remove(String id) throws ServerException;
-
- /**
- * Gets devfile by identifier.
- *
- * @param id devfile identifier
- * @return devfile instance, never null
- * @throws NullPointerException when {@code id} is null
- * @throws ServerException when any other error occurs
- */
- Optional getById(String id) throws ServerException;
-
- /**
- * Gets list of UserDevfiles in given namespace.
- *
- * @param namespace devfiles namespace
- * @return list of devfiles in given namespace. Always returns list(even when there are no devfile
- * in given namespace), never null
- * @throws NullPointerException when {@code namespace} is null
- * @throws ServerException when any other error occurs during workspaces fetching
- */
- Page getByNamespace(String namespace, int maxItems, long skipCount)
- throws ServerException;
-
- /**
- * Gets all devfiles which user can read filtered by given parameters in a given order
- *
- * @param maxItems the maximum number of workspaces to return
- * @param skipCount the number of workspaces to skip
- * @param filter additional conditions for the desired devfiles. Conditions represented as pairs
- * of the filed and the value. All pairs would be joined with AND condition. Value of
- * the pair can start with 'like:' prefix. In this case would be used LIKE query,
- * otherwise = condition.
- * @param order - a list of fields and directions of sort. By default items would be sorted by id.
- * @return list of devfiles which user can read, never null
- * @throws ServerException when any other error occurs during devfile fetching
- * @throws IllegalArgumentException when maxItems < 1 or skipCount < 0 or sort order is not 'asc'
- * or 'desc'.
- */
- Page getDevfiles(
- int maxItems,
- int skipCount,
- List> filter,
- List> order)
- throws ServerException;
-
- /**
- * Get the count of all user devfiles from the persistent layer.
- *
- * @return workspace count
- * @throws ServerException when any error occurs
- */
- long getTotalCount() throws ServerException;
-}
diff --git a/wsmaster/che-core-api-devfile/src/test/java/org/eclipse/che/api/devfile/server/UserDevfileManagerTest.java b/wsmaster/che-core-api-devfile/src/test/java/org/eclipse/che/api/devfile/server/UserDevfileManagerTest.java
deleted file mode 100644
index 2c7dc1e428..0000000000
--- a/wsmaster/che-core-api-devfile/src/test/java/org/eclipse/che/api/devfile/server/UserDevfileManagerTest.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.api.devfile.server;
-
-import static com.google.common.base.Strings.isNullOrEmpty;
-import static java.util.Arrays.asList;
-import static org.eclipse.che.api.devfile.server.TestObjectGenerator.TEST_ACCOUNT;
-import static org.eclipse.che.api.devfile.server.TestObjectGenerator.TEST_CHE_NAMESPACE;
-import static org.eclipse.che.api.devfile.server.TestObjectGenerator.createUserDevfile;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.lenient;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-
-import java.util.Collections;
-import java.util.Optional;
-import org.eclipse.che.account.api.AccountManager;
-import org.eclipse.che.api.core.NotFoundException;
-import org.eclipse.che.api.core.Page;
-import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.api.core.model.workspace.devfile.UserDevfile;
-import org.eclipse.che.api.core.notification.EventService;
-import org.eclipse.che.api.devfile.server.model.impl.UserDevfileImpl;
-import org.eclipse.che.api.devfile.server.spi.UserDevfileDao;
-import org.eclipse.che.api.devfile.shared.event.DevfileCreatedEvent;
-import org.eclipse.che.api.devfile.shared.event.DevfileDeletedEvent;
-import org.eclipse.che.api.devfile.shared.event.DevfileUpdatedEvent;
-import org.eclipse.che.commons.env.EnvironmentContext;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.testng.MockitoTestNGListener;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Listeners;
-import org.testng.annotations.Test;
-
-@Listeners(value = MockitoTestNGListener.class)
-public class UserDevfileManagerTest {
- @Mock UserDevfileDao userDevfileDao;
- @Mock EventService eventService;
- @Mock AccountManager accountManager;
- @InjectMocks UserDevfileManager userDevfileManager;
-
- @Captor private ArgumentCaptor userDevfileArgumentCaptor;
- @Captor private ArgumentCaptor devfileCreatedEventCaptor;
- @Captor private ArgumentCaptor devfileDeletedEventCaptor;
- @Captor private ArgumentCaptor devfileUpdatedEventCaptor;
-
- @BeforeMethod
- public void setUp() throws Exception {
- EnvironmentContext.getCurrent().setSubject(TestObjectGenerator.TEST_SUBJECT);
- lenient().doReturn(TEST_ACCOUNT).when(accountManager).getByName(eq(TEST_CHE_NAMESPACE));
- }
-
- @Test
- public void shouldGenerateUserDevfileIdOnCreation() throws Exception {
- // given
- final UserDevfileImpl userDevfile =
- new UserDevfileImpl(null, TEST_ACCOUNT, createUserDevfile());
- when(userDevfileDao.create(any(UserDevfileImpl.class)))
- .thenAnswer(invocationOnMock -> invocationOnMock.getArguments()[0]);
- // when
- UserDevfile actual = userDevfileManager.createDevfile(userDevfile);
- // then
- verify(userDevfileDao).create(userDevfileArgumentCaptor.capture());
- assertFalse(isNullOrEmpty(userDevfileArgumentCaptor.getValue().getId()));
- assertEquals(new UserDevfileImpl(null, TEST_ACCOUNT, actual), userDevfile);
- }
-
- @Test
- public void shouldSendDevfileCreatedEventOnCreation() throws Exception {
- // given
- final UserDevfileImpl userDevfile =
- new UserDevfileImpl(null, TEST_ACCOUNT, createUserDevfile());
- when(userDevfileDao.create(any(UserDevfileImpl.class)))
- .thenAnswer(invocationOnMock -> invocationOnMock.getArguments()[0]);
- // when
- UserDevfile expected = userDevfileManager.createDevfile(userDevfile);
- // then
- verify(eventService).publish(devfileCreatedEventCaptor.capture());
- assertEquals(expected, devfileCreatedEventCaptor.getValue().getUserDevfile());
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenGettingUserDevfileByNullId() throws Exception {
- userDevfileManager.getById(null);
- }
-
- @Test
- public void shouldGetUserDevfileById() throws Exception {
- // given
- final Optional toFetch = Optional.of(createUserDevfile());
- when(userDevfileDao.getById(eq("id123"))).thenReturn(toFetch);
-
- // when
- final UserDevfile fetched = userDevfileManager.getById("id123");
- // then
- assertEquals(fetched, toFetch.get());
- verify(userDevfileDao).getById("id123");
- }
-
- @Test(
- expectedExceptions = NotFoundException.class,
- expectedExceptionsMessageRegExp = "Devfile with id 'id123' doesn't exist")
- public void shouldThrowNotFoundExceptionOnGetUserDevfileByIdIfNotFound() throws Exception {
- // given
- doReturn(Optional.empty()).when(userDevfileDao).getById(eq("id123"));
- // when
- userDevfileManager.getById("id123");
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenUpdatingUserDevfileByNullId() throws Exception {
- userDevfileManager.updateUserDevfile(null);
- }
-
- @Test
- public void shouldUpdateUserDevfile() throws Exception {
- // given
- final UserDevfileImpl userDevfile = createUserDevfile();
- when(userDevfileDao.update(any(UserDevfileImpl.class)))
- .thenAnswer(invocationOnMock -> Optional.of(invocationOnMock.getArguments()[0]));
- // when
- userDevfileManager.updateUserDevfile(userDevfile);
- // then
- verify(userDevfileDao).update(eq(userDevfile));
- }
-
- @Test(expectedExceptions = NotFoundException.class)
- public void shouldThrowNotFoundIfUserDevfileIsNotFoundOnUpdate() throws Exception {
- // given
- final UserDevfileImpl userDevfile = createUserDevfile();
- Mockito.doReturn(Optional.empty()).when(userDevfileDao).update(any(UserDevfileImpl.class));
- // when
- userDevfileManager.updateUserDevfile(userDevfile);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhendeleteUserDevfileByNullId() throws Exception {
- userDevfileManager.removeUserDevfile(null);
- }
-
- @Test
- public void shouldRemoveUserDevfile() throws Exception {
- // given
- final UserDevfileImpl userDevfile = createUserDevfile();
- // when
- userDevfileManager.removeUserDevfile(userDevfile.getId());
- // then
- verify(userDevfileDao).remove(userDevfile.getId());
- }
-
- @Test
- public void shouldSendDevfileUpdatedEventOnUpdateDevfile() throws Exception {
- // given
- final UserDevfileImpl userDevfile = createUserDevfile();
- when(userDevfileDao.update(any(UserDevfileImpl.class)))
- .thenAnswer(invocationOnMock -> Optional.of(invocationOnMock.getArguments()[0]));
- // when
- userDevfileManager.updateUserDevfile(userDevfile);
- // then
- verify(eventService).publish(devfileUpdatedEventCaptor.capture());
- assertEquals(userDevfile, devfileUpdatedEventCaptor.getValue().getUserDevfile());
- }
-
- @Test
- public void shouldBeAbleToGetUserDevfilesAvailableToUser() throws ServerException {
- // given
- final UserDevfileImpl userDevfile = createUserDevfile();
- final UserDevfileImpl userDevfile2 = createUserDevfile();
- when(userDevfileDao.getDevfiles(2, 30, Collections.emptyList(), Collections.emptyList()))
- .thenReturn(new Page<>(asList(userDevfile, userDevfile2), 0, 2, 2));
- // when
- Page actual =
- userDevfileManager.getUserDevfiles(2, 30, Collections.emptyList(), Collections.emptyList());
- // then
- assertEquals(actual.getItems().size(), 2);
- }
-}
diff --git a/wsmaster/che-core-api-devfile/src/test/java/org/eclipse/che/api/devfile/server/jpa/UserDevfileTckModule.java b/wsmaster/che-core-api-devfile/src/test/java/org/eclipse/che/api/devfile/server/jpa/UserDevfileTckModule.java
index 56ea718e13..458370da97 100644
--- a/wsmaster/che-core-api-devfile/src/test/java/org/eclipse/che/api/devfile/server/jpa/UserDevfileTckModule.java
+++ b/wsmaster/che-core-api-devfile/src/test/java/org/eclipse/che/api/devfile/server/jpa/UserDevfileTckModule.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
+ * Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
@@ -12,72 +12,18 @@
package org.eclipse.che.api.devfile.server.jpa;
import com.google.inject.TypeLiteral;
-import org.eclipse.che.account.spi.AccountDao;
import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.account.spi.jpa.JpaAccountDao;
import org.eclipse.che.api.devfile.server.model.impl.UserDevfileImpl;
-import org.eclipse.che.api.devfile.server.spi.UserDevfileDao;
import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.api.workspace.server.devfile.SerializableConverter;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ActionImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.CommandImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ComponentImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.DevfileImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.EndpointImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.EntrypointImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.EnvImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ProjectImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.SourceImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.VolumeImpl;
-import org.eclipse.che.commons.test.db.H2DBTestServer;
-import org.eclipse.che.commons.test.db.H2JpaCleaner;
-import org.eclipse.che.commons.test.db.PersistTestModuleBuilder;
import org.eclipse.che.commons.test.tck.TckModule;
-import org.eclipse.che.commons.test.tck.TckResourcesCleaner;
import org.eclipse.che.commons.test.tck.repository.JpaTckRepository;
import org.eclipse.che.commons.test.tck.repository.TckRepository;
-import org.eclipse.che.core.db.DBInitializer;
-import org.eclipse.che.core.db.h2.jpa.eclipselink.H2ExceptionHandler;
-import org.eclipse.che.core.db.schema.SchemaInitializer;
-import org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer;
-import org.h2.Driver;
/** Tck module for UserDevfile test. */
public class UserDevfileTckModule extends TckModule {
@Override
protected void configure() {
- H2DBTestServer server = H2DBTestServer.startDefault();
- install(
- new PersistTestModuleBuilder()
- .setDriver(Driver.class)
- .runningOn(server)
- .addEntityClasses(
- UserImpl.class,
- AccountImpl.class,
- UserDevfileImpl.class,
- DevfileImpl.class,
- ActionImpl.class,
- CommandImpl.class,
- ComponentImpl.class,
- DevfileImpl.class,
- EndpointImpl.class,
- EntrypointImpl.class,
- EnvImpl.class,
- ProjectImpl.class,
- SourceImpl.class,
- VolumeImpl.class)
- .addClass(SerializableConverter.class)
- .setExceptionHandler(H2ExceptionHandler.class)
- .setProperty("eclipselink.logging.level", "OFF")
- .build());
- bind(DBInitializer.class).asEagerSingleton();
- bind(SchemaInitializer.class)
- .toInstance(new FlywaySchemaInitializer(server.getDataSource(), "che-schema"));
- bind(TckResourcesCleaner.class).toInstance(new H2JpaCleaner(server));
-
- bind(UserDevfileDao.class).to(JpaUserDevfileDao.class);
- bind(AccountDao.class).to(JpaAccountDao.class);
bind(new TypeLiteral>() {})
.toInstance(new JpaTckRepository<>(UserDevfileImpl.class));
diff --git a/wsmaster/che-core-api-devfile/src/test/java/org/eclipse/che/api/devfile/server/spi/tck/UserDevfileDaoTest.java b/wsmaster/che-core-api-devfile/src/test/java/org/eclipse/che/api/devfile/server/spi/tck/UserDevfileDaoTest.java
deleted file mode 100644
index 84446728a4..0000000000
--- a/wsmaster/che-core-api-devfile/src/test/java/org/eclipse/che/api/devfile/server/spi/tck/UserDevfileDaoTest.java
+++ /dev/null
@@ -1,589 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.api.devfile.server.spi.tck;
-
-import static java.lang.Math.min;
-import static java.util.Arrays.asList;
-import static java.util.stream.Collectors.toList;
-import static org.eclipse.che.api.devfile.server.TestObjectGenerator.createUserDevfile;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertTrue;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.Optional;
-import java.util.stream.Stream;
-import javax.inject.Inject;
-import javax.inject.Provider;
-import javax.persistence.EntityManager;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.core.ConflictException;
-import org.eclipse.che.api.core.NotFoundException;
-import org.eclipse.che.api.core.Page;
-import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.api.core.model.workspace.devfile.UserDevfile;
-import org.eclipse.che.api.core.notification.EventService;
-import org.eclipse.che.api.devfile.server.TestObjectGenerator;
-import org.eclipse.che.api.devfile.server.event.BeforeDevfileRemovedEvent;
-import org.eclipse.che.api.devfile.server.jpa.JpaUserDevfileDao;
-import org.eclipse.che.api.devfile.server.model.impl.UserDevfileImpl;
-import org.eclipse.che.api.devfile.server.spi.UserDevfileDao;
-import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ActionImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.CommandImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ComponentImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.DevfileImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.MetadataImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.ProjectImpl;
-import org.eclipse.che.api.workspace.server.model.impl.devfile.SourceImpl;
-import org.eclipse.che.commons.lang.NameGenerator;
-import org.eclipse.che.commons.lang.Pair;
-import org.eclipse.che.commons.test.tck.TckListener;
-import org.eclipse.che.commons.test.tck.repository.TckRepository;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.DataProvider;
-import org.testng.annotations.Listeners;
-import org.testng.annotations.Test;
-
-@Listeners(TckListener.class)
-@Test(suiteName = UserDevfileDaoTest.SUITE_NAME)
-public class UserDevfileDaoTest {
-
- public static final String SUITE_NAME = "DevfileDaoTck";
- private static final int ENTRY_COUNT = 10;
- private static final int COUNT_OF_ACCOUNTS = 6;
-
- private UserDevfileImpl[] devfiles;
- private AccountImpl[] accounts;
-
- @Inject private EventService eventService;
-
- @Inject private UserDevfileDao userDevfileDaoDao;
-
- @Inject private TckRepository devfileTckRepository;
-
- @Inject private TckRepository userTckRepository;
-
- @Inject private TckRepository accountRepo;
-
- @Inject private Provider entityManagerProvider;
-
- @BeforeMethod
- public void setUp() throws Exception {
- accounts = new AccountImpl[COUNT_OF_ACCOUNTS];
- for (int i = 0; i < COUNT_OF_ACCOUNTS; i++) {
- accounts[i] = new AccountImpl("accountId" + i, "accountName" + i, "test");
- }
-
- devfiles = new UserDevfileImpl[ENTRY_COUNT];
- for (int i = 0; i < ENTRY_COUNT; i++) {
- AccountImpl account = accounts[i / 2];
- devfiles[i] =
- createUserDevfile(
- NameGenerator.generate("id-" + i + "-", 6),
- account,
- NameGenerator.generate("devfileName-" + i, 6));
- }
- accountRepo.createAll(Stream.of(accounts).map(AccountImpl::new).collect(toList()));
- devfileTckRepository.createAll(Stream.of(devfiles).map(UserDevfileImpl::new).collect(toList()));
- }
-
- @AfterMethod
- public void cleanUp() throws Exception {
- devfileTckRepository.removeAll();
- accountRepo.removeAll();
- }
-
- @Test
- public void shouldGetUserDevfileById() throws Exception {
- final UserDevfileImpl devfile = devfiles[0];
-
- assertEquals(userDevfileDaoDao.getById(devfile.getId()), Optional.of(devfile));
- }
-
- @Test(dependsOnMethods = "shouldGetUserDevfileById")
- public void shouldCreateUserDevfile() throws Exception {
- // given
- final UserDevfileImpl devfile = createUserDevfile(accounts[0]);
- // when
- userDevfileDaoDao.create(devfile);
-
- assertEquals(
- userDevfileDaoDao.getById(devfile.getId()), Optional.of(new UserDevfileImpl(devfile)));
- }
-
- @Test
- public void shouldCreateUserDevfileWithNullDescription() throws Exception {
- // given
- final UserDevfileImpl devfile = createUserDevfile(accounts[0]);
- devfile.setDescription(null);
- // when
- userDevfileDaoDao.create(devfile);
-
- Optional devfileOptional = userDevfileDaoDao.getById(devfile.getId());
- assertTrue(devfileOptional.isPresent());
- assertNull(devfileOptional.get().getDescription());
- assertEquals(devfileOptional, Optional.of(new UserDevfileImpl(devfile)));
- }
-
- @Test
- public void shouldCreateUserDevfileWithEmptyMataName() throws Exception {
- // given
- final UserDevfileImpl devfile = createUserDevfile(accounts[0]);
- DevfileImpl newDevfile = new DevfileImpl(devfile.getDevfile());
- MetadataImpl newMeta = new MetadataImpl();
- newMeta.setGenerateName("gener-");
- newDevfile.setMetadata(newMeta);
- devfile.setDevfile(newDevfile);
- // when
- userDevfileDaoDao.create(devfile);
-
- Optional devfileOptional = userDevfileDaoDao.getById(devfile.getId());
- assertTrue(devfileOptional.isPresent());
- UserDevfile actual = devfileOptional.get();
- assertNull(actual.getDevfile().getMetadata().getName());
- assertNotNull(actual.getDevfile().getMetadata().getGenerateName());
- assertEquals(devfileOptional, Optional.of(new UserDevfileImpl(devfile)));
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenCreateNullDevfile() throws Exception {
- userDevfileDaoDao.create(null);
- }
-
- @Test(expectedExceptions = ConflictException.class)
- public void shouldThrowConflictExceptionWhenCreatingUserDevfileWithExistingId() throws Exception {
- // given
- final UserDevfileImpl devfile = createUserDevfile(accounts[0]);
- final UserDevfileImpl existing = devfiles[0];
- devfile.setId(existing.getId());
- // when
- userDevfileDaoDao.create(devfile);
- // then
- }
-
- @Test
- public void shouldUpdateUserDevfile() throws Exception {
- // given
-
- DevfileImpl newDevfile = TestObjectGenerator.createDevfile("newUpdate");
- newDevfile.setApiVersion("V15.0");
- newDevfile.setProjects(
- ImmutableList.of(
- new ProjectImpl(
- "projectUp2",
- new SourceImpl(
- "typeUp2",
- "http://location",
- "branch2",
- "point2",
- "tag2",
- "commit2",
- "sparseCheckoutDir2"),
- "path2")));
- newDevfile.setComponents(ImmutableList.of(new ComponentImpl("type3", "id54")));
- newDevfile.setCommands(
- ImmutableList.of(
- new CommandImpl(
- new CommandImpl(
- "cmd1",
- Collections.singletonList(
- new ActionImpl(
- "exe44", "compo2nent2", "run.sh", "/home/user/2", null, null)),
- Collections.singletonMap("attr1", "value1"),
- null))));
- newDevfile.setAttributes(ImmutableMap.of("key2", "val34"));
- newDevfile.setMetadata(new MetadataImpl("myNewName"));
- final UserDevfileImpl update = devfiles[0];
- update.setDevfile(newDevfile);
- // when
- userDevfileDaoDao.update(update);
- // then
- assertEquals(userDevfileDaoDao.getById(update.getId()), Optional.of(update));
- }
-
- @Test
- public void shouldNotUpdateWorkspaceWhichDoesNotExist() throws Exception {
- // given
- final UserDevfileImpl userDevfile = devfiles[0];
- userDevfile.setId("non-existing-devfile");
- // when
- Optional result = userDevfileDaoDao.update(userDevfile);
- // then
- assertFalse(result.isPresent());
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenUpdatingNull() throws Exception {
- userDevfileDaoDao.update(null);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenGetByIdNull() throws Exception {
- userDevfileDaoDao.getById(null);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenDeleteNull() throws Exception {
- userDevfileDaoDao.getById(null);
- }
-
- @Test(dependsOnMethods = "shouldGetUserDevfileById")
- public void shouldRemoveDevfile() throws Exception {
- final String userDevfileId = devfiles[0].getId();
- userDevfileDaoDao.remove(userDevfileId);
- Optional result = userDevfileDaoDao.getById(userDevfileId);
-
- assertFalse(result.isPresent());
- }
-
- @Test
- public void shouldDoNothingWhenRemovingNonExistingUserDevfile() throws Exception {
- userDevfileDaoDao.remove("non-existing");
- }
-
- @Test
- public void shouldBeAbleToGetAvailableToUserDevfiles() throws ServerException {
- // given
- // when
- final Page result =
- userDevfileDaoDao.getDevfiles(30, 0, Collections.emptyList(), Collections.emptyList());
- // then
- assertEquals(new HashSet<>(result.getItems()), new HashSet<>(asList(devfiles)));
- }
-
- @Test(expectedExceptions = IllegalArgumentException.class)
- public void shouldThrowIllegalStateExceptionOnNegativeLimit() throws Exception {
- userDevfileDaoDao.getDevfiles(0, -2, Collections.emptyList(), Collections.emptyList());
- }
-
- @Test(expectedExceptions = IllegalArgumentException.class)
- public void shouldThrowIllegalStateExceptionOnNegativeSkipCount() throws Exception {
- userDevfileDaoDao.getDevfiles(-2, 0, Collections.emptyList(), Collections.emptyList());
- }
-
- @Test
- public void shouldBeAbleToGetAvailableToUserDevfilesWithFilter() throws ServerException {
- // given
- // when
- final Page result =
- userDevfileDaoDao.getDevfiles(
- 30,
- 0,
- ImmutableList.of(new Pair<>("name", "like:devfileName%")),
- Collections.emptyList());
- // then
- assertEquals(new HashSet<>(result.getItems()), new HashSet<>(asList(devfiles)));
- }
-
- @Test(expectedExceptions = IllegalArgumentException.class)
- public void shouldNotAllowSearchWithInvalidFilter() throws ServerException {
- // given
- // when
- final Page result =
- userDevfileDaoDao.getDevfiles(
- 30,
- 0,
- ImmutableList.of(
- new Pair<>("id", "like:dev%"),
- new Pair<>("devfile.metadata.something", "like:devfileName%")),
- Collections.emptyList());
- // then
- }
-
- @Test
- public void shouldBeAbleToGetAvailableToUserDevfilesWithFilter2()
- throws ServerException, NotFoundException, ConflictException {
- // given
- final UserDevfileImpl update = devfiles[0];
- update.setName("New345Name");
- userDevfileDaoDao.update(update);
- // when
- final Page result =
- userDevfileDaoDao.getDevfiles(
- 30, 0, ImmutableList.of(new Pair<>("name", "like:%w345N%")), Collections.emptyList());
- // then
- assertEquals(new HashSet<>(result.getItems()), ImmutableSet.of(update));
- }
-
- @Test
- public void shouldBeAbleToGetAvailableToUserDevfilesWithFilterAndLimit()
- throws ServerException, NotFoundException, ConflictException {
- // given
- final UserDevfileImpl update = devfiles[0];
- update.setName("New345Name");
- userDevfileDaoDao.update(update);
- // when
- final Page result =
- userDevfileDaoDao.getDevfiles(
- 12,
- 0,
- ImmutableList.of(new Pair<>("name", "like:devfileName%")),
- Collections.emptyList());
- // then
- assertEquals(result.getItems().size(), 9);
- }
-
- @Test
- public void shouldBeAbleToGetDevfilesSortedById()
- throws ServerException, NotFoundException, ConflictException {
- // given
- UserDevfileImpl[] expected =
- Arrays.stream(devfiles)
- .sorted(Comparator.comparing(UserDevfileImpl::getId))
- .toArray(UserDevfileImpl[]::new);
- // when
- final Page result =
- userDevfileDaoDao.getDevfiles(
- devfiles.length, 0, Collections.emptyList(), ImmutableList.of(new Pair<>("id", "asc")));
- // then
- assertEquals(result.getItems().stream().toArray(UserDevfileImpl[]::new), expected);
- }
-
- @Test
- public void shouldBeAbleToGetDevfilesSortedByIdReverse()
- throws ServerException, NotFoundException, ConflictException {
- // given
- UserDevfileImpl[] expected =
- Arrays.stream(devfiles)
- .sorted(Comparator.comparing(UserDevfileImpl::getId).reversed())
- .toArray(UserDevfileImpl[]::new);
- // when
- final Page result =
- userDevfileDaoDao.getDevfiles(
- devfiles.length,
- 0,
- Collections.emptyList(),
- ImmutableList.of(new Pair<>("id", "desc")));
- // then
- assertEquals(result.getItems().stream().toArray(UserDevfileImpl[]::new), expected);
- }
-
- @Test
- public void shouldBeAbleToGetDevfilesSortedByName()
- throws ServerException, NotFoundException, ConflictException {
- // given
- UserDevfileImpl[] expected =
- Arrays.stream(devfiles)
- .sorted(Comparator.comparing(UserDevfileImpl::getName))
- .toArray(UserDevfileImpl[]::new);
- // when
- final Page result =
- userDevfileDaoDao.getDevfiles(
- devfiles.length,
- 0,
- Collections.emptyList(),
- ImmutableList.of(new Pair<>("name", "asc")));
- // then
- assertEquals(result.getItems().stream().toArray(UserDevfileImpl[]::new), expected);
- }
-
- @Test
- public void shouldSendDevfileDeletedEventOnRemoveUserDevfile() throws Exception {
- // given
- final String userDevfileId = devfiles[0].getId();
- final boolean[] isNotified = new boolean[] {false};
- eventService.subscribe(event -> isNotified[0] = true, BeforeDevfileRemovedEvent.class);
- // when
- userDevfileDaoDao.remove(userDevfileId);
- // then
- assertTrue(isNotified[0], "Event subscriber notified");
- }
-
- @Test(dataProvider = "boundsdataprovider")
- public void shouldBeAbleToGetDevfilesSortedByNameWithSpecificMaxItemsAndSkipCount(
- int maxitems, int skipCount) throws ServerException, NotFoundException, ConflictException {
- // given
- UserDevfileImpl[] expected =
- Arrays.stream(
- Arrays.copyOfRange(devfiles, skipCount, min(devfiles.length, skipCount + maxitems)))
- .sorted(Comparator.comparing(UserDevfileImpl::getId))
- .toArray(UserDevfileImpl[]::new);
- // when
- final Page result =
- userDevfileDaoDao.getDevfiles(
- maxitems,
- skipCount,
- Collections.emptyList(),
- ImmutableList.of(new Pair<>("id", "asc")));
- // then
- assertEquals(result.getItems().stream().toArray(UserDevfileImpl[]::new), expected);
- }
-
- @DataProvider
- public Object[][] boundsdataprovider() {
- return new Object[][] {
- {1, 1},
- {1, 4},
- {4, 5},
- {6, 8},
- {1, ENTRY_COUNT},
- {ENTRY_COUNT, ENTRY_COUNT},
- {ENTRY_COUNT, 1},
- {ENTRY_COUNT, 8}
- };
- }
-
- @Test(
- expectedExceptions = IllegalArgumentException.class,
- expectedExceptionsMessageRegExp = "The number of items has to be positive.")
- public void shouldNotAllowZeroMaxItemsToSearch()
- throws ServerException, NotFoundException, ConflictException {
- // given
- // when
- userDevfileDaoDao.getDevfiles(0, 0, Collections.emptyList(), Collections.emptyList());
- // then
- }
-
- @Test(
- expectedExceptions = IllegalArgumentException.class,
- expectedExceptionsMessageRegExp = "The number of items has to be positive.")
- public void shouldNotAllowNegativeMaxItemsToSearch()
- throws ServerException, NotFoundException, ConflictException {
- // given
- // when
- userDevfileDaoDao.getDevfiles(-5, 0, Collections.emptyList(), Collections.emptyList());
- // then
- }
-
- @Test(
- expectedExceptions = IllegalArgumentException.class,
- expectedExceptionsMessageRegExp =
- "The number of items to skip can't be negative or greater than 2147483647")
- public void shouldNotAllowNegativeItemsToSkipToSearch()
- throws ServerException, NotFoundException, ConflictException {
- // given
- // when
- userDevfileDaoDao.getDevfiles(5, -1, Collections.emptyList(), Collections.emptyList());
- // then
- }
-
- @Test(
- expectedExceptions = IllegalArgumentException.class,
- expectedExceptionsMessageRegExp =
- "Invalid sort order direction\\. Possible values are 'asc' or 'desc'"
- + " but got: \\[\\{first=name, second=ddd}, \\{first=id, second=bla}]")
- public void shouldFailOnInvalidSortOrder()
- throws ServerException, NotFoundException, ConflictException {
- // given
- // when
- userDevfileDaoDao.getDevfiles(
- 5,
- 4,
- Collections.emptyList(),
- ImmutableList.of(
- new Pair<>("id", "asc"),
- new Pair<>("name", "ddd"),
- new Pair<>("name", "DesC"),
- new Pair<>("id", "bla")));
- // then
- }
-
- @Test
- public void shouldGetDevfilesByNamespace() throws Exception {
- final UserDevfileImpl devfile1 = devfiles[0];
- final UserDevfileImpl devfile2 = devfiles[1];
- assertEquals(devfile1.getNamespace(), devfile2.getNamespace(), "Namespaces must be the same");
-
- final Page found = userDevfileDaoDao.getByNamespace(devfile1.getNamespace(), 6, 0);
-
- assertEquals(found.getTotalItemsCount(), 2);
- assertEquals(found.getItemsCount(), 2);
- assertEquals(new HashSet<>(found.getItems()), new HashSet<>(asList(devfile1, devfile2)));
- }
-
- @Test
- public void emptyListShouldBeReturnedWhenThereAreNoDevfilesInGivenNamespace() throws Exception {
- assertTrue(userDevfileDaoDao.getByNamespace("non-existing-namespace", 30, 0).isEmpty());
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenGettingDevfilesByNullNamespace() throws Exception {
- userDevfileDaoDao.getByNamespace(null, 30, 0);
- }
-
- @Test(dataProvider = "validOrderFiled")
- public void shouldTestValidOrderFileds(String filed) {
- JpaUserDevfileDao.UserDevfileSearchQueryBuilder queryBuilder =
- new JpaUserDevfileDao.UserDevfileSearchQueryBuilder(null);
- try {
- queryBuilder.withOrder(ImmutableList.of(new Pair<>(filed, "blah")));
- } catch (IllegalArgumentException e) {
- Assert.fail(filed + " is valid but failed");
- }
- }
-
- @Test(
- dataProvider = "invalidOrderField",
- expectedExceptions = IllegalArgumentException.class,
- expectedExceptionsMessageRegExp = "Order allowed only by \\[id, name\\] but got: .*")
- public void shouldTestInvalidOrderFileds(String filed) {
- JpaUserDevfileDao.UserDevfileSearchQueryBuilder queryBuilder =
- new JpaUserDevfileDao.UserDevfileSearchQueryBuilder(null);
- queryBuilder.withOrder(ImmutableList.of(new Pair<>(filed, "blah")));
- }
-
- @Test(dataProvider = "validSearchFiled")
- public void shouldTestValidSearchFileds(String filed) {
- JpaUserDevfileDao.UserDevfileSearchQueryBuilder queryBuilder =
- new JpaUserDevfileDao.UserDevfileSearchQueryBuilder(null);
- try {
- queryBuilder.withFilter(ImmutableList.of(new Pair<>(filed, "blah")));
- } catch (IllegalArgumentException e) {
- Assert.fail(filed + " is valid but failed");
- }
- }
-
- @Test(
- dataProvider = "invalidSearchField",
- expectedExceptions = IllegalArgumentException.class,
- expectedExceptionsMessageRegExp = "Filtering allowed only by \\[name\\] but got: .*")
- public void shouldTestInvalidSearchFileds(String filed) {
- JpaUserDevfileDao.UserDevfileSearchQueryBuilder queryBuilder =
- new JpaUserDevfileDao.UserDevfileSearchQueryBuilder(null);
- queryBuilder.withFilter(ImmutableList.of(new Pair<>(filed, "blah")));
- }
-
- @DataProvider
- public Object[][] validOrderFiled() {
- return new Object[][] {{"id"}, {"Id"}, {"name"}, {"nAmE"}};
- }
-
- @DataProvider
- public Object[][] invalidOrderField() {
- return new Object[][] {{"devfile"}, {"meta_name"}, {"description"}, {"meta_generated_name"}};
- }
-
- @DataProvider
- public Object[][] validSearchFiled() {
- return new Object[][] {
- {"name"}, {"NaMe"},
- };
- }
-
- @DataProvider
- public Object[][] invalidSearchField() {
- return new Object[][] {
- {"id"}, {"devfile"}, {"ID"}, {"meta_name"}, {"description"}, {"meta_generated_name"}
- };
- }
-}
diff --git a/wsmaster/che-core-api-factory/pom.xml b/wsmaster/che-core-api-factory/pom.xml
index b77a68e8c7..8e0f3f7776 100644
--- a/wsmaster/che-core-api-factory/pom.xml
+++ b/wsmaster/che-core-api-factory/pom.xml
@@ -46,10 +46,6 @@
io.swagger.core.v3
swagger-annotations-jakarta
-
- jakarta.annotation
- jakarta.annotation-api
-
jakarta.inject
jakarta.inject-api
@@ -110,10 +106,6 @@
org.eclipse.che.core
che-core-commons-test
-
- org.eclipse.che.core
- che-core-db
-
org.eclipse.persistence
jakarta.persistence
@@ -157,11 +149,6 @@
che-core-commons-json
test
-
- org.eclipse.che.core
- che-core-db-vendor-h2
- test
-
org.eclipse.che.core
che-core-sql-schema
diff --git a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/jpa/FactoryJpaModule.java b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/jpa/FactoryJpaModule.java
index 78fc575fca..a9f802d855 100644
--- a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/jpa/FactoryJpaModule.java
+++ b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/jpa/FactoryJpaModule.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2018 Red Hat, Inc.
+ * Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
@@ -12,7 +12,6 @@
package org.eclipse.che.api.factory.server.jpa;
import com.google.inject.AbstractModule;
-import org.eclipse.che.api.factory.server.jpa.JpaFactoryDao.RemoveFactoriesBeforeUserRemovedEventSubscriber;
import org.eclipse.che.api.factory.server.spi.FactoryDao;
/** @author Yevhenii Voevodin */
@@ -20,6 +19,5 @@ public class FactoryJpaModule extends AbstractModule {
@Override
protected void configure() {
bind(FactoryDao.class).to(JpaFactoryDao.class);
- bind(RemoveFactoriesBeforeUserRemovedEventSubscriber.class).asEagerSingleton();
}
}
diff --git a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/jpa/JpaFactoryDao.java b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/jpa/JpaFactoryDao.java
index c246947a48..d647b20412 100644
--- a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/jpa/JpaFactoryDao.java
+++ b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/jpa/JpaFactoryDao.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
+ * Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
@@ -17,11 +17,8 @@ import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
-import static org.eclipse.che.api.core.Pages.iterate;
import com.google.inject.persist.Transactional;
-import jakarta.annotation.PostConstruct;
-import jakarta.annotation.PreDestroy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -35,15 +32,10 @@ import org.eclipse.che.api.core.ConflictException;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.Page;
import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.api.core.notification.EventService;
import org.eclipse.che.api.factory.server.model.impl.FactoryImpl;
import org.eclipse.che.api.factory.server.spi.FactoryDao;
-import org.eclipse.che.api.user.server.event.BeforeUserRemovedEvent;
import org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl;
import org.eclipse.che.commons.lang.Pair;
-import org.eclipse.che.core.db.cascade.CascadeEventSubscriber;
-import org.eclipse.che.core.db.jpa.DuplicateKeyException;
-import org.eclipse.che.core.db.jpa.IntegrityConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -59,12 +51,6 @@ public class JpaFactoryDao implements FactoryDao {
requireNonNull(factory);
try {
doCreate(factory);
- } catch (DuplicateKeyException ex) {
- throw new ConflictException(
- format("Factory with name '%s' already exists for current user", factory.getName()));
- } catch (IntegrityConstraintViolationException ex) {
- throw new ConflictException(
- "Could not create factory with creator that refers to a non-existent user");
} catch (RuntimeException ex) {
throw new ServerException(ex.getLocalizedMessage(), ex);
}
@@ -77,9 +63,6 @@ public class JpaFactoryDao implements FactoryDao {
requireNonNull(update);
try {
return new FactoryImpl(doUpdate(update));
- } catch (DuplicateKeyException ex) {
- throw new ConflictException(
- format("Factory with name '%s' already exists for current user", update.getName()));
} catch (RuntimeException ex) {
throw new ServerException(ex.getLocalizedMessage(), ex);
}
@@ -233,31 +216,4 @@ public class JpaFactoryDao implements FactoryDao {
manager.flush();
}
}
-
- @Singleton
- public static class RemoveFactoriesBeforeUserRemovedEventSubscriber
- extends CascadeEventSubscriber {
- @Inject private FactoryDao factoryDao;
- @Inject private EventService eventService;
-
- @PostConstruct
- public void subscribe() {
- eventService.subscribe(this, BeforeUserRemovedEvent.class);
- }
-
- @PreDestroy
- public void unsubscribe() {
- eventService.unsubscribe(this, BeforeUserRemovedEvent.class);
- }
-
- @Override
- public void onCascadeEvent(BeforeUserRemovedEvent event) throws ServerException {
- for (FactoryImpl factory :
- iterate(
- (maxItems, skipCount) ->
- factoryDao.getByUser(event.getUser().getId(), maxItems, skipCount))) {
- factoryDao.remove(factory.getId());
- }
- }
- }
}
diff --git a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/jpa/FactoryTckModule.java b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/jpa/FactoryTckModule.java
index 668425a654..b0bee44122 100644
--- a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/jpa/FactoryTckModule.java
+++ b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/jpa/FactoryTckModule.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
+ * Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
@@ -12,37 +12,12 @@
package org.eclipse.che.api.factory.server.jpa;
import com.google.inject.TypeLiteral;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.factory.server.model.impl.ActionImpl;
import org.eclipse.che.api.factory.server.model.impl.FactoryImpl;
-import org.eclipse.che.api.factory.server.model.impl.IdeImpl;
-import org.eclipse.che.api.factory.server.model.impl.OnAppClosedImpl;
-import org.eclipse.che.api.factory.server.model.impl.OnAppLoadedImpl;
-import org.eclipse.che.api.factory.server.model.impl.OnProjectsLoadedImpl;
import org.eclipse.che.api.factory.server.spi.FactoryDao;
import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.api.workspace.server.model.impl.CommandImpl;
-import org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl;
-import org.eclipse.che.api.workspace.server.model.impl.MachineConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.MachineImpl;
-import org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.RecipeImpl;
-import org.eclipse.che.api.workspace.server.model.impl.ServerConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.SourceStorageImpl;
-import org.eclipse.che.api.workspace.server.model.impl.VolumeImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl;
-import org.eclipse.che.commons.test.db.H2DBTestServer;
-import org.eclipse.che.commons.test.db.H2JpaCleaner;
-import org.eclipse.che.commons.test.db.PersistTestModuleBuilder;
import org.eclipse.che.commons.test.tck.TckModule;
-import org.eclipse.che.commons.test.tck.TckResourcesCleaner;
import org.eclipse.che.commons.test.tck.repository.JpaTckRepository;
import org.eclipse.che.commons.test.tck.repository.TckRepository;
-import org.eclipse.che.core.db.DBInitializer;
-import org.eclipse.che.core.db.h2.jpa.eclipselink.H2ExceptionHandler;
-import org.eclipse.che.core.db.schema.SchemaInitializer;
-import org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer;
-import org.h2.Driver;
/**
* Tck module for factory test.
@@ -53,40 +28,6 @@ public class FactoryTckModule extends TckModule {
@Override
protected void configure() {
- H2DBTestServer server = H2DBTestServer.startDefault();
- install(
- new PersistTestModuleBuilder()
- .setDriver(Driver.class)
- .runningOn(server)
- .addEntityClasses(
- UserImpl.class,
- AccountImpl.class,
- FactoryImpl.class,
- OnAppClosedImpl.class,
- OnProjectsLoadedImpl.class,
- OnAppLoadedImpl.class,
- ActionImpl.class,
- IdeImpl.class,
- WorkspaceConfigImpl.class,
- ProjectConfigImpl.class,
- EnvironmentImpl.class,
- RecipeImpl.class,
- MachineImpl.class,
- MachineConfigImpl.class,
- SourceStorageImpl.class,
- ServerConfigImpl.class,
- CommandImpl.class,
- VolumeImpl.class)
- .addEntityClass(
- "org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl$Attribute")
- .setExceptionHandler(H2ExceptionHandler.class)
- .setProperty("eclipselink.logging.level", "OFF")
- .build());
- bind(DBInitializer.class).asEagerSingleton();
- bind(SchemaInitializer.class)
- .toInstance(new FlywaySchemaInitializer(server.getDataSource(), "che-schema"));
- bind(TckResourcesCleaner.class).toInstance(new H2JpaCleaner(server));
-
bind(FactoryDao.class).to(JpaFactoryDao.class);
bind(new TypeLiteral>() {})
diff --git a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/spi/tck/FactoryDaoTest.java b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/spi/tck/FactoryDaoTest.java
deleted file mode 100644
index 400817aa11..0000000000
--- a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/spi/tck/FactoryDaoTest.java
+++ /dev/null
@@ -1,401 +0,0 @@
-/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.api.factory.server.spi.tck;
-
-import static java.util.Arrays.asList;
-import static java.util.Collections.emptyList;
-import static java.util.Collections.singletonList;
-import static java.util.Collections.singletonMap;
-import static java.util.stream.Collectors.toList;
-import static org.testng.Assert.assertEquals;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Stream;
-import javax.inject.Inject;
-import org.eclipse.che.api.core.ConflictException;
-import org.eclipse.che.api.core.NotFoundException;
-import org.eclipse.che.api.core.Page;
-import org.eclipse.che.api.factory.server.model.impl.ActionImpl;
-import org.eclipse.che.api.factory.server.model.impl.AuthorImpl;
-import org.eclipse.che.api.factory.server.model.impl.FactoryImpl;
-import org.eclipse.che.api.factory.server.model.impl.IdeImpl;
-import org.eclipse.che.api.factory.server.model.impl.OnAppClosedImpl;
-import org.eclipse.che.api.factory.server.model.impl.OnAppLoadedImpl;
-import org.eclipse.che.api.factory.server.model.impl.OnProjectsLoadedImpl;
-import org.eclipse.che.api.factory.server.model.impl.PoliciesImpl;
-import org.eclipse.che.api.factory.server.spi.FactoryDao;
-import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.api.workspace.server.model.impl.CommandImpl;
-import org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl;
-import org.eclipse.che.api.workspace.server.model.impl.MachineConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.RecipeImpl;
-import org.eclipse.che.api.workspace.server.model.impl.ServerConfigImpl;
-import org.eclipse.che.api.workspace.server.model.impl.SourceStorageImpl;
-import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl;
-import org.eclipse.che.commons.lang.Pair;
-import org.eclipse.che.commons.test.tck.TckListener;
-import org.eclipse.che.commons.test.tck.repository.TckRepository;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Listeners;
-import org.testng.annotations.Test;
-
-/**
- * Tests {@link FactoryDao} contract.
- *
- * @author Anton Korneta
- */
-@Listeners(TckListener.class)
-@Test(suiteName = FactoryDaoTest.SUITE_NAME)
-public class FactoryDaoTest {
-
- public static final String SUITE_NAME = "FactoryDaoTck";
-
- private static final int ENTRY_COUNT = 5;
-
- private FactoryImpl[] factories;
- private UserImpl[] users;
-
- @Inject private FactoryDao factoryDao;
-
- @Inject private TckRepository factoryTckRepository;
-
- @Inject private TckRepository userTckRepository;
-
- @BeforeMethod
- public void setUp() throws Exception {
- factories = new FactoryImpl[ENTRY_COUNT];
- users = new UserImpl[ENTRY_COUNT];
- for (int i = 0; i < ENTRY_COUNT; i++) {
- users[i] = new UserImpl("userId_" + i, "email_" + i, "name" + i);
- }
- for (int i = 0; i < ENTRY_COUNT; i++) {
- factories[i] = createFactory(i, users[i].getId());
- }
- userTckRepository.createAll(Arrays.asList(users));
- factoryTckRepository.createAll(Stream.of(factories).map(FactoryImpl::new).collect(toList()));
- }
-
- @AfterMethod
- public void cleanUp() throws Exception {
- factoryTckRepository.removeAll();
- userTckRepository.removeAll();
- }
-
- @Test(dependsOnMethods = "shouldGetFactoryById")
- public void shouldCreateFactory() throws Exception {
- final FactoryImpl factory = createFactory(10, users[0].getId());
- factory.getCreator().setUserId(factories[0].getCreator().getUserId());
- factoryDao.create(factory);
-
- assertEquals(factoryDao.getById(factory.getId()), new FactoryImpl(factory));
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenCreateNullFactory() throws Exception {
- factoryDao.create(null);
- }
-
- @Test(expectedExceptions = ConflictException.class)
- public void shouldThrowConflictExceptionWhenCreatingFactoryWithExistingId() throws Exception {
- final FactoryImpl factory = createFactory(10, users[0].getId());
- final FactoryImpl existing = factories[0];
- factory.getCreator().setUserId(existing.getCreator().getUserId());
- factory.setId(existing.getId());
- factoryDao.create(factory);
- }
-
- @Test(
- expectedExceptions = ConflictException.class,
- expectedExceptionsMessageRegExp =
- "Factory with name 'factoryName0' already exists for current user")
- public void shouldThrowConflictExceptionWhenCreatingFactoryWithExistingNameAndUserId()
- throws Exception {
- final FactoryImpl factory = createFactory(10, users[0].getId());
- final FactoryImpl existing = factories[0];
- factory.getCreator().setUserId(existing.getCreator().getUserId());
- factory.setName(existing.getName());
- factoryDao.create(factory);
- }
-
- @Test
- public void shouldUpdateFactory() throws Exception {
- final FactoryImpl update = factories[0];
- final String userId = update.getCreator().getUserId();
- update.setName("new-name");
- update.setV("5_0");
- final long currentTime = System.currentTimeMillis();
- update.setPolicies(new PoliciesImpl("ref", "per-click", currentTime, currentTime + 1000));
- update.setCreator(new AuthorImpl(userId, currentTime));
- update
- .getIde()
- .getOnAppClosed()
- .getActions()
- .add(new ActionImpl("remove file", ImmutableMap.of("file1", "/che/core/pom.xml")));
- update
- .getIde()
- .getOnAppLoaded()
- .getActions()
- .add(new ActionImpl("edit file", ImmutableMap.of("file2", "/che/core/pom.xml")));
- update
- .getIde()
- .getOnProjectsLoaded()
- .getActions()
- .add(new ActionImpl("open file", ImmutableMap.of("file2", "/che/pom.xml")));
- factoryDao.update(update);
-
- assertEquals(factoryDao.getById(update.getId()), update);
- }
-
- @Test(
- expectedExceptions = ConflictException.class,
- expectedExceptionsMessageRegExp =
- "Factory with name 'factoryName1' already exists for current user")
- public void shouldThrowConflictExceptionWhenUpdateFactoryWithExistingNameAndUserId()
- throws Exception {
- final FactoryImpl update = factories[0];
- update.setName(factories[1].getName());
- update.getCreator().setUserId(factories[1].getCreator().getUserId());
- factoryDao.update(update);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenFactoryUpdateIsNull() throws Exception {
- factoryDao.update(null);
- }
-
- @Test(expectedExceptions = NotFoundException.class)
- public void shouldThrowNotFoundExceptionWhenUpdatingNonExistingFactory() throws Exception {
- factoryDao.update(createFactory(10, users[0].getId()));
- }
-
- @Test
- public void shouldGetFactoryById() throws Exception {
- final FactoryImpl factory = factories[0];
-
- assertEquals(factoryDao.getById(factory.getId()), factory);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenGettingFactoryByNullId() throws Exception {
- factoryDao.getById(null);
- }
-
- @Test(expectedExceptions = NotFoundException.class)
- public void shouldThrowNotFoundExceptionWhenFactoryWithGivenIdDoesNotExist() throws Exception {
- factoryDao.getById("non-existing");
- }
-
- @Test
- public void shouldGetFactoryByIdAttribute() throws Exception {
- final FactoryImpl factory = factories[0];
- final List> attributes = ImmutableList.of(Pair.of("id", factory.getId()));
- final Page result = factoryDao.getByAttributes(1, 0, attributes);
-
- assertEquals(new HashSet<>(result.getItems()), ImmutableSet.of(factory));
- }
-
- @Test(dependsOnMethods = "shouldUpdateFactory")
- public void shouldFindFactoryByEmbeddedAttributes() throws Exception {
- final List> attributes =
- ImmutableList.of(
- Pair.of("policies.referer", "referrer"),
- Pair.of("policies.create", "perClick"),
- Pair.of("workspace.defaultEnv", "env1"));
- final FactoryImpl factory1 = factories[1];
- final FactoryImpl factory3 = factories[3];
- factory1.getPolicies().setCreate("perAccount");
- factory3.getPolicies().setReferer("ref2");
- factoryDao.update(factory1);
- factoryDao.update(factory3);
- final Page result = factoryDao.getByAttributes(factories.length, 0, attributes);
-
- assertEquals(
- new HashSet<>(result.getItems()),
- ImmutableSet.of(factories[0], factories[2], factories[4]));
- }
-
- @Test
- public void shouldFindAllFactoriesWhenAttributesNotSpecified() throws Exception {
- final List> attributes = emptyList();
- final Page result = factoryDao.getByAttributes(factories.length, 0, attributes);
-
- assertEquals(new HashSet<>(result.getItems()), new HashSet<>(asList(factories)));
- }
-
- @Test
- public void shouldFindAllFactoriesOfSpecifiedUser() throws Exception {
- final Page result = factoryDao.getByUser(users[1].getId(), 30, 0);
- assertEquals(new HashSet<>(result.getItems()), new HashSet<>(asList(factories[1])));
- }
-
- @Test(expectedExceptions = NotFoundException.class, dependsOnMethods = "shouldGetFactoryById")
- public void shouldRemoveFactory() throws Exception {
- final String factoryId = factories[0].getId();
- factoryDao.remove(factoryId);
- factoryDao.getById(factoryId);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenRemovingNullFactory() throws Exception {
- factoryDao.remove(null);
- }
-
- @Test
- public void shouldDoNothingWhenRemovingNonExistingFactory() throws Exception {
- factoryDao.remove("non-existing");
- }
-
- private static FactoryImpl createFactory(int index, String userId) {
- final long timeMs = System.currentTimeMillis();
- final AuthorImpl creator = new AuthorImpl(userId, timeMs);
- final PoliciesImpl policies = new PoliciesImpl("referrer", "perClick", timeMs, timeMs + 1000);
- final List a1 =
- new ArrayList<>(
- singletonList(new ActionImpl("id" + index, ImmutableMap.of("key1", "value1"))));
- final OnAppLoadedImpl onAppLoaded = new OnAppLoadedImpl(a1);
- final List a2 =
- new ArrayList<>(
- singletonList(new ActionImpl("id" + index, ImmutableMap.of("key2", "value2"))));
- final OnProjectsLoadedImpl onProjectsLoaded = new OnProjectsLoadedImpl(a2);
- final List a3 =
- new ArrayList<>(
- singletonList(new ActionImpl("id" + index, ImmutableMap.of("key3", "value3"))));
- final OnAppClosedImpl onAppClosed = new OnAppClosedImpl(a3);
- final IdeImpl ide = new IdeImpl(onAppLoaded, onProjectsLoaded, onAppClosed);
- final FactoryImpl factory =
- FactoryImpl.builder()
- .generateId()
- .setVersion("4_0")
- .setName("factoryName" + index)
- .setCreator(creator)
- .setPolicies(policies)
- .setIde(ide)
- .build();
- factory.setWorkspace(createWorkspaceConfig(index));
- return factory;
- }
-
- private static WorkspaceConfigImpl createWorkspaceConfig(int index) {
- // Project Sources configuration
- final SourceStorageImpl source1 = new SourceStorageImpl();
- source1.setType("type1");
- source1.setLocation("location1");
- source1.setParameters(new HashMap<>(ImmutableMap.of("param1", "value1")));
- final SourceStorageImpl source2 = new SourceStorageImpl();
- source2.setType("type2");
- source2.setLocation("location2");
- source2.setParameters(new HashMap<>(ImmutableMap.of("param4", "value1")));
-
- // Project Configuration
- final ProjectConfigImpl pCfg1 = new ProjectConfigImpl();
- pCfg1.setPath("/path1");
- pCfg1.setType("type1");
- pCfg1.setName("project1");
- pCfg1.setDescription("description1");
- pCfg1.getMixins().addAll(asList("mixin1", "mixin2"));
- pCfg1.setSource(source1);
-
- final ProjectConfigImpl pCfg2 = new ProjectConfigImpl();
- pCfg2.setPath("/path2");
- pCfg2.setType("type2");
- pCfg2.setName("project2");
- pCfg2.setDescription("description2");
- pCfg2.getMixins().addAll(asList("mixin3", "mixin4"));
- pCfg2.setSource(source2);
-
- final List projects = new ArrayList<>(asList(pCfg1, pCfg2));
-
- // Commands
- final CommandImpl cmd1 = new CommandImpl("name1", "cmd1", "type1");
- cmd1.getAttributes().putAll(ImmutableMap.of("key1", "value1"));
- final CommandImpl cmd2 = new CommandImpl("name2", "cmd2", "type2");
- cmd2.getAttributes().putAll(ImmutableMap.of("key4", "value4"));
- final List commands = new ArrayList<>(asList(cmd1, cmd2));
-
- // Machine configs
- final MachineConfigImpl exMachine1 = new MachineConfigImpl();
- final ServerConfigImpl serverConf1 =
- new ServerConfigImpl("2265", "http", "/path1", singletonMap("key", "value"));
- final ServerConfigImpl serverConf2 =
- new ServerConfigImpl("2266", "ftp", "/path2", singletonMap("key", "value"));
- exMachine1.setServers(ImmutableMap.of("ref1", serverConf1, "ref2", serverConf2));
- exMachine1.setAttributes(singletonMap("att1", "val"));
- exMachine1.setEnv(singletonMap("CHE_ENV", "value"));
-
- final MachineConfigImpl exMachine2 = new MachineConfigImpl();
- final ServerConfigImpl serverConf3 =
- new ServerConfigImpl("2333", "https", "/path1", singletonMap("key", "value"));
- final ServerConfigImpl serverConf4 =
- new ServerConfigImpl("2334", "wss", "/path2", singletonMap("key", "value"));
- exMachine2.setServers(ImmutableMap.of("ref1", serverConf3, "ref2", serverConf4));
- exMachine2.setAttributes(singletonMap("att1", "val"));
- exMachine2.setEnv(singletonMap("CHE_ENV2", "value"));
-
- final MachineConfigImpl exMachine3 = new MachineConfigImpl();
- final ServerConfigImpl serverConf5 =
- new ServerConfigImpl("2333", "https", "/path3", singletonMap("key", "value"));
- exMachine3.setServers(singletonMap("ref1", serverConf5));
- exMachine3.setAttributes(singletonMap("att1", "val"));
- exMachine3.setEnv(singletonMap("CHE_ENV3", "value"));
-
- // Environments
- final RecipeImpl recipe1 = new RecipeImpl();
- recipe1.setLocation("https://eclipse.che/Dockerfile");
- recipe1.setType("dockerfile");
- recipe1.setContentType("text/x-dockerfile");
- recipe1.setContent("content");
- final EnvironmentImpl env1 = new EnvironmentImpl();
- env1.setMachines(
- new HashMap<>(
- ImmutableMap.of(
- "machine1", exMachine1,
- "machine2", exMachine2,
- "machine3", exMachine3)));
- env1.setRecipe(recipe1);
-
- final RecipeImpl recipe2 = new RecipeImpl();
- recipe2.setLocation("https://eclipse.che/Dockerfile");
- recipe2.setType("dockerfile");
- recipe2.setContentType("text/x-dockerfile");
- recipe2.setContent("content");
- final EnvironmentImpl env2 = new EnvironmentImpl();
- env2.setMachines(
- new HashMap<>(
- ImmutableMap.of(
- "machine1", exMachine1,
- "machine3", exMachine3)));
- env2.setRecipe(recipe2);
-
- final Map environments = ImmutableMap.of("env1", env1, "env2", env2);
-
- // Workspace configuration
- final WorkspaceConfigImpl wCfg = new WorkspaceConfigImpl();
- wCfg.setDefaultEnv("env1");
- wCfg.setName("cfgName_" + index);
- wCfg.setDescription("description");
- wCfg.setCommands(commands);
- wCfg.setProjects(projects);
- wCfg.setEnvironments(environments);
-
- return wCfg;
- }
-}
diff --git a/wsmaster/che-core-api-ssh/pom.xml b/wsmaster/che-core-api-ssh/pom.xml
index b0ac80acd6..44f4553d19 100644
--- a/wsmaster/che-core-api-ssh/pom.xml
+++ b/wsmaster/che-core-api-ssh/pom.xml
@@ -46,10 +46,6 @@
io.swagger.core.v3
swagger-annotations-jakarta
-
- jakarta.annotation
- jakarta.annotation-api
-
jakarta.inject
jakarta.inject-api
@@ -78,100 +74,10 @@
org.eclipse.che.core
che-core-commons-annotations
-
- org.eclipse.che.core
- che-core-db
-
org.eclipse.persistence
jakarta.persistence
provided
-
- com.h2database
- h2
- test
-
-
- org.eclipse.che.core
- che-core-api-account
- test
-
-
- org.eclipse.che.core
- che-core-commons-lang
- test
-
-
- org.eclipse.che.core
- che-core-commons-test
- test
-
-
- org.eclipse.che.core
- che-core-db-vendor-h2
- test
-
-
- org.eclipse.che.core
- che-core-sql-schema
- test
-
-
- org.eclipse.persistence
- org.eclipse.persistence.core
- test
-
-
- org.eclipse.persistence
- org.eclipse.persistence.jpa
- test
-
-
- org.everrest
- everrest-assured
- test
-
-
- org.flywaydb
- flyway-core
- test
-
-
- org.mockito
- mockito-core
- test
-
-
- org.mockito
- mockito-testng
- test
-
-
- org.testng
- testng
- test
-
-
-
-
-
- org.apache.maven.plugins
- maven-jar-plugin
-
-
-
- test-jar
-
-
-
- **/spi/tck/*.*
-
-
-
-
-
-
-
diff --git a/wsmaster/che-core-api-ssh/src/main/java/org/eclipse/che/api/ssh/server/jpa/JpaSshDao.java b/wsmaster/che-core-api-ssh/src/main/java/org/eclipse/che/api/ssh/server/jpa/JpaSshDao.java
index 2c3b076931..22ebd1344c 100644
--- a/wsmaster/che-core-api-ssh/src/main/java/org/eclipse/che/api/ssh/server/jpa/JpaSshDao.java
+++ b/wsmaster/che-core-api-ssh/src/main/java/org/eclipse/che/api/ssh/server/jpa/JpaSshDao.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2021 Red Hat, Inc.
+ * Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
@@ -15,8 +15,6 @@ import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import com.google.inject.persist.Transactional;
-import jakarta.annotation.PostConstruct;
-import jakarta.annotation.PreDestroy;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Provider;
@@ -25,12 +23,8 @@ import javax.persistence.EntityManager;
import org.eclipse.che.api.core.ConflictException;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.ServerException;
-import org.eclipse.che.api.core.notification.EventService;
import org.eclipse.che.api.ssh.server.model.impl.SshPairImpl;
import org.eclipse.che.api.ssh.server.spi.SshDao;
-import org.eclipse.che.api.user.server.event.BeforeUserRemovedEvent;
-import org.eclipse.che.core.db.cascade.CascadeEventSubscriber;
-import org.eclipse.che.core.db.jpa.DuplicateKeyException;
/**
* JPA based implementation of {@link SshDao}.
@@ -48,11 +42,6 @@ public class JpaSshDao implements SshDao {
requireNonNull(sshPair);
try {
doCreate(sshPair);
- } catch (DuplicateKeyException e) {
- throw new ConflictException(
- format(
- "Ssh pair with service '%s' and name '%s' already exists",
- sshPair.getService(), sshPair.getName()));
} catch (RuntimeException e) {
throw new ServerException(e);
}
@@ -144,28 +133,4 @@ public class JpaSshDao implements SshDao {
manager.remove(entity);
manager.flush();
}
-
- @Singleton
- public static class RemoveSshKeysBeforeUserRemovedEventSubscriber
- extends CascadeEventSubscriber {
- @Inject private SshDao sshDao;
- @Inject private EventService eventService;
-
- @PostConstruct
- public void subscribe() {
- eventService.subscribe(this, BeforeUserRemovedEvent.class);
- }
-
- @PreDestroy
- public void unsubscribe() {
- eventService.unsubscribe(this, BeforeUserRemovedEvent.class);
- }
-
- @Override
- public void onCascadeEvent(BeforeUserRemovedEvent event) throws Exception {
- for (SshPairImpl sshPair : sshDao.get(event.getUser().getId())) {
- sshDao.remove(sshPair.getOwner(), sshPair.getService(), sshPair.getName());
- }
- }
- }
}
diff --git a/wsmaster/che-core-api-ssh/src/main/java/org/eclipse/che/api/ssh/server/jpa/SshJpaModule.java b/wsmaster/che-core-api-ssh/src/main/java/org/eclipse/che/api/ssh/server/jpa/SshJpaModule.java
index 908446bc1d..f5f0ce00a9 100644
--- a/wsmaster/che-core-api-ssh/src/main/java/org/eclipse/che/api/ssh/server/jpa/SshJpaModule.java
+++ b/wsmaster/che-core-api-ssh/src/main/java/org/eclipse/che/api/ssh/server/jpa/SshJpaModule.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2018 Red Hat, Inc.
+ * Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
@@ -12,7 +12,6 @@
package org.eclipse.che.api.ssh.server.jpa;
import com.google.inject.AbstractModule;
-import org.eclipse.che.api.ssh.server.jpa.JpaSshDao.RemoveSshKeysBeforeUserRemovedEventSubscriber;
import org.eclipse.che.api.ssh.server.spi.SshDao;
/** @author Yevhenii Voevodin */
@@ -21,6 +20,5 @@ public class SshJpaModule extends AbstractModule {
@Override
protected void configure() {
bind(SshDao.class).to(JpaSshDao.class);
- bind(RemoveSshKeysBeforeUserRemovedEventSubscriber.class).asEagerSingleton();
}
}
diff --git a/wsmaster/che-core-api-ssh/src/test/java/org/eclipse/che/api/ssh/server/jpa/SshTckModule.java b/wsmaster/che-core-api-ssh/src/test/java/org/eclipse/che/api/ssh/server/jpa/SshTckModule.java
deleted file mode 100644
index 68081a0aaa..0000000000
--- a/wsmaster/che-core-api-ssh/src/test/java/org/eclipse/che/api/ssh/server/jpa/SshTckModule.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2012-2018 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.api.ssh.server.jpa;
-
-import com.google.inject.TypeLiteral;
-import org.eclipse.che.account.spi.AccountImpl;
-import org.eclipse.che.api.ssh.server.model.impl.SshPairImpl;
-import org.eclipse.che.api.ssh.server.spi.SshDao;
-import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.commons.test.db.H2DBTestServer;
-import org.eclipse.che.commons.test.db.H2JpaCleaner;
-import org.eclipse.che.commons.test.db.PersistTestModuleBuilder;
-import org.eclipse.che.commons.test.tck.TckModule;
-import org.eclipse.che.commons.test.tck.TckResourcesCleaner;
-import org.eclipse.che.commons.test.tck.repository.JpaTckRepository;
-import org.eclipse.che.commons.test.tck.repository.TckRepository;
-import org.eclipse.che.core.db.DBInitializer;
-import org.eclipse.che.core.db.h2.jpa.eclipselink.H2ExceptionHandler;
-import org.eclipse.che.core.db.schema.SchemaInitializer;
-import org.eclipse.che.core.db.schema.impl.flyway.FlywaySchemaInitializer;
-import org.h2.Driver;
-
-/**
- * @author Mihail Kuznyetsov
- * @author Yevhenii Voevodin
- */
-public class SshTckModule extends TckModule {
-
- @Override
- protected void configure() {
- H2DBTestServer server = H2DBTestServer.startDefault();
- install(
- new PersistTestModuleBuilder()
- .setDriver(Driver.class)
- .runningOn(server)
- .addEntityClasses(SshPairImpl.class, UserImpl.class, AccountImpl.class)
- .setExceptionHandler(H2ExceptionHandler.class)
- .build());
- bind(DBInitializer.class).asEagerSingleton();
- bind(SchemaInitializer.class)
- .toInstance(new FlywaySchemaInitializer(server.getDataSource(), "che-schema"));
- bind(TckResourcesCleaner.class).toInstance(new H2JpaCleaner(server));
-
- bind(SshDao.class).to(JpaSshDao.class);
- bind(new TypeLiteral>() {})
- .toInstance(new JpaTckRepository<>(SshPairImpl.class));
- bind(new TypeLiteral>() {})
- .toInstance(new JpaTckRepository<>(UserImpl.class));
- }
-}
diff --git a/wsmaster/che-core-api-ssh/src/test/java/org/eclipse/che/api/ssh/server/spi/tck/SshDaoTest.java b/wsmaster/che-core-api-ssh/src/test/java/org/eclipse/che/api/ssh/server/spi/tck/SshDaoTest.java
deleted file mode 100644
index 4476a0c5d2..0000000000
--- a/wsmaster/che-core-api-ssh/src/test/java/org/eclipse/che/api/ssh/server/spi/tck/SshDaoTest.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (c) 2012-2018 Red Hat, Inc.
- * This program and the accompanying materials are made
- * available under the terms of the Eclipse Public License 2.0
- * which is available at https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Red Hat, Inc. - initial API and implementation
- */
-package org.eclipse.che.api.ssh.server.spi.tck;
-
-import static java.util.Arrays.asList;
-import static java.util.Collections.emptyList;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import javax.inject.Inject;
-import org.eclipse.che.api.core.ConflictException;
-import org.eclipse.che.api.core.NotFoundException;
-import org.eclipse.che.api.ssh.server.model.impl.SshPairImpl;
-import org.eclipse.che.api.ssh.server.spi.SshDao;
-import org.eclipse.che.api.user.server.model.impl.UserImpl;
-import org.eclipse.che.commons.lang.NameGenerator;
-import org.eclipse.che.commons.test.tck.TckListener;
-import org.eclipse.che.commons.test.tck.repository.TckRepository;
-import org.eclipse.che.commons.test.tck.repository.TckRepositoryException;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Listeners;
-import org.testng.annotations.Test;
-
-/**
- * Tests {@link SshDao} interface contract.
- *
- * @author Mihail Kuznyetsov.
- * @author Yevhenii Voevodin
- */
-@Listeners(TckListener.class)
-@Test(suiteName = SshDaoTest.SUITE_NAME)
-public class SshDaoTest {
- public static final String SUITE_NAME = "SshDaoTck";
-
- private static final int COUNT_OF_PAIRS = 6;
- private static final int COUNT_OF_USERS = 3;
-
- SshPairImpl[] pairs;
-
- @Inject private SshDao sshDao;
-
- @Inject private TckRepository sshRepository;
-
- @Inject private TckRepository userRepository;
-
- @BeforeMethod
- public void setUp() throws TckRepositoryException {
- UserImpl[] users = new UserImpl[COUNT_OF_USERS];
- for (int i = 0; i < COUNT_OF_USERS; i++) {
- users[i] =
- new UserImpl(
- "owner" + i, "owner" + i + "@eclipse.org", "owner" + i, "password", emptyList());
- }
-
- pairs = new SshPairImpl[COUNT_OF_PAIRS];
-
- for (int i = 0; i < COUNT_OF_PAIRS; i++) {
- pairs[i] =
- new SshPairImpl(
- "owner" + i / 3, // 3 each pairs share the same owner
- "service" + i / 2, // each 2 pairs share the same service
- "name" + i,
- NameGenerator.generate("publicKey-", 20),
- NameGenerator.generate("privateKey-", 20));
- }
-
- userRepository.createAll(Arrays.asList(users));
- sshRepository.createAll(Arrays.asList(pairs));
- }
-
- @AfterMethod
- public void cleanUp() throws TckRepositoryException {
- sshRepository.removeAll();
- userRepository.removeAll();
- }
-
- @Test(dependsOnMethods = "shouldGetSshPairByNameOwnerAndService")
- public void shouldCreateSshKeyPair() throws Exception {
- SshPairImpl pair = new SshPairImpl("owner1", "service", "name", "publicKey", "privateKey");
- sshDao.create(pair);
-
- assertEquals(sshDao.get("owner1", "service", "name"), pair);
- }
-
- @Test(expectedExceptions = ConflictException.class)
- public void shouldThrowConflictExceptionWhenSshPairWithSuchOwnerAndServiceAndNameAlreadyExists()
- throws Exception {
- sshDao.create(pairs[0]);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnCreateIfSshPairIsNull() throws Exception {
- sshDao.create(null);
- }
-
- @Test
- public void shouldGetSshPairByNameOwnerAndService() throws Exception {
- SshPairImpl sshPair = pairs[0];
-
- sshDao.get(sshPair.getOwner(), sshPair.getService(), sshPair.getName());
- }
-
- @Test(expectedExceptions = NotFoundException.class)
- public void shouldThrowNotFoundExceptionIfPairWithSuchNameOwnerAndServiceDoesNotExist()
- throws Exception {
- SshPairImpl sshPair = pairs[0];
-
- sshDao.get(sshPair.getService(), sshPair.getService(), sshPair.getName());
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnGetSshPairWhenOwnerIsNull() throws Exception {
- sshDao.get(null, "service", "name");
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnGetSshPairWhenServiceIsNull() throws Exception {
- sshDao.get("owner", null, "name");
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnGetSshPairWhenNameIsNull() throws Exception {
- sshDao.get("owner", "service", null);
- }
-
- @Test
- public void shouldGetSshPairListByNameAndService() throws Exception {
- SshPairImpl sshPair1 = pairs[0];
- SshPairImpl sshPair2 = pairs[1];
- assertEquals(sshPair1.getOwner(), sshPair2.getOwner(), "Owner must be the same");
- assertEquals(sshPair1.getService(), sshPair2.getService(), "Service must be the same");
-
- final List found = sshDao.get(sshPair1.getOwner(), sshPair1.getService());
- assertEquals(new HashSet<>(found), new HashSet<>(asList(sshPair1, sshPair2)));
- }
-
- @Test
- public void shouldReturnEmptyListWhenThereAreNoPairsWithGivenOwnerAndService() throws Exception {
- assertTrue(sshDao.get("non-existing-owner", "non-existing-service").isEmpty());
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnGetSshPairsListWhenOwnerIsNull() throws Exception {
- sshDao.get(null, "service");
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnGetSshPairsListWhenServiceIsNull() throws Exception {
- sshDao.get("owner", null);
- }
-
- @Test(
- expectedExceptions = NotFoundException.class,
- dependsOnMethods =
- "shouldThrowNotFoundExceptionIfPairWithSuchNameOwnerAndServiceDoesNotExist")
- public void shouldRemoveSshKeyPair() throws Exception {
- final SshPairImpl pair = pairs[4];
-
- try {
- sshDao.remove(pair.getOwner(), pair.getService(), pair.getName());
- } catch (NotFoundException x) {
- fail("SshKeyPair should be removed");
- }
-
- sshDao.get(pair.getOwner(), pair.getService(), pair.getName());
- }
-
- @Test
- public void shouldGetSshPairByOwner() throws Exception {
- final List sshPairs = sshDao.get(pairs[0].getOwner());
-
- assertEquals(new HashSet<>(sshPairs), new HashSet<>(asList(pairs[0], pairs[1], pairs[2])));
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeWhenGettingByNullOwner() throws Exception {
- sshDao.get(null);
- }
-
- @Test(expectedExceptions = NotFoundException.class)
- public void shouldThrowNotFoundExceptionWhenRemovingNonExistingPair() throws Exception {
- sshDao.remove(pairs[4].getService(), pairs[4].getService(), pairs[4].getService());
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnRemoveWhenOwnerIsNull() throws Exception {
- sshDao.remove(null, "service", "name");
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnRemoveWhenServiceIsNull() throws Exception {
- sshDao.remove("owner", null, "name");
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void shouldThrowNpeOnRemoveWhenNameIsNull() throws Exception {
- sshDao.remove("owner", "service", null);
- }
-}
diff --git a/wsmaster/che-core-api-ssh/src/test/resources/META-INF/services/org.eclipse.che.commons.test.tck.TckModule b/wsmaster/che-core-api-ssh/src/test/resources/META-INF/services/org.eclipse.che.commons.test.tck.TckModule
deleted file mode 100644
index f4b169e32f..0000000000
--- a/wsmaster/che-core-api-ssh/src/test/resources/META-INF/services/org.eclipse.che.commons.test.tck.TckModule
+++ /dev/null
@@ -1 +0,0 @@
-org.eclipse.che.api.ssh.server.jpa.SshTckModule
diff --git a/wsmaster/che-core-api-system/pom.xml b/wsmaster/che-core-api-system/pom.xml
index 7b29144a47..d1505b2e4a 100644
--- a/wsmaster/che-core-api-system/pom.xml
+++ b/wsmaster/che-core-api-system/pom.xml
@@ -83,10 +83,6 @@
org.eclipse.che.core
che-core-commons-schedule