From c2a2fca5aebbd85a23dfd2eec5a577ff4a3d1605 Mon Sep 17 00:00:00 2001 From: Igor Vinokur Date: Thu, 12 Sep 2024 09:39:57 +0300 Subject: [PATCH] Remove devfile v1 leftovers (#717) --- .../che/api/deploy/WsMasterModule.java | 6 - .../AzureDevOpsFactoryParametersResolver.java | 46 --- .../pom.xml | 4 - ...rAuthorizingFactoryParametersResolver.java | 31 -- ...horizingFactoryParametersResolverTest.java | 31 +- .../BitbucketFactoryParametersResolver.java | 42 --- ...itbucketFactoryParametersResolverTest.java | 108 +----- wsmaster/che-core-api-factory-git-ssh/pom.xml | 4 - .../ssh/GitSshFactoryParametersResolver.java | 26 +- ...stractGithubFactoryParametersResolver.java | 41 --- wsmaster/che-core-api-factory-github/pom.xml | 4 - .../GithubFactoryParametersResolver.java | 3 - ...GithubFactoryParametersResolverSecond.java | 3 - .../GithubFactoryParametersResolverTest.java | 117 +------ wsmaster/che-core-api-factory-gitlab/pom.xml | 4 - .../GitlabFactoryParametersResolver.java | 31 -- .../GitlabFactoryParametersResolverTest.java | 26 +- wsmaster/che-core-api-factory-shared/pom.xml | 4 - .../api/factory/shared/dto/FactoryDto.java | 78 ----- .../factory/shared/dto/FactoryVisitor.java | 13 +- .../che/api/factory/server/DtoConverter.java | 27 +- .../server/FactoryCreateValidator.java | 38 --- .../factory/server/FactoryEditValidator.java | 34 -- .../server/builder/FactoryBuilder.java | 314 ------------------ .../server/impl/FactoryBaseValidator.java | 82 +---- .../impl/FactoryCreateValidatorImpl.java | 48 --- .../server/impl/FactoryEditValidatorImpl.java | 57 ---- .../urlfactory/ProjectConfigDtoMerger.java | 70 ---- .../server/urlfactory/URLFactoryBuilder.java | 103 +----- .../factory/server/FactoryServiceTest.java | 64 ---- ...evfileUrlFactoryParameterResolverTest.java | 51 +-- .../server/builder/FactoryBuilderTest.java | 288 ---------------- .../server/impl/FactoryBaseValidatorTest.java | 234 +------------ ...oryCreateAndAcceptValidatorsImplsTest.java | 91 ----- .../impl/FactoryEditValidatorImplTest.java | 93 ------ .../ProjectConfigDtoMergerTest.java | 91 ----- .../urlfactory/URLFactoryBuilderTest.java | 67 +--- 37 files changed, 53 insertions(+), 2321 deletions(-) delete mode 100644 wsmaster/che-core-api-factory-shared/src/main/java/org/eclipse/che/api/factory/shared/dto/FactoryDto.java delete mode 100644 wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/FactoryCreateValidator.java delete mode 100644 wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/FactoryEditValidator.java delete mode 100644 wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/builder/FactoryBuilder.java delete mode 100644 wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryCreateValidatorImpl.java delete mode 100644 wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryEditValidatorImpl.java delete mode 100644 wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/urlfactory/ProjectConfigDtoMerger.java delete mode 100644 wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/builder/FactoryBuilderTest.java delete mode 100644 wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryCreateAndAcceptValidatorsImplsTest.java delete mode 100644 wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryEditValidatorImplTest.java delete mode 100644 wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/urlfactory/ProjectConfigDtoMergerTest.java diff --git a/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java b/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java index 131291ab8a4..965dfec5cf7 100644 --- a/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java +++ b/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java @@ -32,8 +32,6 @@ import org.eclipse.che.api.core.rest.MessageBodyAdapterInterceptor; import org.eclipse.che.api.deploy.jsonrpc.CheJsonRpcWebSocketConfigurationModule; import org.eclipse.che.api.factory.server.FactoryAcceptValidator; -import org.eclipse.che.api.factory.server.FactoryCreateValidator; -import org.eclipse.che.api.factory.server.FactoryEditValidator; import org.eclipse.che.api.factory.server.FactoryParametersResolver; import org.eclipse.che.api.factory.server.RawDevfileUrlFactoryParameterResolver; import org.eclipse.che.api.factory.server.ScmFileResolver; @@ -144,10 +142,6 @@ protected void configure() { // factory bind(FactoryAcceptValidator.class) .to(org.eclipse.che.api.factory.server.impl.FactoryAcceptValidatorImpl.class); - bind(FactoryCreateValidator.class) - .to(org.eclipse.che.api.factory.server.impl.FactoryCreateValidatorImpl.class); - bind(FactoryEditValidator.class) - .to(org.eclipse.che.api.factory.server.impl.FactoryEditValidatorImpl.class); bind(org.eclipse.che.api.factory.server.FactoryService.class); bind(ScmService.class); install(new org.eclipse.che.api.factory.server.jpa.FactoryJpaModule()); diff --git a/wsmaster/che-core-api-factory-azure-devops/src/main/java/org/eclipse/che/api/factory/server/azure/devops/AzureDevOpsFactoryParametersResolver.java b/wsmaster/che-core-api-factory-azure-devops/src/main/java/org/eclipse/che/api/factory/server/azure/devops/AzureDevOpsFactoryParametersResolver.java index 6b3654d3841..13f6c6d4d5e 100644 --- a/wsmaster/che-core-api-factory-azure-devops/src/main/java/org/eclipse/che/api/factory/server/azure/devops/AzureDevOpsFactoryParametersResolver.java +++ b/wsmaster/che-core-api-factory-azure-devops/src/main/java/org/eclipse/che/api/factory/server/azure/devops/AzureDevOpsFactoryParametersResolver.java @@ -25,19 +25,14 @@ import org.eclipse.che.api.factory.server.FactoryParametersResolver; import org.eclipse.che.api.factory.server.scm.AuthorisationRequestManager; import org.eclipse.che.api.factory.server.scm.PersonalAccessTokenManager; -import org.eclipse.che.api.factory.server.urlfactory.ProjectConfigDtoMerger; import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.FactoryMetaDto; import org.eclipse.che.api.factory.shared.dto.FactoryVisitor; import org.eclipse.che.api.factory.shared.dto.ScmInfoDto; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; -import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.ProjectDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.SourceDto; /** * Provides Factory Parameters resolver for Azure DevOps repositories. @@ -56,11 +51,9 @@ public class AzureDevOpsFactoryParametersResolver extends BaseFactoryParameterRe private final URLFetcher urlFetcher; private final URLFactoryBuilder urlFactoryBuilder; private final PersonalAccessTokenManager personalAccessTokenManager; - private final ProjectConfigDtoMerger projectConfigDtoMerger; @Inject public AzureDevOpsFactoryParametersResolver( - ProjectConfigDtoMerger projectConfigDtoMerger, AzureDevOpsURLParser azureDevOpsURLParser, URLFetcher urlFetcher, URLFactoryBuilder urlFactoryBuilder, @@ -71,7 +64,6 @@ public AzureDevOpsFactoryParametersResolver( this.urlFetcher = urlFetcher; this.urlFactoryBuilder = urlFactoryBuilder; this.personalAccessTokenManager = personalAccessTokenManager; - this.projectConfigDtoMerger = projectConfigDtoMerger; } @Override @@ -122,44 +114,6 @@ public FactoryDevfileV2Dto visit(FactoryDevfileV2Dto factoryDto) { .withBranch(azureDevOpsUrl.getBranch()); return factoryDto.withScmInfo(scmInfo); } - - @Override - public FactoryDto visit(FactoryDto factory) { - if (factory.getWorkspace() != null) { - return projectConfigDtoMerger.merge( - factory, - () -> { - // Compute project configuration - return newDto(ProjectConfigDto.class) - .withSource(buildWorkspaceConfigSource(azureDevOpsUrl)) - .withName(azureDevOpsUrl.getRepository()) - .withPath("/".concat(azureDevOpsUrl.getRepository())); - }); - } else if (factory.getDevfile() == null) { - factory.setDevfile(urlFactoryBuilder.buildDefaultDevfile(azureDevOpsUrl.getRepository())); - } - - updateProjects( - factory.getDevfile(), - () -> - newDto(ProjectDto.class) - .withSource( - newDto(SourceDto.class) - .withLocation(azureDevOpsUrl.getRepositoryLocation()) - .withType("git") - .withBranch(azureDevOpsUrl.getBranch()) - .withTag(azureDevOpsUrl.getTag())) - .withName(azureDevOpsUrl.getRepository()), - project -> { - final String location = project.getSource().getLocation(); - if (location.equals(azureDevOpsUrl.getRepositoryLocation())) { - project.getSource().setBranch(azureDevOpsUrl.getBranch()); - project.getSource().setTag(azureDevOpsUrl.getTag()); - } - }); - - return factory; - } } @Override diff --git a/wsmaster/che-core-api-factory-bitbucket-server/pom.xml b/wsmaster/che-core-api-factory-bitbucket-server/pom.xml index dc2a4df1995..3aeed59630c 100644 --- a/wsmaster/che-core-api-factory-bitbucket-server/pom.xml +++ b/wsmaster/che-core-api-factory-bitbucket-server/pom.xml @@ -94,10 +94,6 @@ org.eclipse.che.core che-core-api-workspace - - org.eclipse.che.core - che-core-api-workspace-shared - org.eclipse.che.core che-core-commons-annotations diff --git a/wsmaster/che-core-api-factory-bitbucket-server/src/main/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketServerAuthorizingFactoryParametersResolver.java b/wsmaster/che-core-api-factory-bitbucket-server/src/main/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketServerAuthorizingFactoryParametersResolver.java index 37c61bbe383..61e95ccc5a4 100644 --- a/wsmaster/che-core-api-factory-bitbucket-server/src/main/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketServerAuthorizingFactoryParametersResolver.java +++ b/wsmaster/che-core-api-factory-bitbucket-server/src/main/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketServerAuthorizingFactoryParametersResolver.java @@ -27,13 +27,10 @@ import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.FactoryMetaDto; import org.eclipse.che.api.factory.shared.dto.FactoryVisitor; import org.eclipse.che.api.factory.shared.dto.ScmInfoDto; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; -import org.eclipse.che.api.workspace.shared.dto.devfile.ProjectDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.SourceDto; /** * Provides Factory Parameters resolver for both public and private bitbucket repositories. @@ -134,34 +131,6 @@ public FactoryDevfileV2Dto visit(FactoryDevfileV2Dto factoryDto) { } return factoryDto.withScmInfo(scmInfo); } - - @Override - public FactoryDto visit(FactoryDto factory) { - if (factory.getDevfile() == null) { - // initialize default devfile - factory.setDevfile( - urlFactoryBuilder.buildDefaultDevfile(bitbucketServerUrl.getRepository())); - } - - updateProjects( - factory.getDevfile(), - () -> - newDto(ProjectDto.class) - .withSource( - newDto(SourceDto.class) - .withLocation(bitbucketServerUrl.repositoryLocation()) - .withType("git") - .withBranch(bitbucketServerUrl.getBranch())) - .withName(bitbucketServerUrl.getRepository()), - project -> { - final String location = project.getSource().getLocation(); - if (location.equals(bitbucketServerUrl.repositoryLocation())) { - project.getSource().setBranch(bitbucketServerUrl.getBranch()); - } - }); - - return factory; - } } @Override diff --git a/wsmaster/che-core-api-factory-bitbucket-server/src/test/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketServerAuthorizingFactoryParametersResolverTest.java b/wsmaster/che-core-api-factory-bitbucket-server/src/test/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketServerAuthorizingFactoryParametersResolverTest.java index 2d2657227e5..90b1df33a8f 100644 --- a/wsmaster/che-core-api-factory-bitbucket-server/src/test/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketServerAuthorizingFactoryParametersResolverTest.java +++ b/wsmaster/che-core-api-factory-bitbucket-server/src/test/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketServerAuthorizingFactoryParametersResolverTest.java @@ -14,7 +14,6 @@ import static java.util.Collections.singletonMap; import static org.eclipse.che.api.factory.shared.Constants.CURRENT_VERSION; import static org.eclipse.che.api.factory.shared.Constants.URL_PARAMETER_NAME; -import static org.eclipse.che.api.workspace.server.devfile.Constants.CURRENT_API_VERSION; import static org.eclipse.che.dto.server.DtoFactory.newDto; import static org.eclipse.che.security.oauth1.OAuthAuthenticationService.ERROR_QUERY_NAME; import static org.mockito.ArgumentMatchers.any; @@ -40,12 +39,8 @@ import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.ScmInfoDto; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; -import org.eclipse.che.api.workspace.shared.dto.devfile.DevfileDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.MetadataDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.SourceDto; import org.eclipse.che.security.oauth.OAuthAPI; import org.mockito.Mock; import org.mockito.testng.MockitoTestNGListener; @@ -131,21 +126,21 @@ public void shouldSetDefaultProjectIntoDevfileIfNotSpecified() throws Exception String bitbucketUrl = "http://bitbucket.2mcl.com/users/test/repos/repo/browse?at=refs%2Fheads%2Ffoobar"; - FactoryDto computedFactory = generateDevfileFactory(); + FactoryDevfileV2Dto factoryDevfileV2Dto = generateDevfileV2Factory(); when(urlFactoryBuilder.createFactoryFromDevfile( any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) - .thenReturn(Optional.of(computedFactory)); + .thenReturn(Optional.of(factoryDevfileV2Dto)); Map params = ImmutableMap.of(URL_PARAMETER_NAME, bitbucketUrl); // when - FactoryDto factory = - (FactoryDto) bitbucketServerFactoryParametersResolver.createFactory(params); + FactoryDevfileV2Dto factory = + (FactoryDevfileV2Dto) bitbucketServerFactoryParametersResolver.createFactory(params); // then assertNotNull(factory.getDevfile()); - SourceDto source = factory.getDevfile().getProjects().get(0).getSource(); - assertEquals(source.getLocation(), "http://bitbucket.2mcl.com/scm/~test/repo.git"); - assertEquals(source.getBranch(), "refs%2Fheads%2Ffoobar"); + ScmInfoDto source = factory.getScmInfo(); + assertEquals(source.getRepositoryUrl(), "http://bitbucket.2mcl.com/scm/~test/repo.git"); + assertEquals(source.getBranch(), "foobar"); } @Test @@ -172,16 +167,6 @@ public void shouldSetScmInfoIntoDevfileV2() throws Exception { assertEquals(scmInfo.getBranch(), "foobar"); } - private FactoryDto generateDevfileFactory() { - return newDto(FactoryDto.class) - .withV(CURRENT_VERSION) - .withSource("repo") - .withDevfile( - newDto(DevfileDto.class) - .withApiVersion(CURRENT_API_VERSION) - .withMetadata(newDto(MetadataDto.class).withName("che"))); - } - private FactoryDevfileV2Dto generateDevfileV2Factory() { return newDto(FactoryDevfileV2Dto.class) .withV(CURRENT_VERSION) @@ -197,7 +182,7 @@ public void shouldCreateFactoryWithoutAuthentication() throws ApiException { ImmutableMap.of(URL_PARAMETER_NAME, bitbucketServerUrl, ERROR_QUERY_NAME, "access_denied"); when(urlFactoryBuilder.createFactoryFromDevfile( any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) - .thenReturn(Optional.of(generateDevfileFactory())); + .thenReturn(Optional.of(generateDevfileV2Factory())); // when bitbucketServerFactoryParametersResolver.createFactory(params); diff --git a/wsmaster/che-core-api-factory-bitbucket/src/main/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketFactoryParametersResolver.java b/wsmaster/che-core-api-factory-bitbucket/src/main/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketFactoryParametersResolver.java index 7e828904f78..be0e44ab892 100644 --- a/wsmaster/che-core-api-factory-bitbucket/src/main/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketFactoryParametersResolver.java +++ b/wsmaster/che-core-api-factory-bitbucket/src/main/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketFactoryParametersResolver.java @@ -24,17 +24,13 @@ import org.eclipse.che.api.factory.server.FactoryParametersResolver; import org.eclipse.che.api.factory.server.scm.AuthorisationRequestManager; import org.eclipse.che.api.factory.server.scm.PersonalAccessTokenManager; -import org.eclipse.che.api.factory.server.urlfactory.ProjectConfigDtoMerger; import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.FactoryMetaDto; import org.eclipse.che.api.factory.shared.dto.FactoryVisitor; import org.eclipse.che.api.factory.shared.dto.ScmInfoDto; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; -import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.ProjectDto; /** Provides Factory Parameters resolver for bitbucket repositories. */ @Singleton @@ -51,8 +47,6 @@ public class BitbucketFactoryParametersResolver extends BaseFactoryParameterReso private final BitbucketSourceStorageBuilder bitbucketSourceStorageBuilder; private final URLFactoryBuilder urlFactoryBuilder; - /** ProjectDtoMerger */ - private final ProjectConfigDtoMerger projectConfigDtoMerger; /** Personal Access Token manager used when fetching protected content. */ private final PersonalAccessTokenManager personalAccessTokenManager; @@ -65,7 +59,6 @@ public BitbucketFactoryParametersResolver( URLFetcher urlFetcher, BitbucketSourceStorageBuilder bitbucketSourceStorageBuilder, URLFactoryBuilder urlFactoryBuilder, - ProjectConfigDtoMerger projectConfigDtoMerger, PersonalAccessTokenManager personalAccessTokenManager, BitbucketApiClient bitbucketApiClient, AuthorisationRequestManager authorisationRequestManager) { @@ -74,7 +67,6 @@ public BitbucketFactoryParametersResolver( this.urlFetcher = urlFetcher; this.bitbucketSourceStorageBuilder = bitbucketSourceStorageBuilder; this.urlFactoryBuilder = urlFactoryBuilder; - this.projectConfigDtoMerger = projectConfigDtoMerger; this.personalAccessTokenManager = personalAccessTokenManager; this.bitbucketApiClient = bitbucketApiClient; } @@ -142,40 +134,6 @@ public FactoryDevfileV2Dto visit(FactoryDevfileV2Dto factoryDto) { } return factoryDto.withScmInfo(scmInfo); } - - @Override - public FactoryDto visit(FactoryDto factory) { - if (factory.getWorkspace() != null) { - return projectConfigDtoMerger.merge( - factory, - () -> { - // Compute project configuration - return newDto(ProjectConfigDto.class) - .withSource( - bitbucketSourceStorageBuilder.buildWorkspaceConfigSource(bitbucketUrl)) - .withName(bitbucketUrl.getRepository()) - .withPath("/".concat(bitbucketUrl.getRepository())); - }); - } else if (factory.getDevfile() == null) { - // initialize default devfile - factory.setDevfile(urlFactoryBuilder.buildDefaultDevfile(bitbucketUrl.getRepository())); - } - - updateProjects( - factory.getDevfile(), - () -> - newDto(ProjectDto.class) - .withSource(bitbucketSourceStorageBuilder.buildDevfileSource(bitbucketUrl)) - .withName(bitbucketUrl.getRepository()), - project -> { - final String location = project.getSource().getLocation(); - if (location.equals(bitbucketUrl.repositoryLocation())) { - project.getSource().setBranch(bitbucketUrl.getBranch()); - } - }); - - return factory; - } } @Override diff --git a/wsmaster/che-core-api-factory-bitbucket/src/test/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketFactoryParametersResolverTest.java b/wsmaster/che-core-api-factory-bitbucket/src/test/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketFactoryParametersResolverTest.java index 48b79828082..b41510c3acd 100644 --- a/wsmaster/che-core-api-factory-bitbucket/src/test/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketFactoryParametersResolverTest.java +++ b/wsmaster/che-core-api-factory-bitbucket/src/test/java/org/eclipse/che/api/factory/server/bitbucket/BitbucketFactoryParametersResolverTest.java @@ -14,24 +14,20 @@ import static java.util.Collections.singletonMap; import static org.eclipse.che.api.factory.shared.Constants.CURRENT_VERSION; import static org.eclipse.che.api.factory.shared.Constants.URL_PARAMETER_NAME; -import static org.eclipse.che.api.workspace.server.devfile.Constants.CURRENT_API_VERSION; import static org.eclipse.che.dto.server.DtoFactory.newDto; import static org.eclipse.che.security.oauth1.OAuthAuthenticationService.ERROR_QUERY_NAME; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.never; 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 static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import com.google.common.collect.ImmutableMap; -import java.util.Collections; import java.util.Map; import java.util.Optional; import org.eclipse.che.api.core.ApiException; @@ -39,18 +35,12 @@ import org.eclipse.che.api.factory.server.scm.AuthorisationRequestManager; import org.eclipse.che.api.factory.server.scm.PersonalAccessTokenManager; import org.eclipse.che.api.factory.server.urlfactory.DevfileFilenamesProvider; -import org.eclipse.che.api.factory.server.urlfactory.ProjectConfigDtoMerger; import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.ScmInfoDto; import org.eclipse.che.api.workspace.server.devfile.FileContentProvider; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; -import org.eclipse.che.api.workspace.shared.dto.devfile.DevfileDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.MetadataDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.ProjectDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.SourceDto; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -78,9 +68,6 @@ public class BitbucketFactoryParametersResolverTest { private BitbucketSourceStorageBuilder bitbucketSourceStorageBuilder = new BitbucketSourceStorageBuilder(); - /** ProjectDtoMerger */ - @Mock private ProjectConfigDtoMerger projectConfigDtoMerger; - /** Parser which will allow to check validity of URLs and create objects. */ @Mock private URLFactoryBuilder urlFactoryBuilder; @@ -89,7 +76,8 @@ public class BitbucketFactoryParametersResolverTest { /** * Capturing the location parameter when calling {@link - * URLFactoryBuilder#createFactoryFromDevfile(RemoteFactoryUrl, FileContentProvider, Map)} + * URLFactoryBuilder#createFactoryFromDevfile(RemoteFactoryUrl, FileContentProvider, Map, + * boolean)} */ @Captor private ArgumentCaptor factoryUrlArgumentCaptor; @@ -106,7 +94,6 @@ protected void init() { urlFetcher, bitbucketSourceStorageBuilder, urlFactoryBuilder, - projectConfigDtoMerger, personalAccessTokenManager, bitbucketApiClient, authorisationRequestManager); @@ -159,85 +146,6 @@ public void shouldGenerateDevfileForFactoryWithNoDevfile() throws Exception { assertEquals(scmInfo.getBranch(), null); } - @Test - public void shouldReturnFactoryFromRepositoryWithDevfile() throws Exception { - - when(devfileFilenamesProvider.getConfiguredDevfileFilenames()) - .thenReturn(Collections.singletonList("devfile.yaml")); - - String bitbucketUrl = "https://bitbucket.org/eclipse/che"; - - FactoryDto computedFactory = generateDevfileFactory(); - - when(urlFactoryBuilder.createFactoryFromDevfile( - any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) - .thenReturn(Optional.of(computedFactory)); - - Map params = ImmutableMap.of(URL_PARAMETER_NAME, bitbucketUrl); - // when - FactoryDto factory = (FactoryDto) bitbucketFactoryParametersResolver.createFactory(params); - // then - assertNotNull(factory.getDevfile()); - assertNull(factory.getWorkspace()); - - // check we called the builder with the following devfile file - verify(urlFactoryBuilder) - .createFactoryFromDevfile( - factoryUrlArgumentCaptor.capture(), any(), anyMap(), anyBoolean()); - verify(urlFactoryBuilder, never()).buildDefaultDevfile(eq("che")); - assertEquals( - factoryUrlArgumentCaptor.getValue().devfileFileLocations().iterator().next().location(), - "https://bitbucket.org/eclipse/che/raw/HEAD/devfile.yaml"); - } - - @Test - public void shouldSetDefaultProjectIntoDevfileIfNotSpecified() throws Exception { - - String bitbucketUrl = "https://bitbucket.org/eclipse/che/src/foobar"; - - FactoryDto computedFactory = generateDevfileFactory(); - - when(urlFactoryBuilder.createFactoryFromDevfile( - any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) - .thenReturn(Optional.of(computedFactory)); - - Map params = ImmutableMap.of(URL_PARAMETER_NAME, bitbucketUrl); - // when - FactoryDto factory = (FactoryDto) bitbucketFactoryParametersResolver.createFactory(params); - // then - assertNotNull(factory.getDevfile()); - SourceDto source = factory.getDevfile().getProjects().get(0).getSource(); - assertEquals(source.getLocation(), "https://bitbucket.org/eclipse/che.git"); - assertEquals(source.getBranch(), "foobar"); - } - - @Test - public void shouldSetBranchIntoDevfileIfNotMatchesCurrent() throws Exception { - - String bitbucketUrl = "https://bitbucket.org/eclipse/che/src/foobranch"; - - FactoryDto computedFactory = generateDevfileFactory(); - computedFactory - .getDevfile() - .getProjects() - .add( - newDto(ProjectDto.class) - .withSource( - newDto(SourceDto.class).withLocation("https://bitbucket.org/eclipse/che.git"))); - - when(urlFactoryBuilder.createFactoryFromDevfile( - any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) - .thenReturn(Optional.of(computedFactory)); - - Map params = ImmutableMap.of(URL_PARAMETER_NAME, bitbucketUrl); - // when - FactoryDto factory = (FactoryDto) bitbucketFactoryParametersResolver.createFactory(params); - // then - assertNotNull(factory.getDevfile()); - SourceDto source = factory.getDevfile().getProjects().get(0).getSource(); - assertEquals(source.getBranch(), "foobranch"); - } - @Test public void shouldSetScmInfoIntoDevfileV2() throws Exception { @@ -261,16 +169,6 @@ public void shouldSetScmInfoIntoDevfileV2() throws Exception { assertEquals(scmInfo.getBranch(), "foobar"); } - private FactoryDto generateDevfileFactory() { - return newDto(FactoryDto.class) - .withV(CURRENT_VERSION) - .withSource("repo") - .withDevfile( - newDto(DevfileDto.class) - .withApiVersion(CURRENT_API_VERSION) - .withMetadata(newDto(MetadataDto.class).withName("che"))); - } - private FactoryDevfileV2Dto generateDevfileV2Factory() { return newDto(FactoryDevfileV2Dto.class) .withV(CURRENT_VERSION) @@ -286,7 +184,7 @@ public void shouldCreateFactoryWithoutAuthentication() throws ApiException { ImmutableMap.of(URL_PARAMETER_NAME, bitbucketUrl, ERROR_QUERY_NAME, "access_denied"); when(urlFactoryBuilder.createFactoryFromDevfile( any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) - .thenReturn(Optional.of(generateDevfileFactory())); + .thenReturn(Optional.of(generateDevfileV2Factory())); // when bitbucketFactoryParametersResolver.createFactory(params); diff --git a/wsmaster/che-core-api-factory-git-ssh/pom.xml b/wsmaster/che-core-api-factory-git-ssh/pom.xml index 4bfa5aee91f..62619149716 100644 --- a/wsmaster/che-core-api-factory-git-ssh/pom.xml +++ b/wsmaster/che-core-api-factory-git-ssh/pom.xml @@ -54,10 +54,6 @@ org.eclipse.che.core che-core-api-workspace - - org.eclipse.che.core - che-core-api-workspace-shared - ch.qos.logback logback-classic diff --git a/wsmaster/che-core-api-factory-git-ssh/src/main/java/org/eclipse/che/api/factory/server/git/ssh/GitSshFactoryParametersResolver.java b/wsmaster/che-core-api-factory-git-ssh/src/main/java/org/eclipse/che/api/factory/server/git/ssh/GitSshFactoryParametersResolver.java index cc5ae1058aa..890e3a8b255 100644 --- a/wsmaster/che-core-api-factory-git-ssh/src/main/java/org/eclipse/che/api/factory/server/git/ssh/GitSshFactoryParametersResolver.java +++ b/wsmaster/che-core-api-factory-git-ssh/src/main/java/org/eclipse/che/api/factory/server/git/ssh/GitSshFactoryParametersResolver.java @@ -29,13 +29,10 @@ import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.FactoryMetaDto; import org.eclipse.che.api.factory.shared.dto.FactoryVisitor; import org.eclipse.che.api.factory.shared.dto.ScmInfoDto; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; -import org.eclipse.che.api.workspace.shared.dto.devfile.ProjectDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.SourceDto; /** * Provides Factory Parameters resolver for Git Ssh repositories. @@ -93,7 +90,8 @@ public FactoryMetaDto createFactory(@NotNull final Map factoryPa gitSshUrl, urlFetcher, personalAccessTokenManager), extractOverrideParams(factoryParameters), true) - .orElseGet(() -> newDto(FactoryDto.class).withV(CURRENT_VERSION).withSource("repo")) + .orElseGet( + () -> newDto(FactoryDevfileV2Dto.class).withV(CURRENT_VERSION).withSource("repo")) .acceptVisitor(new GitSshFactoryVisitor(gitSshUrl)); } @@ -117,26 +115,6 @@ public FactoryDevfileV2Dto visit(FactoryDevfileV2Dto factoryDto) { .withRepositoryUrl(gitSshUrl.getRepositoryLocation()); return factoryDto.withScmInfo(scmInfo); } - - @Override - public FactoryDto visit(FactoryDto factory) { - if (factory.getDevfile() == null) { - factory.setDevfile(urlFactoryBuilder.buildDefaultDevfile(gitSshUrl.getRepository())); - } - - updateProjects( - factory.getDevfile(), - () -> - newDto(ProjectDto.class) - .withSource( - newDto(SourceDto.class) - .withLocation(gitSshUrl.getRepositoryLocation()) - .withType("git")) - .withName(gitSshUrl.getRepository()), - project -> {}); - - return factory; - } } @Override diff --git a/wsmaster/che-core-api-factory-github-common/src/main/java/org/eclipse/che/api/factory/server/github/AbstractGithubFactoryParametersResolver.java b/wsmaster/che-core-api-factory-github-common/src/main/java/org/eclipse/che/api/factory/server/github/AbstractGithubFactoryParametersResolver.java index 0aed63b4929..5415bb7d10f 100644 --- a/wsmaster/che-core-api-factory-github-common/src/main/java/org/eclipse/che/api/factory/server/github/AbstractGithubFactoryParametersResolver.java +++ b/wsmaster/che-core-api-factory-github-common/src/main/java/org/eclipse/che/api/factory/server/github/AbstractGithubFactoryParametersResolver.java @@ -23,13 +23,10 @@ import org.eclipse.che.api.factory.server.FactoryParametersResolver; import org.eclipse.che.api.factory.server.scm.AuthorisationRequestManager; import org.eclipse.che.api.factory.server.scm.PersonalAccessTokenManager; -import org.eclipse.che.api.factory.server.urlfactory.ProjectConfigDtoMerger; import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.factory.shared.dto.*; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; -import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.ProjectDto; /** * Provides Factory Parameters resolver for github repositories. @@ -49,9 +46,6 @@ public abstract class AbstractGithubFactoryParametersResolver extends BaseFactor private final URLFactoryBuilder urlFactoryBuilder; - /** ProjectDtoMerger */ - private final ProjectConfigDtoMerger projectConfigDtoMerger; - private final PersonalAccessTokenManager personalAccessTokenManager; private final String providerName; @@ -62,7 +56,6 @@ public AbstractGithubFactoryParametersResolver( GithubSourceStorageBuilder githubSourceStorageBuilder, AuthorisationRequestManager authorisationRequestManager, URLFactoryBuilder urlFactoryBuilder, - ProjectConfigDtoMerger projectConfigDtoMerger, PersonalAccessTokenManager personalAccessTokenManager, String providerName) { super(authorisationRequestManager, urlFactoryBuilder, providerName); @@ -71,7 +64,6 @@ public AbstractGithubFactoryParametersResolver( this.urlFetcher = urlFetcher; this.githubSourceStorageBuilder = githubSourceStorageBuilder; this.urlFactoryBuilder = urlFactoryBuilder; - this.projectConfigDtoMerger = projectConfigDtoMerger; this.personalAccessTokenManager = personalAccessTokenManager; } @@ -143,39 +135,6 @@ public FactoryDevfileV2Dto visit(FactoryDevfileV2Dto factoryDto) { } return factoryDto.withScmInfo(scmInfo); } - - @Override - public FactoryDto visit(FactoryDto factory) { - if (factory.getWorkspace() != null) { - return projectConfigDtoMerger.merge( - factory, - () -> { - // Compute project configuration - return newDto(ProjectConfigDto.class) - .withSource(githubSourceStorageBuilder.buildWorkspaceConfigSource(githubUrl)) - .withName(githubUrl.getRepository()) - .withPath("/".concat(githubUrl.getRepository())); - }); - } else if (factory.getDevfile() == null) { - // initialize default devfile - factory.setDevfile(urlFactoryBuilder.buildDefaultDevfile(githubUrl.getRepository())); - } - - updateProjects( - factory.getDevfile(), - () -> - newDto(ProjectDto.class) - .withSource(githubSourceStorageBuilder.buildDevfileSource(githubUrl)) - .withName(githubUrl.getRepository()), - project -> { - final String location = project.getSource().getLocation(); - if (location.equals(githubUrl.repositoryLocation())) { - project.getSource().setBranch(githubUrl.getBranch()); - } - }); - - return factory; - } } @Override diff --git a/wsmaster/che-core-api-factory-github/pom.xml b/wsmaster/che-core-api-factory-github/pom.xml index 46a8a79ad40..54c0333b905 100644 --- a/wsmaster/che-core-api-factory-github/pom.xml +++ b/wsmaster/che-core-api-factory-github/pom.xml @@ -74,10 +74,6 @@ org.eclipse.che.core che-core-api-workspace - - org.eclipse.che.core - che-core-api-workspace-shared - org.eclipse.che.core che-core-commons-annotations diff --git a/wsmaster/che-core-api-factory-github/src/main/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolver.java b/wsmaster/che-core-api-factory-github/src/main/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolver.java index 462505bde64..cba97c04441 100644 --- a/wsmaster/che-core-api-factory-github/src/main/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolver.java +++ b/wsmaster/che-core-api-factory-github/src/main/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolver.java @@ -15,7 +15,6 @@ import javax.inject.Singleton; import org.eclipse.che.api.factory.server.scm.AuthorisationRequestManager; import org.eclipse.che.api.factory.server.scm.PersonalAccessTokenManager; -import org.eclipse.che.api.factory.server.urlfactory.ProjectConfigDtoMerger; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; @@ -36,7 +35,6 @@ public GithubFactoryParametersResolver( GithubSourceStorageBuilder githubSourceStorageBuilder, AuthorisationRequestManager authorisationRequestManager, URLFactoryBuilder urlFactoryBuilder, - ProjectConfigDtoMerger projectConfigDtoMerger, PersonalAccessTokenManager personalAccessTokenManager) { super( githubUrlParser, @@ -44,7 +42,6 @@ public GithubFactoryParametersResolver( githubSourceStorageBuilder, authorisationRequestManager, urlFactoryBuilder, - projectConfigDtoMerger, personalAccessTokenManager, PROVIDER_NAME); } diff --git a/wsmaster/che-core-api-factory-github/src/main/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolverSecond.java b/wsmaster/che-core-api-factory-github/src/main/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolverSecond.java index 20a37cbd8d6..d2f25992f81 100644 --- a/wsmaster/che-core-api-factory-github/src/main/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolverSecond.java +++ b/wsmaster/che-core-api-factory-github/src/main/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolverSecond.java @@ -15,7 +15,6 @@ import javax.inject.Singleton; import org.eclipse.che.api.factory.server.scm.AuthorisationRequestManager; import org.eclipse.che.api.factory.server.scm.PersonalAccessTokenManager; -import org.eclipse.che.api.factory.server.urlfactory.ProjectConfigDtoMerger; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; @@ -36,7 +35,6 @@ public GithubFactoryParametersResolverSecond( GithubSourceStorageBuilder githubSourceStorageBuilder, AuthorisationRequestManager authorisationRequestManager, URLFactoryBuilder urlFactoryBuilder, - ProjectConfigDtoMerger projectConfigDtoMerger, PersonalAccessTokenManager personalAccessTokenManager) { super( githubUrlParser, @@ -44,7 +42,6 @@ public GithubFactoryParametersResolverSecond( githubSourceStorageBuilder, authorisationRequestManager, urlFactoryBuilder, - projectConfigDtoMerger, personalAccessTokenManager, PROVIDER_NAME); } diff --git a/wsmaster/che-core-api-factory-github/src/test/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolverTest.java b/wsmaster/che-core-api-factory-github/src/test/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolverTest.java index e7374efca6d..a8dcac141ef 100644 --- a/wsmaster/che-core-api-factory-github/src/test/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolverTest.java +++ b/wsmaster/che-core-api-factory-github/src/test/java/org/eclipse/che/api/factory/server/github/GithubFactoryParametersResolverTest.java @@ -14,7 +14,6 @@ import static java.util.Collections.singletonMap; import static org.eclipse.che.api.factory.shared.Constants.CURRENT_VERSION; import static org.eclipse.che.api.factory.shared.Constants.URL_PARAMETER_NAME; -import static org.eclipse.che.api.workspace.server.devfile.Constants.CURRENT_API_VERSION; import static org.eclipse.che.dto.server.DtoFactory.newDto; import static org.eclipse.che.security.oauth1.OAuthAuthenticationService.ERROR_QUERY_NAME; import static org.mockito.ArgumentMatchers.any; @@ -29,11 +28,9 @@ 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.ImmutableMap; -import java.util.Collections; import java.util.Map; import java.util.Optional; import org.eclipse.che.api.core.ApiException; @@ -41,18 +38,12 @@ import org.eclipse.che.api.factory.server.scm.AuthorisationRequestManager; import org.eclipse.che.api.factory.server.scm.PersonalAccessTokenManager; import org.eclipse.che.api.factory.server.urlfactory.DevfileFilenamesProvider; -import org.eclipse.che.api.factory.server.urlfactory.ProjectConfigDtoMerger; import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.ScmInfoDto; import org.eclipse.che.api.workspace.server.devfile.FileContentProvider; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; -import org.eclipse.che.api.workspace.shared.dto.devfile.DevfileDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.MetadataDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.ProjectDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.SourceDto; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -83,9 +74,6 @@ public class GithubFactoryParametersResolverTest { @Spy private GithubSourceStorageBuilder githubSourceStorageBuilder = new GithubSourceStorageBuilder(); - /** ProjectDtoMerger */ - @Mock private ProjectConfigDtoMerger projectConfigDtoMerger; - /** Parser which will allow to check validity of URLs and create objects. */ private URLFactoryBuilder urlFactoryBuilder; @@ -95,7 +83,7 @@ public class GithubFactoryParametersResolverTest { /** * Capturing the location parameter when calling {@link * URLFactoryBuilder#createFactoryFromDevfile(RemoteFactoryUrl, FileContentProvider, Map, - * Boolean)} + * boolean)} */ @Captor private ArgumentCaptor factoryUrlArgumentCaptor; @@ -118,7 +106,6 @@ protected void init() throws Exception { githubSourceStorageBuilder, authorisationRequestManager, urlFactoryBuilder, - projectConfigDtoMerger, personalAccessTokenManager); assertNotNull(this.abstractGithubFactoryParametersResolver); } @@ -207,94 +194,6 @@ public void shouldNotSkipAuthenticationWhenNoErrorParameterPassed() throws Excep any(RemoteFactoryUrl.class), any(FileContentProvider.class), anyMap(), eq(false)); } - @Test - public void shouldReturnFactoryFromRepositoryWithDevfile() throws Exception { - - when(devfileFilenamesProvider.getConfiguredDevfileFilenames()) - .thenReturn(Collections.singletonList("devfile.yaml")); - - String githubUrl = "https://github.com/eclipse/che"; - - FactoryDto computedFactory = generateDevfileFactory(); - - when(urlFactoryBuilder.createFactoryFromDevfile( - any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) - .thenReturn(Optional.of(computedFactory)); - when(githubApiClient.isConnected(eq("https://github.com"))).thenReturn(true); - when(githubApiClient.getLatestCommit(anyString(), anyString(), anyString(), any())) - .thenReturn(new GithubCommit().withSha("13bbd0d4605a6ed3350f7b15eb02c4d4e6f8df6e")); - - Map params = ImmutableMap.of(URL_PARAMETER_NAME, githubUrl); - // when - FactoryDto factory = (FactoryDto) abstractGithubFactoryParametersResolver.createFactory(params); - // then - assertNotNull(factory.getDevfile()); - assertNull(factory.getWorkspace()); - - // check we called the builder with the following devfile file - verify(urlFactoryBuilder) - .createFactoryFromDevfile( - factoryUrlArgumentCaptor.capture(), any(), anyMap(), anyBoolean()); - verify(urlFactoryBuilder, never()).buildDefaultDevfile(eq("che")); - assertEquals( - factoryUrlArgumentCaptor.getValue().devfileFileLocations().iterator().next().location(), - "https://raw.githubusercontent.com/eclipse/che/13bbd0d4605a6ed3350f7b15eb02c4d4e6f8df6e/devfile.yaml"); - } - - @Test - public void shouldSetDefaultProjectIntoDevfileIfNotSpecified() throws Exception { - - String githubUrl = "https://github.com/eclipse/che/tree/foobar"; - - FactoryDto computedFactory = generateDevfileFactory(); - - when(urlFactoryBuilder.createFactoryFromDevfile( - any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) - .thenReturn(Optional.of(computedFactory)); - when(githubApiClient.isConnected(eq("https://github.com"))).thenReturn(true); - when(githubApiClient.getLatestCommit(anyString(), anyString(), anyString(), any())) - .thenReturn(new GithubCommit().withSha("test-sha")); - - Map params = ImmutableMap.of(URL_PARAMETER_NAME, githubUrl); - // when - FactoryDto factory = (FactoryDto) abstractGithubFactoryParametersResolver.createFactory(params); - // then - assertNotNull(factory.getDevfile()); - SourceDto source = factory.getDevfile().getProjects().get(0).getSource(); - assertEquals(source.getLocation(), "https://github.com/eclipse/che.git"); - assertEquals(source.getBranch(), "foobar"); - } - - @Test - public void shouldSetBranchIntoDevfileIfNotMatchesCurrent() throws Exception { - - String githubUrl = "https://github.com/eclipse/che/tree/foobranch"; - - FactoryDto computedFactory = generateDevfileFactory(); - computedFactory - .getDevfile() - .getProjects() - .add( - newDto(ProjectDto.class) - .withSource( - newDto(SourceDto.class).withLocation("https://github.com/eclipse/che.git"))); - - when(urlFactoryBuilder.createFactoryFromDevfile( - any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) - .thenReturn(Optional.of(computedFactory)); - when(githubApiClient.isConnected(eq("https://github.com"))).thenReturn(true); - when(githubApiClient.getLatestCommit(anyString(), anyString(), anyString(), any())) - .thenReturn(new GithubCommit().withSha("test-sha")); - - Map params = ImmutableMap.of(URL_PARAMETER_NAME, githubUrl); - // when - FactoryDto factory = (FactoryDto) abstractGithubFactoryParametersResolver.createFactory(params); - // then - assertNotNull(factory.getDevfile()); - SourceDto source = factory.getDevfile().getProjects().get(0).getSource(); - assertEquals(source.getBranch(), "foobranch"); - } - @Test public void shouldSetScmInfoIntoDevfileV2() throws Exception { @@ -329,7 +228,7 @@ public void shouldCreateFactoryWithoutAuthentication() throws ApiException { ImmutableMap.of(URL_PARAMETER_NAME, githubUrl, ERROR_QUERY_NAME, "access_denied"); when(urlFactoryBuilder.createFactoryFromDevfile( any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) - .thenReturn(Optional.of(generateDevfileFactory())); + .thenReturn(Optional.of(generateDevfileV2Factory())); // when abstractGithubFactoryParametersResolver.createFactory(params); @@ -355,7 +254,6 @@ public void shouldParseFactoryUrlWithAuthentication() throws Exception { githubSourceStorageBuilder, authorisationRequestManager, urlFactoryBuilder, - projectConfigDtoMerger, personalAccessTokenManager); when(authorisationRequestManager.isStored(eq("github"))).thenReturn(true); // when @@ -377,7 +275,6 @@ public void shouldParseFactoryUrlWithOutAuthentication() throws Exception { githubSourceStorageBuilder, authorisationRequestManager, urlFactoryBuilder, - projectConfigDtoMerger, personalAccessTokenManager); when(authorisationRequestManager.isStored(eq("github"))).thenReturn(false); // when @@ -387,16 +284,6 @@ public void shouldParseFactoryUrlWithOutAuthentication() throws Exception { verify(githubUrlParser, never()).parseWithoutAuthentication("url"); } - private FactoryDto generateDevfileFactory() { - return newDto(FactoryDto.class) - .withV(CURRENT_VERSION) - .withSource("repo") - .withDevfile( - newDto(DevfileDto.class) - .withApiVersion(CURRENT_API_VERSION) - .withMetadata(newDto(MetadataDto.class).withName("che"))); - } - private FactoryDevfileV2Dto generateDevfileV2Factory() { return newDto(FactoryDevfileV2Dto.class) .withV(CURRENT_VERSION) diff --git a/wsmaster/che-core-api-factory-gitlab/pom.xml b/wsmaster/che-core-api-factory-gitlab/pom.xml index 3325af242a9..d4933510d4d 100644 --- a/wsmaster/che-core-api-factory-gitlab/pom.xml +++ b/wsmaster/che-core-api-factory-gitlab/pom.xml @@ -79,10 +79,6 @@ org.eclipse.che.core che-core-api-workspace - - org.eclipse.che.core - che-core-api-workspace-shared - org.eclipse.che.core che-core-commons-annotations diff --git a/wsmaster/che-core-api-factory-gitlab/src/main/java/org/eclipse/che/api/factory/server/gitlab/GitlabFactoryParametersResolver.java b/wsmaster/che-core-api-factory-gitlab/src/main/java/org/eclipse/che/api/factory/server/gitlab/GitlabFactoryParametersResolver.java index cca0a9b21a2..b9bfd2024a1 100644 --- a/wsmaster/che-core-api-factory-gitlab/src/main/java/org/eclipse/che/api/factory/server/gitlab/GitlabFactoryParametersResolver.java +++ b/wsmaster/che-core-api-factory-gitlab/src/main/java/org/eclipse/che/api/factory/server/gitlab/GitlabFactoryParametersResolver.java @@ -27,13 +27,10 @@ import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.FactoryMetaDto; import org.eclipse.che.api.factory.shared.dto.FactoryVisitor; import org.eclipse.che.api.factory.shared.dto.ScmInfoDto; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; -import org.eclipse.che.api.workspace.shared.dto.devfile.ProjectDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.SourceDto; /** * Provides Factory Parameters resolver for Gitlab repositories. @@ -126,34 +123,6 @@ public FactoryDevfileV2Dto visit(FactoryDevfileV2Dto factoryDto) { } return factoryDto.withScmInfo(scmInfo); } - - @Override - public FactoryDto visit(FactoryDto factory) { - - if (factory.getDevfile() == null) { - // initialize default devfile - factory.setDevfile(urlFactoryBuilder.buildDefaultDevfile(gitlabUrl.getProject())); - } - - updateProjects( - factory.getDevfile(), - () -> - newDto(ProjectDto.class) - .withSource( - newDto(SourceDto.class) - .withLocation(gitlabUrl.repositoryLocation()) - .withType("git") - .withBranch(gitlabUrl.getBranch())) - .withName(gitlabUrl.getProject()), - project -> { - final String location = project.getSource().getLocation(); - if (location.equals(gitlabUrl.repositoryLocation())) { - project.getSource().setBranch(gitlabUrl.getBranch()); - } - }); - - return factory; - } } @Override diff --git a/wsmaster/che-core-api-factory-gitlab/src/test/java/org/eclipse/che/api/factory/server/gitlab/GitlabFactoryParametersResolverTest.java b/wsmaster/che-core-api-factory-gitlab/src/test/java/org/eclipse/che/api/factory/server/gitlab/GitlabFactoryParametersResolverTest.java index af93f29228d..a6381aa8f08 100644 --- a/wsmaster/che-core-api-factory-gitlab/src/test/java/org/eclipse/che/api/factory/server/gitlab/GitlabFactoryParametersResolverTest.java +++ b/wsmaster/che-core-api-factory-gitlab/src/test/java/org/eclipse/che/api/factory/server/gitlab/GitlabFactoryParametersResolverTest.java @@ -14,7 +14,6 @@ import static java.util.Collections.singletonMap; import static org.eclipse.che.api.factory.shared.Constants.CURRENT_VERSION; import static org.eclipse.che.api.factory.shared.Constants.URL_PARAMETER_NAME; -import static org.eclipse.che.api.workspace.server.devfile.Constants.CURRENT_API_VERSION; import static org.eclipse.che.dto.server.DtoFactory.newDto; import static org.eclipse.che.security.oauth1.OAuthAuthenticationService.ERROR_QUERY_NAME; import static org.mockito.ArgumentMatchers.any; @@ -40,12 +39,8 @@ import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.ScmInfoDto; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; -import org.eclipse.che.api.workspace.shared.dto.devfile.DevfileDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.MetadataDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.SourceDto; import org.mockito.Mock; import org.mockito.testng.MockitoTestNGListener; import org.testng.annotations.BeforeMethod; @@ -132,7 +127,7 @@ public void shouldSetDefaultProjectIntoDevfileIfNotSpecified() throws Exception String gitlabUrl = "http://gitlab.2mcl.com/test/proj/repo/-/tree/foobar"; - FactoryDto computedFactory = generateDevfileFactory(); + FactoryDevfileV2Dto computedFactory = generateDevfileV2Factory(); when(urlFactoryBuilder.createFactoryFromDevfile( any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) @@ -140,11 +135,12 @@ public void shouldSetDefaultProjectIntoDevfileIfNotSpecified() throws Exception Map params = ImmutableMap.of(URL_PARAMETER_NAME, gitlabUrl); // when - FactoryDto factory = (FactoryDto) gitlabFactoryParametersResolver.createFactory(params); + FactoryDevfileV2Dto factory = + (FactoryDevfileV2Dto) gitlabFactoryParametersResolver.createFactory(params); // then assertNotNull(factory.getDevfile()); - SourceDto source = factory.getDevfile().getProjects().get(0).getSource(); - assertEquals(source.getLocation(), "http://gitlab.2mcl.com/test/proj/repo.git"); + ScmInfoDto source = factory.getScmInfo(); + assertEquals(source.getRepositoryUrl(), "http://gitlab.2mcl.com/test/proj/repo.git"); assertEquals(source.getBranch(), "foobar"); } @@ -156,7 +152,7 @@ public void shouldCreateFactoryWithoutAuthentication() throws ApiException { ImmutableMap.of(URL_PARAMETER_NAME, gitlabUrl, ERROR_QUERY_NAME, "access_denied"); when(urlFactoryBuilder.createFactoryFromDevfile( any(RemoteFactoryUrl.class), any(), anyMap(), anyBoolean())) - .thenReturn(Optional.of(generateDevfileFactory())); + .thenReturn(Optional.of(generateDevfileV2Factory())); // when gitlabFactoryParametersResolver.createFactory(params); @@ -193,16 +189,6 @@ public void shouldSetScmInfoIntoDevfileV2() throws Exception { assertEquals(scmInfo.getBranch(), "foobar"); } - private FactoryDto generateDevfileFactory() { - return newDto(FactoryDto.class) - .withV(CURRENT_VERSION) - .withSource("repo") - .withDevfile( - newDto(DevfileDto.class) - .withApiVersion(CURRENT_API_VERSION) - .withMetadata(newDto(MetadataDto.class).withName("che"))); - } - private FactoryDevfileV2Dto generateDevfileV2Factory() { return newDto(FactoryDevfileV2Dto.class) .withV(CURRENT_VERSION) diff --git a/wsmaster/che-core-api-factory-shared/pom.xml b/wsmaster/che-core-api-factory-shared/pom.xml index 50d17dfbda0..380ae80a568 100644 --- a/wsmaster/che-core-api-factory-shared/pom.xml +++ b/wsmaster/che-core-api-factory-shared/pom.xml @@ -39,10 +39,6 @@ org.eclipse.che.core che-core-api-dto - - org.eclipse.che.core - che-core-api-workspace-shared - org.eclipse.che.core che-core-api-model diff --git a/wsmaster/che-core-api-factory-shared/src/main/java/org/eclipse/che/api/factory/shared/dto/FactoryDto.java b/wsmaster/che-core-api-factory-shared/src/main/java/org/eclipse/che/api/factory/shared/dto/FactoryDto.java deleted file mode 100644 index 8d845467899..00000000000 --- a/wsmaster/che-core-api-factory-shared/src/main/java/org/eclipse/che/api/factory/shared/dto/FactoryDto.java +++ /dev/null @@ -1,78 +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.shared.dto; - -import static org.eclipse.che.api.core.factory.FactoryParameter.Obligation.OPTIONAL; - -import java.util.List; -import org.eclipse.che.api.core.factory.FactoryParameter; -import org.eclipse.che.api.core.model.factory.Factory; -import org.eclipse.che.api.core.rest.shared.dto.Hyperlinks; -import org.eclipse.che.api.core.rest.shared.dto.Link; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.DevfileDto; -import org.eclipse.che.dto.shared.DTO; - -/** - * Factory of version 4.0. - * - *

This 'implementation' of {@link FactoryMetaDto} is used for Devfile v1. - * - * @author Max Shaposhnik - */ -@DTO -public interface FactoryDto extends FactoryMetaDto, Factory, Hyperlinks { - - @Override - default FactoryMetaDto acceptVisitor(FactoryVisitor visitor) { - return visitor.visit(this); - } - - @FactoryParameter(obligation = OPTIONAL) - DevfileDto getDevfile(); - - void setDevfile(DevfileDto devfileDto); - - FactoryDto withDevfile(DevfileDto devfileDto); - - FactoryDto withV(String v); - - @Override - FactoryDto withName(String name); - - @Override - FactoryDto withPolicies(PoliciesDto policies); - - @Override - FactoryDto withIde(IdeDto ide); - - @Override - FactoryDto withId(String id); - - @Override - FactoryDto withSource(String source); - - @Override - FactoryDto withCreator(AuthorDto creator); - - @Override - FactoryDto withLinks(List links); - - /** because factory DTO may have devfile, in that case, workspace may be optional */ - @Override - @FactoryParameter(obligation = OPTIONAL) - WorkspaceConfigDto getWorkspace(); - - void setWorkspace(WorkspaceConfigDto workspace); - - FactoryDto withWorkspace(WorkspaceConfigDto workspace); -} diff --git a/wsmaster/che-core-api-factory-shared/src/main/java/org/eclipse/che/api/factory/shared/dto/FactoryVisitor.java b/wsmaster/che-core-api-factory-shared/src/main/java/org/eclipse/che/api/factory/shared/dto/FactoryVisitor.java index 3d9eead20c4..e7d9d005706 100644 --- a/wsmaster/che-core-api-factory-shared/src/main/java/org/eclipse/che/api/factory/shared/dto/FactoryVisitor.java +++ b/wsmaster/che-core-api-factory-shared/src/main/java/org/eclipse/che/api/factory/shared/dto/FactoryVisitor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012-2023 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,17 +17,6 @@ */ public interface FactoryVisitor { - /** - * Visit factory with devfile v1. - * - *

Implementation should update given factory with needed changes and give it back. - * - * @param factoryDto factory to visit - * @return updated factory - */ - @Deprecated - FactoryDto visit(FactoryDto factoryDto); - /** * Visit factory with devfile v2. * diff --git a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/DtoConverter.java b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/DtoConverter.java index cf9b5972260..526ba6c18e7 100644 --- a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/DtoConverter.java +++ b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/DtoConverter.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,7 +17,6 @@ import java.util.List; import org.eclipse.che.api.core.model.factory.Action; import org.eclipse.che.api.core.model.factory.Author; -import org.eclipse.che.api.core.model.factory.Factory; import org.eclipse.che.api.core.model.factory.Ide; import org.eclipse.che.api.core.model.factory.OnAppClosed; import org.eclipse.che.api.core.model.factory.OnAppLoaded; @@ -25,7 +24,6 @@ import org.eclipse.che.api.core.model.factory.Policies; import org.eclipse.che.api.core.model.user.User; import org.eclipse.che.api.factory.shared.dto.AuthorDto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.IdeActionDto; import org.eclipse.che.api.factory.shared.dto.IdeDto; import org.eclipse.che.api.factory.shared.dto.OnAppClosedDto; @@ -40,29 +38,6 @@ */ public final class DtoConverter { - public static FactoryDto asDto(Factory factory, User user) { - final FactoryDto factoryDto = - newDto(FactoryDto.class) - .withId(factory.getId()) - .withName(factory.getName()) - .withV(factory.getV()); - - if (factory.getWorkspace() != null) { - factoryDto.withWorkspace( - org.eclipse.che.api.workspace.server.DtoConverter.asDto(factory.getWorkspace())); - } - if (factory.getCreator() != null) { - factoryDto.withCreator(asDto(factory.getCreator(), user)); - } - if (factory.getIde() != null) { - factoryDto.withIde(asDto(factory.getIde())); - } - if (factory.getPolicies() != null) { - factoryDto.withPolicies(asDto(factory.getPolicies())); - } - return factoryDto; - } - public static IdeDto asDto(Ide ide) { final IdeDto ideDto = newDto(IdeDto.class); final OnAppClosed onAppClosed = ide.getOnAppClosed(); diff --git a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/FactoryCreateValidator.java b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/FactoryCreateValidator.java deleted file mode 100644 index 63b191fc382..00000000000 --- a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/FactoryCreateValidator.java +++ /dev/null @@ -1,38 +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.factory.server; - -import org.eclipse.che.api.core.BadRequestException; -import org.eclipse.che.api.core.ForbiddenException; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; - -/** - * Interface for validations of factory creation stage. - * - * @author Alexander Garagatyi - */ -public interface FactoryCreateValidator { - - /** - * Validates factory object on creation stage. Implementation should throw exception if factory - * object is invalid. - * - * @param factory factory object to validate - * @throws BadRequestException in case if factory is not valid - * @throws ServerException when any server error occurs - * @throws ForbiddenException when user have no access rights for factory creation - */ - void validateOnCreate(FactoryDto factory) - throws BadRequestException, ServerException, ForbiddenException, NotFoundException; -} diff --git a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/FactoryEditValidator.java b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/FactoryEditValidator.java deleted file mode 100644 index e99da51e50c..00000000000 --- a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/FactoryEditValidator.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.api.factory.server; - -import org.eclipse.che.api.core.ForbiddenException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.api.core.model.factory.Factory; - -/** - * This validator ensures that a factory can be edited by a user that has the associated rights - * (author or account owner) - * - * @author Florent Benoit - */ -public interface FactoryEditValidator { - - /** - * Validates given factory by checking the current user is granted to edit the factory. - * - * @param factory factory object to validate - * @throws ForbiddenException when the current user is not granted to edit the factory - * @throws ServerException when any other error occurs - */ - void validate(Factory factory) throws ForbiddenException, ServerException; -} diff --git a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/builder/FactoryBuilder.java b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/builder/FactoryBuilder.java deleted file mode 100644 index 526abd6780a..00000000000 --- a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/builder/FactoryBuilder.java +++ /dev/null @@ -1,314 +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.factory.server.builder; - -import static org.eclipse.che.api.core.factory.FactoryParameter.Obligation; -import static org.eclipse.che.api.core.factory.FactoryParameter.Version; - -import com.google.common.base.CaseFormat; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import javax.inject.Inject; -import javax.inject.Singleton; -import org.eclipse.che.api.core.ApiException; -import org.eclipse.che.api.core.ConflictException; -import org.eclipse.che.api.core.factory.FactoryParameter; -import org.eclipse.che.api.core.model.workspace.config.ProjectConfig; -import org.eclipse.che.api.core.model.workspace.config.SourceStorage; -import org.eclipse.che.api.factory.server.FactoryConstants; -import org.eclipse.che.api.factory.server.LegacyConverter; -import org.eclipse.che.api.factory.server.ValueHelper; -import org.eclipse.che.api.factory.server.impl.SourceStorageParametersValidator; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; -import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto; -import org.eclipse.che.dto.server.DtoFactory; -import org.eclipse.che.dto.shared.DTO; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Tool to easy convert Factory object to json and vise versa. Also it provides factory parameters - * compatibility. - * - * @author Sergii Kabashniuk - * @author Alexander Garagatyi - */ -@Singleton -public class FactoryBuilder { - private static final Logger LOG = LoggerFactory.getLogger(FactoryBuilder.class); - - /** List contains all possible implementation of factory legacy converters. */ - static final List LEGACY_CONVERTERS; - - static { - List l = new ArrayList<>(1); - l.add(factory -> {}); - LEGACY_CONVERTERS = Collections.unmodifiableList(l); - } - - private final SourceStorageParametersValidator sourceStorageParametersValidator; - - @Inject - public FactoryBuilder(SourceStorageParametersValidator sourceStorageParametersValidator) { - this.sourceStorageParametersValidator = sourceStorageParametersValidator; - } - - /** - * Build factory from json and validate its compatibility. - * - * @param json - json Reader from encoded factory. - * @return - Factory object represented by given factory json. - */ - public FactoryDto build(Reader json) throws IOException, ApiException { - FactoryDto factory = DtoFactory.getInstance().createDtoFromJson(json, FactoryDto.class); - checkValid(factory); - return factory; - } - - /** - * Build factory from json and validate its compatibility. - * - * @param json - json string from encoded factory. - * @return - Factory object represented by given factory json. - */ - public FactoryDto build(String json) throws ApiException { - FactoryDto factory = DtoFactory.getInstance().createDtoFromJson(json, FactoryDto.class); - checkValid(factory); - return factory; - } - - /** - * Build factory from json and validate its compatibility. - * - * @param json - json InputStream from encoded factory. - * @return - Factory object represented by given factory json. - */ - public FactoryDto build(InputStream json) throws IOException, ConflictException { - FactoryDto factory = DtoFactory.getInstance().createDtoFromJson(json, FactoryDto.class); - checkValid(factory); - return factory; - } - - /** - * Validate factory compatibility at creation time. - * - * @param factory - factory object to validate - * @throws ConflictException - */ - public void checkValid(FactoryDto factory) throws ConflictException { - checkValid(factory, false); - } - - /** - * Validate factory compatibility. - * - * @param factory - factory object to validate - * @param isUpdate - indicates is validation performed on update time. Set-by-server variables are - * allowed during update. - * @throws ConflictException - */ - public void checkValid(FactoryDto factory, boolean isUpdate) throws ConflictException { - if (null == factory) { - throw new ConflictException(FactoryConstants.UNPARSABLE_FACTORY_MESSAGE); - } - if (factory.getV() == null) { - throw new ConflictException(FactoryConstants.INVALID_VERSION_MESSAGE); - } - - Version v; - try { - v = Version.fromString(factory.getV()); - } catch (IllegalArgumentException e) { - throw new ConflictException(FactoryConstants.INVALID_VERSION_MESSAGE); - } - - Class usedFactoryVersionMethodProvider; - switch (v) { - case V4_0: - usedFactoryVersionMethodProvider = FactoryDto.class; - break; - default: - throw new ConflictException(FactoryConstants.INVALID_VERSION_MESSAGE); - } - validateCompatibility( - factory, null, FactoryDto.class, usedFactoryVersionMethodProvider, v, "", isUpdate); - } - - /** - * Convert factory of given version to the latest factory format. - * - * @param factory - given factory. - * @return - factory in latest format. - * @throws org.eclipse.che.api.core.ApiException - */ - public FactoryDto convertToLatest(FactoryDto factory) throws ApiException { - FactoryDto resultFactory = DtoFactory.getInstance().clone(factory).withV("4.0"); - for (LegacyConverter converter : LEGACY_CONVERTERS) { - converter.convert(resultFactory); - } - return resultFactory; - } - - /** - * Validate compatibility of factory parameters. - * - * @param object - object to validate factory parameters - * @param parent - parent object - * @param methodsProvider - class that provides methods with {@link - * org.eclipse.che.api.core.factory.FactoryParameter} annotations - * @param allowedMethodsProvider - class that provides allowed methods - * @param version - version of factory - * @param parentName - parent parameter queryParameterName - * @throws org.eclipse.che.api.core.ConflictException - */ - void validateCompatibility( - Object object, - Object parent, - Class methodsProvider, - Class allowedMethodsProvider, - Version version, - String parentName, - boolean isUpdate) - throws ConflictException { - // validate source - if (SourceStorageDto.class.equals(methodsProvider) && !hasSubprojectInPath(parent)) { - sourceStorageParametersValidator.validate((SourceStorage) object, version); - } - - // get all methods recursively - for (Method method : methodsProvider.getMethods()) { - FactoryParameter factoryParameter = method.getAnnotation(FactoryParameter.class); - // is it factory parameter - - if (factoryParameter == null) { - continue; - } - String fullName = - (parentName.isEmpty() ? "" : (parentName + ".")) - + CaseFormat.UPPER_CAMEL.to( - CaseFormat.LOWER_CAMEL, - method.getName().startsWith("is") - ? method.getName().substring(2) - : method.getName().substring(3).toLowerCase()); - // check that field is set - Object parameterValue; - try { - parameterValue = method.invoke(object); - } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) { - // should never happen - LOG.error(e.getLocalizedMessage(), e); - throw new ConflictException(FactoryConstants.INVALID_PARAMETER_MESSAGE); - } - - // if value is null or empty collection or default value for primitives - if (ValueHelper.isEmpty(parameterValue)) { - // field must not be a mandatory, unless it's ignored or deprecated or doesn't suit to the - // version - if (Obligation.MANDATORY.equals(factoryParameter.obligation()) - && factoryParameter.deprecatedSince().compareTo(version) > 0 - && factoryParameter.ignoredSince().compareTo(version) > 0 - && method.getDeclaringClass().isAssignableFrom(allowedMethodsProvider)) { - throw new ConflictException( - String.format(FactoryConstants.MISSING_MANDATORY_MESSAGE, fullName)); - } - } else if (!method.getDeclaringClass().isAssignableFrom(allowedMethodsProvider)) { - throw new ConflictException( - String.format( - FactoryConstants.PARAMETRIZED_INVALID_PARAMETER_MESSAGE, fullName, version)); - } else { - // is parameter deprecated - if (factoryParameter.deprecatedSince().compareTo(version) <= 0 - || (!isUpdate && factoryParameter.setByServer())) { - throw new ConflictException( - String.format( - FactoryConstants.PARAMETRIZED_INVALID_PARAMETER_MESSAGE, fullName, version)); - } - - // use recursion if parameter is DTO object - if (method.getReturnType().isAnnotationPresent(DTO.class)) { - // validate inner objects such Git ot ProjectAttributes - validateCompatibility( - parameterValue, - object, - method.getReturnType(), - method.getReturnType(), - version, - fullName, - isUpdate); - } else if (Map.class.isAssignableFrom(method.getReturnType())) { - Type tp = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[1]; - - Class secMapParamClass = - (tp instanceof ParameterizedType) - ? (Class) ((ParameterizedType) tp).getRawType() - : (Class) tp; - if (!String.class.equals(secMapParamClass) && !List.class.equals(secMapParamClass)) { - if (secMapParamClass.isAnnotationPresent(DTO.class)) { - Map map = (Map) parameterValue; - for (Map.Entry entry : map.entrySet()) { - validateCompatibility( - entry.getValue(), - object, - secMapParamClass, - secMapParamClass, - version, - fullName + "." + entry.getKey(), - isUpdate); - } - } else { - throw new RuntimeException("This type of fields is not supported by factory."); - } - } - } else if (List.class.isAssignableFrom(method.getReturnType())) { - Type tp = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0]; - - Class secListParamClass = - (tp instanceof ParameterizedType) - ? (Class) ((ParameterizedType) tp).getRawType() - : (Class) tp; - if (!String.class.equals(secListParamClass) && !List.class.equals(secListParamClass)) { - if (secListParamClass.isAnnotationPresent(DTO.class)) { - List list = (List) parameterValue; - for (int i = 0; i < list.size(); i++) { - validateCompatibility( - list.get(i), - object, - secListParamClass, - secListParamClass, - version, - fullName + "[" + i + "]", - isUpdate); - } - } else { - throw new RuntimeException("This type of fields is not supported by factory."); - } - } - } - } - } - } - - private boolean hasSubprojectInPath(Object parent) { - return parent != null - && ProjectConfig.class.isAssignableFrom(parent.getClass()) - && ((ProjectConfig) parent).getPath().indexOf('/', 1) != -1; - } -} diff --git a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryBaseValidator.java b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryBaseValidator.java index f7cb3a08c72..5f7876dc9ed 100644 --- a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryBaseValidator.java +++ b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryBaseValidator.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,22 +15,18 @@ import static java.lang.String.format; import static java.lang.System.currentTimeMillis; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.eclipse.che.api.core.BadRequestException; import org.eclipse.che.api.factory.server.FactoryConstants; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.FactoryMetaDto; import org.eclipse.che.api.factory.shared.dto.IdeActionDto; import org.eclipse.che.api.factory.shared.dto.IdeDto; import org.eclipse.che.api.factory.shared.dto.OnAppLoadedDto; import org.eclipse.che.api.factory.shared.dto.OnProjectsLoadedDto; import org.eclipse.che.api.factory.shared.dto.PoliciesDto; -import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; /** * Validates values of factory parameters. @@ -42,52 +38,6 @@ public abstract class FactoryBaseValidator { private static final Pattern PROJECT_NAME_VALIDATOR = Pattern.compile("^[\\\\\\w\\\\\\d]+[\\\\\\w\\\\\\d_.-]*$"); - /** - * Validates source parameter of factory. - * - * @param factory factory to validate - * @throws BadRequestException when source projects in the factory is invalid - */ - protected void validateProjects(FactoryDto factory) throws BadRequestException { - for (ProjectConfigDto project : factory.getWorkspace().getProjects()) { - final String projectName = project.getName(); - if (null != projectName && !PROJECT_NAME_VALIDATOR.matcher(projectName).matches()) { - throw new BadRequestException( - "Project name must contain only Latin letters, " - + "digits or these following special characters -._."); - } - - if (project.getPath().indexOf('/', 1) == -1) { - - if (project.getSource() == null) { - throw new BadRequestException( - format(FactoryConstants.MISSING_MANDATORY_MESSAGE, "project.source")); - } - - final String location = project.getSource().getLocation(); - final String parameterLocationName = "project.source.location"; - - if (isNullOrEmpty(location)) { - throw new BadRequestException( - format( - FactoryConstants.PARAMETRIZED_ILLEGAL_PARAMETER_VALUE_MESSAGE, - parameterLocationName, - location)); - } - - try { - URLDecoder.decode(location, "UTF-8"); - } catch (IllegalArgumentException | UnsupportedEncodingException e) { - throw new BadRequestException( - format( - FactoryConstants.PARAMETRIZED_ILLEGAL_PARAMETER_VALUE_MESSAGE, - parameterLocationName, - location)); - } - } - } - } - /** * Validates that factory can be used at present time (used on accept) * @@ -114,36 +64,6 @@ protected void validateCurrentTimeBetweenSinceUntil(FactoryMetaDto factory) } } - /** - * Validates correct valid since and until times are used (on factory creation) - * - * @param factory factory to validate - * @throws BadRequestException if since date greater or equal than until date - * @throws BadRequestException if since date less than current date - * @throws BadRequestException if until date less than current date - */ - protected void validateCurrentTimeAfterSinceUntil(FactoryDto factory) throws BadRequestException { - final PoliciesDto policies = factory.getPolicies(); - if (policies == null) { - return; - } - - final Long since = policies.getSince() == null ? 0L : policies.getSince(); - final Long until = policies.getUntil() == null ? 0L : policies.getUntil(); - - if (since != 0 && until != 0 && since >= until) { - throw new BadRequestException(FactoryConstants.INVALID_SINCEUNTIL_MESSAGE); - } - - if (since != 0 && currentTimeMillis() > since) { - throw new BadRequestException(FactoryConstants.INVALID_SINCE_MESSAGE); - } - - if (until != 0 && currentTimeMillis() > until) { - throw new BadRequestException(FactoryConstants.INVALID_UNTIL_MESSAGE); - } - } - /** * Validates IDE actions * diff --git a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryCreateValidatorImpl.java b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryCreateValidatorImpl.java deleted file mode 100644 index ce6a9a10b52..00000000000 --- a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryCreateValidatorImpl.java +++ /dev/null @@ -1,48 +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.factory.server.impl; - -import javax.inject.Inject; -import javax.inject.Singleton; -import org.eclipse.che.api.core.BadRequestException; -import org.eclipse.che.api.core.ForbiddenException; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.api.core.ValidationException; -import org.eclipse.che.api.factory.server.FactoryCreateValidator; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; -import org.eclipse.che.api.workspace.server.WorkspaceValidator; - -/** Factory creation stage validator. */ -@Singleton -public class FactoryCreateValidatorImpl extends FactoryBaseValidator - implements FactoryCreateValidator { - private WorkspaceValidator workspaceConfigValidator; - - @Inject - public FactoryCreateValidatorImpl(WorkspaceValidator workspaceConfigValidator) { - this.workspaceConfigValidator = workspaceConfigValidator; - } - - @Override - public void validateOnCreate(FactoryDto factory) - throws BadRequestException, ServerException, ForbiddenException, NotFoundException { - validateProjects(factory); - validateCurrentTimeAfterSinceUntil(factory); - validateProjectActions(factory); - try { - workspaceConfigValidator.validateConfig(factory.getWorkspace()); - } catch (ValidationException x) { - throw new BadRequestException(x.getMessage()); - } - } -} diff --git a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryEditValidatorImpl.java b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryEditValidatorImpl.java deleted file mode 100644 index 2ef3b26d182..00000000000 --- a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/impl/FactoryEditValidatorImpl.java +++ /dev/null @@ -1,57 +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.factory.server.impl; - -import static java.lang.String.format; - -import javax.inject.Singleton; -import org.eclipse.che.api.core.ForbiddenException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.api.core.model.factory.Author; -import org.eclipse.che.api.core.model.factory.Factory; -import org.eclipse.che.api.factory.server.FactoryEditValidator; -import org.eclipse.che.commons.env.EnvironmentContext; - -/** - * This validator ensures that a factory can be edited by a user that has the associated rights - * (author or account owner) - * - * @author Florent Benoit - */ -@Singleton -public class FactoryEditValidatorImpl implements FactoryEditValidator { - - /** - * Validates given factory by checking the current user is granted to edit the factory - * - * @param factory factory object to validate - * @throws ForbiddenException occurs if the current user is not granted to edit the factory - * @throws ServerException when any server error occurs - */ - @Override - public void validate(Factory factory) throws ForbiddenException, ServerException { - // Checks if there is an author from the factory (It may be missing for some old factories) - final Author author = factory.getCreator(); - if (author == null || author.getUserId() == null) { - throw new ServerException( - format( - "Invalid factory without author stored. Please contact the support about the factory ID '%s'", - factory.getId())); - } - // ensure user has the correct permissions - final String userId = EnvironmentContext.getCurrent().getSubject().getUserId(); - if (!author.getUserId().equals(userId)) { - throw new ForbiddenException( - format("You are not authorized for the factory '%s'", factory.getId())); - } - } -} diff --git a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/urlfactory/ProjectConfigDtoMerger.java b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/urlfactory/ProjectConfigDtoMerger.java deleted file mode 100644 index a2e248d999f..00000000000 --- a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/urlfactory/ProjectConfigDtoMerger.java +++ /dev/null @@ -1,70 +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.urlfactory; - -import static java.util.Collections.singletonList; - -import java.util.List; -import java.util.function.Supplier; -import javax.inject.Singleton; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; -import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; - -/** - * Merge or add inside a factory the source storage dto - * - * @author Florent Benoit - */ -@Singleton -public class ProjectConfigDtoMerger { - - /** - * Apply the merging of project config dto including source storage dto into the existing factory - * - *

here are the following rules - * - *

    - *
  • no projects --> add whole project - *
  • if projects: - *
      - *
    • if there is only one project: add source if missing - *
    • if many projects: do nothing - *
    - *
- * - * @param factory source factory - * @param configSupplier supplier which can compute project config on demand - * @return factory with merged project sources - */ - public FactoryDto merge(FactoryDto factory, Supplier configSupplier) { - - if (factory.getWorkspace() == null) { - // factory is created with devfile. There is no need to provision projects - return factory; - } - - final List projects = factory.getWorkspace().getProjects(); - if (projects == null || projects.isEmpty()) { - factory.getWorkspace().setProjects(singletonList(configSupplier.get())); - return factory; - } - - // if we're here, they are projects - if (projects.size() == 1) { - ProjectConfigDto projectConfig = projects.get(0); - if (projectConfig.getSource() == null) - projectConfig.setSource(configSupplier.get().getSource()); - } - - return factory; - } -} diff --git a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/urlfactory/URLFactoryBuilder.java b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/urlfactory/URLFactoryBuilder.java index f35564a2202..50b4975382c 100644 --- a/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/urlfactory/URLFactoryBuilder.java +++ b/wsmaster/che-core-api-factory/src/main/java/org/eclipse/che/api/factory/server/urlfactory/URLFactoryBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012-2023 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,37 +15,24 @@ import static org.eclipse.che.api.factory.server.ApiExceptionMapper.toApiException; import static org.eclipse.che.api.factory.server.scm.exception.ExceptionMessages.getDevfileConnectionErrorMessage; import static org.eclipse.che.api.factory.shared.Constants.CURRENT_VERSION; -import static org.eclipse.che.api.workspace.server.devfile.Constants.CURRENT_API_VERSION; -import static org.eclipse.che.api.workspace.shared.Constants.WORKSPACE_TOOLING_EDITOR_ATTRIBUTE; -import static org.eclipse.che.api.workspace.shared.Constants.WORKSPACE_TOOLING_PLUGINS_ATTRIBUTE; import static org.eclipse.che.dto.server.DtoFactory.newDto; import com.fasterxml.jackson.databind.JsonNode; import java.io.IOException; -import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.eclipse.che.api.core.ApiException; -import org.eclipse.che.api.core.BadRequestException; import org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException; import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl.DevfileLocation; import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.FactoryMetaDto; -import org.eclipse.che.api.workspace.server.DtoConverter; import org.eclipse.che.api.workspace.server.devfile.DevfileParser; import org.eclipse.che.api.workspace.server.devfile.DevfileVersionDetector; import org.eclipse.che.api.workspace.server.devfile.FileContentProvider; import org.eclipse.che.api.workspace.server.devfile.exception.DevfileException; -import org.eclipse.che.api.workspace.server.devfile.exception.OverrideParameterException; -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.shared.dto.WorkspaceConfigDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.DevfileDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.MetadataDto; import org.eclipse.che.commons.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -148,10 +135,7 @@ public Optional createFactoryFromDevfile( } catch (DevfileException e) { throw new ApiException(getDevfileConnectionErrorMessage(devfileLocation)); } - return Optional.of( - createFactory(parsedDevfile, overrideProperties, fileContentProvider, location)); - } catch (OverrideParameterException e) { - throw new BadRequestException("Error processing override parameter(s): " + e.getMessage()); + return Optional.of(createFactory(parsedDevfile, location)); } catch (DevfileException e) { throw toApiException(e, location); } @@ -160,86 +144,15 @@ public Optional createFactoryFromDevfile( } /** - * Converts given devfile json into factory based on the devfile version. + * Converts given devfile json into factory. * - * @param overrideProperties map of overridden properties to apply in devfile - * @param fileContentProvider service-specific devfile related file content provider * @param location devfile's location * @return new factory created from the given devfile - * @throws OverrideParameterException when any issue when overriding parameters occur - * @throws DevfileException when devfile is not valid or we can't work with it - */ - private FactoryMetaDto createFactory( - JsonNode devfileJson, - Map overrideProperties, - FileContentProvider fileContentProvider, - DevfileLocation location) - throws OverrideParameterException, DevfileException { - - if (devfileVersionDetector.devfileMajorVersion(devfileJson) == 1) { - DevfileImpl devfile = devfileParser.parseJsonNode(devfileJson, overrideProperties); - devfileParser.resolveReference(devfile, fileContentProvider); - devfile = ensureToUseGenerateName(devfile); - - return newDto(FactoryDto.class) - .withV(CURRENT_VERSION) - .withDevfile(DtoConverter.asDto(devfile)) - .withSource(location.filename().isPresent() ? location.filename().get() : null); - - } else { - return newDto(FactoryDevfileV2Dto.class) - .withV(CURRENT_VERSION) - .withDevfile(devfileParser.convertYamlToMap(devfileJson)) - .withSource(location.filename().isPresent() ? location.filename().get() : null); - } - } - - /** - * Creates devfile with only `generateName` and no `name`. We take `generateName` with precedence. - * See doc of {@link URLFactoryBuilder#createFactoryFromDevfile(RemoteFactoryUrl, - * FileContentProvider, Map, boolean)} for explanation why. - */ - private DevfileImpl ensureToUseGenerateName(DevfileImpl devfile) { - MetadataImpl devfileMetadata = new MetadataImpl(devfile.getMetadata()); - if (isNullOrEmpty(devfileMetadata.getGenerateName())) { - devfileMetadata.setGenerateName(devfileMetadata.getName()); - } - devfileMetadata.setName(null); - - DevfileImpl devfileWithProperName = new DevfileImpl(devfile); - devfileWithProperName.setMetadata(devfileMetadata); - return devfileWithProperName; - } - - /** - * Help to generate default workspace configuration - * - * @param name the name of the workspace - * @return a workspace configuration - */ - public WorkspaceConfigDto buildDefaultWorkspaceConfig(String name) { - - Map attributes = new HashMap<>(); - attributes.put(WORKSPACE_TOOLING_EDITOR_ATTRIBUTE, defaultCheEditor); - if (!isNullOrEmpty(defaultChePlugins)) { - attributes.put(WORKSPACE_TOOLING_PLUGINS_ATTRIBUTE, defaultChePlugins); - } - - // workspace configuration using the environment - return newDto(WorkspaceConfigDto.class).withName(name).withAttributes(attributes); - } - - /** - * Help to generate default workspace devfile. Also initialise project in it - * - * @param name the name that will be used as `generateName` in the devfile - * @return a workspace devfile */ - public DevfileDto buildDefaultDevfile(String name) { - - // workspace configuration using the environment - return newDto(DevfileDto.class) - .withApiVersion(CURRENT_API_VERSION) - .withMetadata(newDto(MetadataDto.class).withGenerateName(name)); + private FactoryMetaDto createFactory(JsonNode devfileJson, DevfileLocation location) { + return newDto(FactoryDevfileV2Dto.class) + .withV(CURRENT_VERSION) + .withDevfile(devfileParser.convertYamlToMap(devfileJson)) + .withSource(location.filename().isPresent() ? location.filename().get() : null); } } diff --git a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/FactoryServiceTest.java b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/FactoryServiceTest.java index 28ca3966467..1308f975016 100644 --- a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/FactoryServiceTest.java +++ b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/FactoryServiceTest.java @@ -12,24 +12,19 @@ package org.eclipse.che.api.factory.server; import static io.restassured.RestAssured.given; -import static jakarta.ws.rs.core.Response.Status.BAD_REQUEST; import static java.lang.String.valueOf; import static java.util.Collections.singletonMap; import static org.eclipse.che.api.factory.server.FactoryResolverPriority.DEFAULT; import static org.eclipse.che.api.factory.server.FactoryResolverPriority.HIGHEST; import static org.eclipse.che.api.factory.server.FactoryResolverPriority.LOWEST; import static org.eclipse.che.api.factory.server.FactoryService.VALIDATE_QUERY_PARAMETER; -import static org.eclipse.che.api.factory.shared.Constants.CURRENT_VERSION; import static org.eclipse.che.api.factory.shared.Constants.URL_PARAMETER_NAME; -import static org.eclipse.che.dto.server.DtoFactory.newDto; import static org.everrest.assured.JettyHttpServer.ADMIN_USER_NAME; import static org.everrest.assured.JettyHttpServer.ADMIN_USER_PASSWORD; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -47,17 +42,13 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import org.eclipse.che.api.core.BadRequestException; import org.eclipse.che.api.core.model.user.User; import org.eclipse.che.api.core.rest.ApiExceptionMapper; import org.eclipse.che.api.core.rest.shared.dto.ServiceError; import org.eclipse.che.api.factory.server.FactoryService.FactoryParametersResolverHolder; -import org.eclipse.che.api.factory.server.builder.FactoryBuilder; -import org.eclipse.che.api.factory.server.impl.SourceStorageParametersValidator; import org.eclipse.che.api.factory.server.scm.AuthorisationRequestManager; import org.eclipse.che.api.factory.server.scm.PersonalAccessTokenManager; import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.user.server.PreferenceManager; import org.eclipse.che.api.user.server.UserManager; import org.eclipse.che.api.user.server.model.impl.UserImpl; @@ -108,8 +99,6 @@ public class FactoryServiceTest { @InjectMocks private FactoryParametersResolverHolder factoryParametersResolverHolder; private Set specificFactoryParametersResolvers; - private FactoryBuilder factoryBuilderSpy; - private User user; private FactoryService service; @@ -129,9 +118,6 @@ public void setUp() throws Exception { parametersResolvers.setAccessible(true); parametersResolvers.set(factoryParametersResolverHolder, specificFactoryParametersResolvers); specificFactoryParametersResolvers.add(rawDevfileUrlFactoryParameterResolver); - factoryBuilderSpy = spy(new FactoryBuilder(new SourceStorageParametersValidator())); - lenient().doNothing().when(factoryBuilderSpy).checkValid(any(FactoryDto.class)); - lenient().doNothing().when(factoryBuilderSpy).checkValid(any(FactoryDto.class), anyBoolean()); user = new UserImpl(USER_ID, USER_EMAIL, ADMIN_USER_NAME); lenient() .when(preferenceManager.find(USER_ID)) @@ -185,56 +171,6 @@ public void shouldThrowBadRequestWhenNoURLParameterGiven() throws Exception { "Cannot build factory with any of the provided parameters. Please check parameters correctness, and resend query."); } - @Test - public void checkValidateResolver() throws Exception { - final FactoryParametersResolverHolder dummyHolder = spy(factoryParametersResolverHolder); - doReturn(rawDevfileUrlFactoryParameterResolver) - .when(dummyHolder) - .getFactoryParametersResolver(anyMap()); - // service instance with dummy holder - service = - new FactoryService( - acceptValidator, - dummyHolder, - additionalFilenamesProvider, - personalAccessTokenManager, - authorisationRequestManager); - - // invalid factory - final String invalidFactoryMessage = "invalid factory"; - doThrow(new BadRequestException(invalidFactoryMessage)) - .when(acceptValidator) - .validateOnAccept(any()); - - // create factory - final FactoryDto expectFactory = - newDto(FactoryDto.class).withV(CURRENT_VERSION).withName("matchingResolverFactory"); - - // accept resolver - when(rawDevfileUrlFactoryParameterResolver.createFactory(anyMap())).thenReturn(expectFactory); - - // when - final Map map = new HashMap<>(); - final Response response = - given() - .contentType(ContentType.JSON) - .when() - .body(map) - .queryParam(VALIDATE_QUERY_PARAMETER, valueOf(true)) - .post(SERVICE_PATH + "/resolver"); - - // then check we have a bad request - assertEquals(response.getStatusCode(), BAD_REQUEST.getStatusCode()); - assertTrue(response.getBody().asString().contains(invalidFactoryMessage)); - - // check we call resolvers - dummyHolder.getFactoryParametersResolver(anyMap()); - verify(rawDevfileUrlFactoryParameterResolver).createFactory(anyMap()); - - // check we call validator - verify(acceptValidator).validateOnAccept(any()); - } - @Test public void checkRefreshToken() throws Exception { // given diff --git a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/RawDevfileUrlFactoryParameterResolverTest.java b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/RawDevfileUrlFactoryParameterResolverTest.java index 84c95559447..cccf490759f 100644 --- a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/RawDevfileUrlFactoryParameterResolverTest.java +++ b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/RawDevfileUrlFactoryParameterResolverTest.java @@ -14,14 +14,9 @@ import static java.lang.String.format; import static java.util.Collections.singletonMap; import static org.eclipse.che.api.factory.shared.Constants.URL_PARAMETER_NAME; -import static org.eclipse.che.api.workspace.server.devfile.Constants.EDITOR_COMPONENT_TYPE; -import static org.eclipse.che.api.workspace.server.devfile.Constants.KUBERNETES_COMPONENT_TYPE; -import static org.eclipse.che.api.workspace.server.devfile.Constants.OPENSHIFT_COMPONENT_TYPE; -import static org.eclipse.che.api.workspace.server.devfile.Constants.PLUGIN_COMPONENT_TYPE; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -38,12 +33,8 @@ import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl; import org.eclipse.che.api.factory.server.urlfactory.URLFactoryBuilder; import org.eclipse.che.api.workspace.server.devfile.DevfileParser; -import org.eclipse.che.api.workspace.server.devfile.DevfileVersionDetector; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; import org.eclipse.che.api.workspace.server.devfile.URLFileContentProvider; -import org.eclipse.che.api.workspace.server.devfile.validator.ComponentIntegrityValidator; -import org.eclipse.che.api.workspace.server.devfile.validator.ComponentIntegrityValidator.NoopComponentIntegrityValidator; -import org.eclipse.che.api.workspace.server.devfile.validator.DevfileIntegrityValidator; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; @@ -56,53 +47,13 @@ public class RawDevfileUrlFactoryParameterResolverTest { private static final String DEVFILE = - "" - + "apiVersion: 1.0.0\n" - + "metadata:\n" - + " name: test\n" - + "components:\n" - + "- type: kubernetes\n" - + " alias: component\n" - + " reference: ../localfile\n"; + "" + "schemaVersion: 2.3.0\n" + "metadata:\n" + " name: test\n"; @Mock private URLFetcher urlFetcher; @Mock private DevfileParser devfileParser; @InjectMocks private RawDevfileUrlFactoryParameterResolver rawDevfileUrlFactoryParameterResolver; - @Test - public void shouldResolveRelativeFiles() throws Exception { - // given - Map validators = new HashMap<>(); - validators.put(EDITOR_COMPONENT_TYPE, new NoopComponentIntegrityValidator()); - validators.put(PLUGIN_COMPONENT_TYPE, new NoopComponentIntegrityValidator()); - validators.put(KUBERNETES_COMPONENT_TYPE, new NoopComponentIntegrityValidator()); - validators.put(OPENSHIFT_COMPONENT_TYPE, new NoopComponentIntegrityValidator()); - - DevfileIntegrityValidator integrityValidator = new DevfileIntegrityValidator(validators); - - DevfileParser devfileParser = new DevfileParser(integrityValidator); - - URLFactoryBuilder factoryBuilder = - new URLFactoryBuilder( - "editor", "plugin", false, devfileParser, new DevfileVersionDetector()); - - RawDevfileUrlFactoryParameterResolver res = - new RawDevfileUrlFactoryParameterResolver(factoryBuilder, urlFetcher, devfileParser); - - // set up our factory with the location of our devfile that is referencing our localfile - Map factoryParameters = new HashMap<>(); - factoryParameters.put(URL_PARAMETER_NAME, "http://myloc.com/aa/bb/devfile"); - doReturn(DEVFILE).when(urlFetcher).fetch(eq("http://myloc.com/aa/bb/devfile"), eq(null)); - doReturn("localfile").when(urlFetcher).fetch("http://myloc.com/aa/localfile", null); - - // when - res.createFactory(factoryParameters); - - // then - verify(urlFetcher).fetch(eq("http://myloc.com/aa/localfile"), eq(null)); - } - @Test @SuppressWarnings("unchecked") public void shouldFilterAndProvideOverrideParameters() throws Exception { diff --git a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/builder/FactoryBuilderTest.java b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/builder/FactoryBuilderTest.java deleted file mode 100644 index 72fba32e280..00000000000 --- a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/builder/FactoryBuilderTest.java +++ /dev/null @@ -1,288 +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.builder; - -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; -import static java.util.Collections.singletonMap; -import static java.util.Objects.requireNonNull; -import static org.eclipse.che.api.core.model.workspace.config.MachineConfig.MEMORY_LIMIT_ATTRIBUTE; -import static org.eclipse.che.dto.server.DtoFactory.newDto; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; - -import com.google.common.collect.ImmutableMap; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URISyntaxException; -import org.eclipse.che.api.core.ApiException; -import org.eclipse.che.api.core.ConflictException; -import org.eclipse.che.api.core.factory.FactoryParameter; -import org.eclipse.che.api.factory.server.impl.SourceStorageParametersValidator; -import org.eclipse.che.api.factory.shared.dto.AuthorDto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; -import org.eclipse.che.api.factory.shared.dto.IdeActionDto; -import org.eclipse.che.api.factory.shared.dto.IdeDto; -import org.eclipse.che.api.factory.shared.dto.OnAppClosedDto; -import org.eclipse.che.api.factory.shared.dto.OnAppLoadedDto; -import org.eclipse.che.api.factory.shared.dto.OnProjectsLoadedDto; -import org.eclipse.che.api.factory.shared.dto.PoliciesDto; -import org.eclipse.che.api.workspace.shared.dto.CommandDto; -import org.eclipse.che.api.workspace.shared.dto.EnvironmentDto; -import org.eclipse.che.api.workspace.shared.dto.MachineConfigDto; -import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; -import org.eclipse.che.api.workspace.shared.dto.RecipeDto; -import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; -import org.eclipse.che.dto.server.DtoFactory; -import org.mockito.Mock; -import org.mockito.testng.MockitoTestNGListener; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Listeners; -import org.testng.annotations.Test; - -/** - * Tests for {@link FactoryDto} - * - * @author Alexander Garagatyi - * @author Sergii Kabashniuk - */ -@SuppressWarnings("deprecation") -@Listeners(MockitoTestNGListener.class) -public class FactoryBuilderTest { - - private static DtoFactory dto = DtoFactory.getInstance(); - - private FactoryBuilder factoryBuilder; - - private FactoryDto actual; - - private FactoryDto expected; - - @Mock private SourceStorageParametersValidator sourceProjectParametersValidator; - - @BeforeMethod - public void setUp() throws Exception { - factoryBuilder = new FactoryBuilder(sourceProjectParametersValidator); - actual = prepareFactory(); - - expected = dto.createDto(FactoryDto.class); - } - - @Test - public void shouldBeAbleToValidateV4_0() throws Exception { - factoryBuilder.checkValid(actual); - - verify(sourceProjectParametersValidator).validate(any(), eq(FactoryParameter.Version.V4_0)); - } - - @Test(expectedExceptions = ApiException.class) - public void shouldNotValidateUnparseableFactory() throws Exception { - factoryBuilder.checkValid(null); - } - - @Test( - expectedExceptions = ApiException.class, - dataProvider = "setByServerParamsProvider", - expectedExceptionsMessageRegExp = - "You have provided an invalid parameter .* for this version of Factory parameters.*") - public void shouldNotAllowUsingParamsThatCanBeSetOnlyByServer(FactoryDto factory) - throws Exception { - factoryBuilder.checkValid(factory); - } - - @Test(dataProvider = "setByServerParamsProvider") - public void shouldAllowUsingParamsThatCanBeSetOnlyByServerDuringUpdate(FactoryDto factory) - throws Exception { - factoryBuilder.checkValid(factory, true); - } - - @DataProvider(name = "setByServerParamsProvider") - public static Object[][] setByServerParamsProvider() throws Exception { - FactoryDto factory = prepareFactory(); - return new Object[][] { - {requireNonNull(dto.clone(factory)).withId("id")}, - { - requireNonNull(dto.clone(factory)) - .withCreator(dto.createDto(AuthorDto.class).withUserId("id")) - }, - { - requireNonNull(dto.clone(factory)) - .withCreator(dto.createDto(AuthorDto.class).withCreated(123L)) - } - }; - } - - @Test(expectedExceptions = ApiException.class, dataProvider = "notValidParamsProvider") - public void shouldNotAllowUsingNotValidParams(FactoryDto factory) - throws InvocationTargetException, IllegalAccessException, ApiException, - NoSuchMethodException { - factoryBuilder.checkValid(factory); - } - - @DataProvider(name = "notValidParamsProvider") - public static Object[][] notValidParamsProvider() - throws URISyntaxException, IOException, NoSuchMethodException { - FactoryDto factory = prepareFactory(); - EnvironmentDto environmentDto = - factory.getWorkspace().getEnvironments().values().iterator().next(); - environmentDto.getRecipe().withType(null); - return new Object[][] { - { - requireNonNull(dto.clone(factory)) - .withWorkspace(factory.getWorkspace().withDefaultEnv(null)) - }, - { - requireNonNull(dto.clone(factory)) - .withWorkspace( - factory.getWorkspace().withEnvironments(singletonMap("test", environmentDto))) - } - }; - } - - @Test - public void shouldBeAbleToValidateV4_0WithTrackedParamsWithoutAccountIdIfOnPremisesIsEnabled() - throws Exception { - factoryBuilder = new FactoryBuilder(sourceProjectParametersValidator); - - FactoryDto factory = - prepareFactory() - .withPolicies( - dto.createDto(PoliciesDto.class) - .withReferer("referrer") - .withSince(123L) - .withUntil(123L)); - - factoryBuilder.checkValid(factory); - } - - @Test( - expectedExceptions = ConflictException.class, - expectedExceptionsMessageRegExp = - "You are missing a mandatory parameter \"workspace.projects\\[1\\].path\". .*") - public void shouldThrowExceptionWithMessagePointingToMissingMandatoryParameter() - throws Exception { - factoryBuilder = new FactoryBuilder(sourceProjectParametersValidator); - - ProjectConfigDto project = - dto.createDto(ProjectConfigDto.class) - .withSource( - dto.createDto(SourceStorageDto.class).withType("git").withLocation("location")) - .withType("type") - .withAttributes(singletonMap("key", singletonList("value"))) - .withDescription("description") - .withName("name") - .withPath("/path"); - - ProjectConfigDto project2 = - dto.createDto(ProjectConfigDto.class) - .withSource( - dto.createDto(SourceStorageDto.class).withType("git").withLocation("location")) - .withType("") - .withAttributes(singletonMap("key", singletonList("value"))) - .withDescription("description") - .withName("test") - .withPath(""); - FactoryDto factory = prepareFactory(); - factory.getWorkspace().setProjects(asList(project, project2)); - - factoryBuilder.checkValid(factory); - } - - private static FactoryDto prepareFactory() { - ProjectConfigDto project = - dto.createDto(ProjectConfigDto.class) - .withSource( - dto.createDto(SourceStorageDto.class).withType("git").withLocation("location")) - .withType("type") - .withAttributes(singletonMap("key", singletonList("value"))) - .withDescription("description") - .withName("name") - .withPath("/path"); - EnvironmentDto environment = - dto.createDto(EnvironmentDto.class) - .withRecipe( - newDto(RecipeDto.class) - .withType("compose") - .withContentType("application/x-yaml") - .withContent("some content")) - .withMachines( - singletonMap( - "devmachine", - newDto(MachineConfigDto.class) - .withAttributes( - singletonMap(MEMORY_LIMIT_ATTRIBUTE, "" + 512L * 1024L * 1024L)))); - - WorkspaceConfigDto workspaceConfig = - dto.createDto(WorkspaceConfigDto.class) - .withProjects(singletonList(project)) - .withCommands( - singletonList( - dto.createDto(CommandDto.class) - .withName("command1") - .withType("maven") - .withCommandLine("mvn test"))) - .withDefaultEnv("env1") - .withEnvironments(singletonMap("test", environment)); - IdeDto ide = - dto.createDto(IdeDto.class) - .withOnAppClosed( - dto.createDto(OnAppClosedDto.class) - .withActions( - singletonList(dto.createDto(IdeActionDto.class).withId("warnOnClose")))) - .withOnAppLoaded( - dto.createDto(OnAppLoadedDto.class) - .withActions( - asList( - dto.createDto(IdeActionDto.class).withId("newProject"), - dto.createDto(IdeActionDto.class) - .withId("openWelcomePage") - .withProperties( - ImmutableMap.of( - "authenticatedTitle", - "Greeting title for authenticated users", - "authenticatedContentUrl", - "http://example.com/content.url"))))) - .withOnProjectsLoaded( - dto.createDto(OnProjectsLoadedDto.class) - .withActions( - asList( - dto.createDto(IdeActionDto.class) - .withId("openFile") - .withProperties(singletonMap("file", "pom.xml")), - dto.createDto(IdeActionDto.class).withId("run"), - dto.createDto(IdeActionDto.class) - .withId("findReplace") - .withProperties( - ImmutableMap.of( - "in", - "src/main/resources/consts2.properties", - "find", - "OLD_VALUE_2", - "replace", - "NEW_VALUE_2", - "replaceMode", - "mode"))))); - return dto.createDto(FactoryDto.class) - .withV("4.0") - .withWorkspace(workspaceConfig) - .withCreator(dto.createDto(AuthorDto.class).withEmail("email").withName("name")) - .withPolicies( - dto.createDto(PoliciesDto.class) - .withReferer("referrer") - .withSince(123L) - .withUntil(123L)) - .withIde(ide); - } -} diff --git a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryBaseValidatorTest.java b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryBaseValidatorTest.java index f89c225bb7f..c55b96627f4 100644 --- a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryBaseValidatorTest.java +++ b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryBaseValidatorTest.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/ @@ -18,9 +18,7 @@ import static org.mockito.Mockito.lenient; import com.google.common.collect.ImmutableMap; -import jakarta.servlet.http.HttpServletRequest; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.text.ParseException; import java.util.Date; @@ -32,9 +30,8 @@ import org.eclipse.che.api.core.NotFoundException; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.factory.server.FactoryConstants; -import org.eclipse.che.api.factory.server.builder.FactoryBuilder; -import org.eclipse.che.api.factory.shared.dto.AuthorDto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; +import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; +import org.eclipse.che.api.factory.shared.dto.FactoryMetaDto; import org.eclipse.che.api.factory.shared.dto.IdeActionDto; import org.eclipse.che.api.factory.shared.dto.IdeDto; import org.eclipse.che.api.factory.shared.dto.OnAppClosedDto; @@ -42,11 +39,7 @@ import org.eclipse.che.api.factory.shared.dto.OnProjectsLoadedDto; import org.eclipse.che.api.factory.shared.dto.PoliciesDto; import org.eclipse.che.api.user.server.model.impl.UserImpl; -import org.eclipse.che.api.user.server.spi.PreferenceDao; import org.eclipse.che.api.user.server.spi.UserDao; -import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; -import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; import org.eclipse.che.dto.server.DtoFactory; import org.mockito.Mock; import org.mockito.testng.MockitoTestNGListener; @@ -63,165 +56,19 @@ public class FactoryBaseValidatorTest { @Mock private UserDao userDao; - @Mock private PreferenceDao preferenceDao; - - @Mock private FactoryBuilder builder; - - @Mock private HttpServletRequest request; - private TesterFactoryBaseValidator validator; - private FactoryDto factory; + private FactoryDevfileV2Dto factory; @BeforeMethod public void setUp() throws ParseException, NotFoundException, ServerException { - factory = - newDto(FactoryDto.class) - .withV("4.0") - .withCreator(newDto(AuthorDto.class).withUserId("userid")); + factory = newDto(FactoryDevfileV2Dto.class).withV("4.0"); final UserImpl user = new UserImpl("userid", "email", "name"); lenient().when(userDao.getById("userid")).thenReturn(user); validator = new TesterFactoryBaseValidator(); } - @Test - public void shouldBeAbleToValidateFactoryUrlObject() throws ApiException { - factory = prepareFactoryWithGivenStorage("git", VALID_REPOSITORY_URL, VALID_PROJECT_PATH); - validator.validateProjects(factory); - validator.validateProjects(factory); - } - - @Test - public void shouldBeAbleToValidateFactoryUrlObjectIfStorageIsESBWSO2() throws ApiException { - factory = prepareFactoryWithGivenStorage("esbwso2", VALID_REPOSITORY_URL, VALID_PROJECT_PATH); - validator.validateProjects(factory); - validator.validateProjects(factory); - } - - @Test( - expectedExceptions = ApiException.class, - expectedExceptionsMessageRegExp = - "The parameter project.source.location has a value submitted http://codenvy.com/git/04%2 with a value that is " - + "unexpected. " - + "For more information, please visit https://www.eclipse.org/che/docs/workspace-data-model.html#projects") - public void shouldNotValidateIfStorageLocationContainIncorrectEncodedSymbol() - throws ApiException { - // given - factory = - prepareFactoryWithGivenStorage("git", "http://codenvy.com/git/04%2", VALID_PROJECT_PATH); - - // when, then - validator.validateProjects(factory); - } - - @Test - public void shouldValidateIfStorageLocationIsCorrectSsh() throws ApiException { - // given - factory = - prepareFactoryWithGivenStorage( - "git", - "ssh://codenvy@review.gerrithub.io:29418/codenvy/exampleProject", - "example-project"); - - // when, then - validator.validateProjects(factory); - } - - @Test - public void shouldValidateIfStorageLocationIsCorrectHttps() throws ApiException { - // given - factory = - prepareFactoryWithGivenStorage("git", "https://github.com/codenvy/example.git", "/example"); - - // when, then - validator.validateProjects(factory); - } - - @Test - public void shouldValidateSubProjectWithNoLocation() throws ApiException { - // given - factory = prepareFactoryWithGivenStorage("git", "null", "/cloudide/core"); - - // when, then - validator.validateProjects(factory); - } - - @Test(dataProvider = "badAdvancedFactoryUrlProvider", expectedExceptions = ApiException.class) - public void shouldNotValidateIfStorageOrStorageLocationIsInvalid(FactoryDto factory) - throws ApiException { - validator.validateProjects(factory); - } - - @DataProvider(name = "badAdvancedFactoryUrlProvider") - public Object[][] invalidParametersFactoryUrlProvider() throws UnsupportedEncodingException { - FactoryDto adv1 = - prepareFactoryWithGivenStorage("notagit", VALID_REPOSITORY_URL, VALID_PROJECT_PATH); - FactoryDto adv2 = prepareFactoryWithGivenStorage("git", null, VALID_PROJECT_PATH); - FactoryDto adv3 = prepareFactoryWithGivenStorage("git", "", VALID_PROJECT_PATH); - return new Object[][] { - {adv1}, // invalid vcs - {adv2}, // invalid vcsurl - {adv3} // invalid vcsurl - }; - } - - @Test( - dataProvider = "invalidProjectNamesProvider", - expectedExceptions = ApiException.class, - expectedExceptionsMessageRegExp = - "Project name must contain only Latin letters, " - + "digits or these following special characters -._.") - public void shouldThrowFactoryUrlExceptionIfProjectNameInvalid(String projectName) - throws Exception { - // given - factory.withWorkspace( - newDto(WorkspaceConfigDto.class) - .withProjects( - singletonList( - newDto(ProjectConfigDto.class).withType("type").withName(projectName)))); - // when, then - validator.validateProjects(factory); - } - - @Test(dataProvider = "validProjectNamesProvider") - public void shouldBeAbleToValidateValidProjectName(String projectName) throws Exception { - // given - prepareFactoryWithGivenStorage("git", VALID_REPOSITORY_URL, VALID_PROJECT_PATH); - factory.withWorkspace( - newDto(WorkspaceConfigDto.class) - .withProjects( - singletonList( - newDto(ProjectConfigDto.class) - .withType("type") - .withName(projectName) - .withSource( - newDto(SourceStorageDto.class) - .withType("git") - .withLocation(VALID_REPOSITORY_URL)) - .withPath(VALID_PROJECT_PATH)))); - // when, then - validator.validateProjects(factory); - } - - @DataProvider(name = "validProjectNamesProvider") - public Object[][] validProjectNames() { - return new Object[][] { - {"untitled"}, - {"Untitled"}, - {"untitled.project"}, - {"untitled-project"}, - {"untitled_project"}, - {"untitled01"}, - {"000011111"}, - {"0untitled"}, - {"UU"}, - {"untitled-proj12"}, - {"untitled.pro....111"}, - {"SampleStruts"} - }; - } - @DataProvider(name = "invalidProjectNamesProvider") public Object[][] invalidProjectNames() { return new Object[][] { @@ -229,40 +76,6 @@ public Object[][] invalidProjectNames() { }; } - @Test - public void shouldValidateIfCurrentTimeBeforeSinceUntil() throws Exception { - Long currentTime = new Date().getTime(); - - factory.withPolicies( - newDto(PoliciesDto.class).withSince(currentTime + 10000L).withUntil(currentTime + 20000L)); - validator.validateCurrentTimeAfterSinceUntil(factory); - } - - @Test( - expectedExceptions = ApiException.class, - expectedExceptionsMessageRegExp = FactoryConstants.INVALID_SINCE_MESSAGE) - public void shouldNotValidateIfSinceBeforeCurrent() throws ApiException { - factory.withPolicies(newDto(PoliciesDto.class).withSince(1L)); - validator.validateCurrentTimeAfterSinceUntil(factory); - } - - @Test( - expectedExceptions = ApiException.class, - expectedExceptionsMessageRegExp = FactoryConstants.INVALID_UNTIL_MESSAGE) - public void shouldNotValidateIfUntilBeforeCurrent() throws ApiException { - factory.withPolicies(newDto(PoliciesDto.class).withUntil(1L)); - validator.validateCurrentTimeAfterSinceUntil(factory); - } - - @Test( - expectedExceptions = ApiException.class, - expectedExceptionsMessageRegExp = FactoryConstants.INVALID_SINCEUNTIL_MESSAGE) - public void shouldNotValidateIfUntilBeforeSince() throws ApiException { - factory.withPolicies(newDto(PoliciesDto.class).withSince(2L).withUntil(1L)); - - validator.validateCurrentTimeAfterSinceUntil(factory); - } - @Test( expectedExceptions = ApiException.class, expectedExceptionsMessageRegExp = FactoryConstants.ILLEGAL_FACTORY_BY_UNTIL_MESSAGE) @@ -296,7 +109,7 @@ public void shouldNotValidateIfUntilSinceAfterCurrentTime() throws ApiException @Test public void shouldValidateTrackedParamsIfOrgIdIsMissingButOnPremisesTrue() throws Exception { final DtoFactory dtoFactory = getInstance(); - FactoryDto factory = dtoFactory.createDto(FactoryDto.class); + FactoryDevfileV2Dto factory = dtoFactory.createDto(FactoryDevfileV2Dto.class); factory .withV("4.0") .withPolicies( @@ -315,7 +128,7 @@ public void shouldNotValidateOpenfileActionIfInWrongSectionOnAppClosed() throws List actions = singletonList(newDto(IdeActionDto.class).withId("openFile")); IdeDto ide = newDto(IdeDto.class).withOnAppClosed(newDto(OnAppClosedDto.class).withActions(actions)); - FactoryDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); + FactoryMetaDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); // when validator.validateProjectActions(factoryWithAccountId); } @@ -327,7 +140,7 @@ public void shouldNotValidateFindReplaceActionIfInWrongSectionOnAppLoaded() thro List actions = singletonList(newDto(IdeActionDto.class).withId("findReplace")); IdeDto ide = newDto(IdeDto.class).withOnAppLoaded(newDto(OnAppLoadedDto.class).withActions(actions)); - FactoryDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); + FactoryMetaDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); // when validator.validateProjectActions(factoryWithAccountId); } @@ -340,7 +153,7 @@ public void shouldNotValidateIfOpenfileActionInsufficientParams() throws Excepti IdeDto ide = newDto(IdeDto.class) .withOnProjectsLoaded(newDto(OnProjectsLoadedDto.class).withActions(actions)); - FactoryDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); + FactoryMetaDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); // when validator.validateProjectActions(factoryWithAccountId); } @@ -353,7 +166,7 @@ public void shouldNotValidateIfrunCommandActionInsufficientParams() throws Excep IdeDto ide = newDto(IdeDto.class) .withOnProjectsLoaded(newDto(OnProjectsLoadedDto.class).withActions(actions)); - FactoryDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); + FactoryMetaDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); // when validator.validateProjectActions(factoryWithAccountId); } @@ -366,7 +179,7 @@ public void shouldNotValidateIfOpenWelcomePageActionInsufficientParams() throws singletonList(newDto(IdeActionDto.class).withId("openWelcomePage")); IdeDto ide = newDto(IdeDto.class).withOnAppLoaded((newDto(OnAppLoadedDto.class).withActions(actions))); - FactoryDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); + FactoryMetaDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); // when validator.validateProjectActions(factoryWithAccountId); } @@ -384,7 +197,7 @@ public void shouldNotValidateIfFindReplaceActionInsufficientParams() throws Exce IdeDto ide = newDto(IdeDto.class) .withOnProjectsLoaded(newDto(OnProjectsLoadedDto.class).withActions(actions)); - FactoryDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); + FactoryMetaDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); // when validator.validateProjectActions(factoryWithAccountId); } @@ -402,7 +215,7 @@ public void shouldValidateFindReplaceAction() throws Exception { IdeDto ide = newDto(IdeDto.class) .withOnProjectsLoaded(newDto(OnProjectsLoadedDto.class).withActions(actions)); - FactoryDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); + FactoryMetaDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); // when validator.validateProjectActions(factoryWithAccountId); } @@ -418,7 +231,7 @@ public void shouldValidateOpenfileAction() throws Exception { IdeDto ide = newDto(IdeDto.class) .withOnProjectsLoaded(newDto(OnProjectsLoadedDto.class).withActions(actions)); - FactoryDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); + FactoryMetaDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide); // when validator.validateProjectActions(factoryWithAccountId); } @@ -428,7 +241,7 @@ public Object[][] trackedFactoryParameterWithoutValidAccountId() throws URISyntaxException, IOException, NoSuchMethodException { return new Object[][] { { - newDto(FactoryDto.class) + newDto(FactoryMetaDto.class) .withV("4.0") .withIde( newDto(IdeDto.class) @@ -449,31 +262,20 @@ public Object[][] trackedFactoryParameterWithoutValidAccountId() .build()))))) }, { - newDto(FactoryDto.class) + newDto(FactoryMetaDto.class) .withV("4.0") .withPolicies(newDto(PoliciesDto.class).withSince(10000L)) }, { - newDto(FactoryDto.class) + newDto(FactoryMetaDto.class) .withV("4.0") .withPolicies(newDto(PoliciesDto.class).withUntil(10000L)) }, { - newDto(FactoryDto.class) + newDto(FactoryMetaDto.class) .withV("4.0") .withPolicies(newDto(PoliciesDto.class).withReferer("host")) } }; } - - private FactoryDto prepareFactoryWithGivenStorage(String type, String location, String path) { - return factory.withWorkspace( - newDto(WorkspaceConfigDto.class) - .withProjects( - singletonList( - newDto(ProjectConfigDto.class) - .withSource( - newDto(SourceStorageDto.class).withType(type).withLocation(location)) - .withPath(path)))); - } } diff --git a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryCreateAndAcceptValidatorsImplsTest.java b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryCreateAndAcceptValidatorsImplsTest.java deleted file mode 100644 index 96e74b4c87a..00000000000 --- a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryCreateAndAcceptValidatorsImplsTest.java +++ /dev/null @@ -1,91 +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.factory.server.impl; - -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import org.eclipse.che.api.core.ApiException; -import org.eclipse.che.api.core.model.workspace.WorkspaceConfig; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; -import org.eclipse.che.api.user.server.spi.PreferenceDao; -import org.eclipse.che.api.user.server.spi.UserDao; -import org.eclipse.che.api.workspace.server.WorkspaceValidator; -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 org.eclipse.che.api.factory.server.impl.FactoryAcceptValidatorImpl} and {@link - * FactoryCreateValidatorImpl} - */ -@Listeners(value = {MockitoTestNGListener.class}) -public class FactoryCreateAndAcceptValidatorsImplsTest { - - @Mock private UserDao userDao; - - @Mock private PreferenceDao preferenceDao; - - @Mock private FactoryDto factory; - - @Mock private WorkspaceValidator workspaceConfigValidator; - - private FactoryAcceptValidatorImpl acceptValidator; - - private FactoryCreateValidatorImpl createValidator; - - @BeforeMethod - public void setUp() throws Exception { - - acceptValidator = new FactoryAcceptValidatorImpl(); - createValidator = new FactoryCreateValidatorImpl(workspaceConfigValidator); - } - - @Test - public void testValidateOnCreate() throws Exception { - FactoryCreateValidatorImpl spy = spy(createValidator); - doNothing().when(spy).validateProjects(any(FactoryDto.class)); - doNothing().when(spy).validateCurrentTimeAfterSinceUntil(any(FactoryDto.class)); - doNothing().when(spy).validateProjectActions(any(FactoryDto.class)); - doNothing().when(workspaceConfigValidator).validateConfig(nullable(WorkspaceConfig.class)); - - // main invoke - spy.validateOnCreate(factory); - - verify(spy).validateProjects(any(FactoryDto.class)); - verify(spy).validateCurrentTimeAfterSinceUntil(any(FactoryDto.class)); - verify(spy).validateOnCreate(any(FactoryDto.class)); - verify(spy).validateProjectActions(any(FactoryDto.class)); - verifyNoMoreInteractions(spy); - } - - @Test - public void testOnAcceptEncoded() throws ApiException { - FactoryAcceptValidatorImpl spy = spy(acceptValidator); - doNothing().when(spy).validateCurrentTimeBetweenSinceUntil(any(FactoryDto.class)); - doNothing().when(spy).validateProjectActions(any(FactoryDto.class)); - - // main invoke - spy.validateOnAccept(factory); - - verify(spy).validateCurrentTimeBetweenSinceUntil(any(FactoryDto.class)); - verify(spy).validateOnAccept(any(FactoryDto.class)); - verify(spy).validateProjectActions(any(FactoryDto.class)); - verifyNoMoreInteractions(spy); - } -} diff --git a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryEditValidatorImplTest.java b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryEditValidatorImplTest.java deleted file mode 100644 index 31c42e375a9..00000000000 --- a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/impl/FactoryEditValidatorImplTest.java +++ /dev/null @@ -1,93 +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.factory.server.impl; - -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.eclipse.che.api.core.ApiException; -import org.eclipse.che.api.core.ForbiddenException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.api.factory.server.FactoryEditValidator; -import org.eclipse.che.api.factory.shared.dto.AuthorDto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; -import org.eclipse.che.commons.env.EnvironmentContext; -import org.eclipse.che.commons.subject.Subject; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.testng.MockitoTestNGListener; -import org.testng.annotations.Listeners; -import org.testng.annotations.Test; - -/** - * Tests for {@link FactoryEditValidator} - * - * @author Florent Benoit - */ -@Listeners(value = {MockitoTestNGListener.class}) -public class FactoryEditValidatorImplTest { - - @Mock private FactoryDto factory; - - @InjectMocks private FactoryEditValidator factoryEditValidator = new FactoryEditValidatorImpl(); - - /** - * Check missing author data - * - * @throws ApiException - */ - @Test(expectedExceptions = ServerException.class) - public void testNoAuthor() throws ApiException { - setCurrentUser(""); - factoryEditValidator.validate(factory); - } - - /** - * Check when user is not same than the one than create the factory - * - * @throws ApiException - */ - @Test(expectedExceptions = ForbiddenException.class) - public void testUserIsNotTheAuthor() throws ApiException { - String userId = "florent"; - setCurrentUser(userId); - - AuthorDto author = mock(AuthorDto.class); - doReturn(author).when(factory).getCreator(); - doReturn("john").when(author).getUserId(); - - factoryEditValidator.validate(factory); - } - - /** - * Check when user is the same than the one than create the factory - * - * @throws ApiException - */ - @Test - public void testUserIsTheAuthor() throws ApiException { - String userId = "florent"; - setCurrentUser(userId); - AuthorDto author = mock(AuthorDto.class); - doReturn(author).when(factory).getCreator(); - doReturn(userId).when(author).getUserId(); - - factoryEditValidator.validate(factory); - } - - private void setCurrentUser(String userId) { - Subject subject = mock(Subject.class); - when(subject.getUserId()).thenReturn(userId); - EnvironmentContext.getCurrent().setSubject(subject); - } -} diff --git a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/urlfactory/ProjectConfigDtoMergerTest.java b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/urlfactory/ProjectConfigDtoMergerTest.java deleted file mode 100644 index 61619615f83..00000000000 --- a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/urlfactory/ProjectConfigDtoMergerTest.java +++ /dev/null @@ -1,91 +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.factory.server.urlfactory; - -import static org.eclipse.che.dto.server.DtoFactory.newDto; -import static org.testng.Assert.assertEquals; - -import java.util.Collections; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; -import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; -import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; -import org.mockito.InjectMocks; -import org.mockito.testng.MockitoTestNGListener; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Listeners; -import org.testng.annotations.Test; - -/** - * Testing {@link ProjectConfigDtoMerger} - * - * @author Florent Benoit - */ -@Listeners(MockitoTestNGListener.class) -public class ProjectConfigDtoMergerTest { - - /** Location */ - private static final String DUMMY_LOCATION = "dummy-location"; - - @InjectMocks private ProjectConfigDtoMerger projectConfigDtoMerger; - - private ProjectConfigDto computedProjectConfig; - - private FactoryDto factory; - - @BeforeClass - public void setup() { - WorkspaceConfigDto workspaceConfigDto = newDto(WorkspaceConfigDto.class); - this.factory = newDto(FactoryDto.class).withWorkspace(workspaceConfigDto); - - SourceStorageDto sourceStorageDto = newDto(SourceStorageDto.class).withLocation(DUMMY_LOCATION); - computedProjectConfig = newDto(ProjectConfigDto.class).withSource(sourceStorageDto); - } - - /** Check project is added when we have no project */ - @Test - public void mergeWithoutAnyProject() { - - // no project - Assert.assertTrue(factory.getWorkspace().getProjects().isEmpty()); - - // merge - projectConfigDtoMerger.merge(factory, () -> computedProjectConfig); - - // project - assertEquals(factory.getWorkspace().getProjects().size(), 1); - - assertEquals(factory.getWorkspace().getProjects().get(0), computedProjectConfig); - } - - /** Check source are added if there is only one project without source */ - @Test - public void mergeWithoutOneProjectWithoutSource() { - - // add existing project - ProjectConfigDto projectConfigDto = newDto(ProjectConfigDto.class); - factory.getWorkspace().setProjects(Collections.singletonList(projectConfigDto)); - // no source storage - Assert.assertNull(projectConfigDto.getSource()); - - // merge - projectConfigDtoMerger.merge(factory, () -> computedProjectConfig); - - // project still 1 - assertEquals(factory.getWorkspace().getProjects().size(), 1); - - SourceStorageDto sourceStorageDto = factory.getWorkspace().getProjects().get(0).getSource(); - - assertEquals(sourceStorageDto.getLocation(), DUMMY_LOCATION); - } -} diff --git a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/urlfactory/URLFactoryBuilderTest.java b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/urlfactory/URLFactoryBuilderTest.java index 062d0e98204..0e293657a53 100644 --- a/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/urlfactory/URLFactoryBuilderTest.java +++ b/wsmaster/che-core-api-factory/src/test/java/org/eclipse/che/api/factory/server/urlfactory/URLFactoryBuilderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012-2023 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,11 +15,6 @@ import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.eclipse.che.api.workspace.server.devfile.Constants.KUBERNETES_COMPONENT_TYPE; -import static org.eclipse.che.api.workspace.shared.Constants.WORKSPACE_TOOLING_EDITOR_ATTRIBUTE; -import static org.eclipse.che.api.workspace.shared.Constants.WORKSPACE_TOOLING_PLUGINS_ATTRIBUTE; -import static org.eclipse.che.dto.server.DtoFactory.newDto; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -34,7 +29,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -47,20 +41,17 @@ import org.eclipse.che.api.factory.server.scm.exception.UnknownScmProviderException; import org.eclipse.che.api.factory.server.urlfactory.RemoteFactoryUrl.DevfileLocation; import org.eclipse.che.api.factory.shared.dto.FactoryDevfileV2Dto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; import org.eclipse.che.api.factory.shared.dto.FactoryMetaDto; import org.eclipse.che.api.workspace.server.devfile.DevfileParser; import org.eclipse.che.api.workspace.server.devfile.DevfileVersionDetector; import org.eclipse.che.api.workspace.server.devfile.FileContentProvider; import org.eclipse.che.api.workspace.server.devfile.URLFetcher; import org.eclipse.che.api.workspace.server.devfile.exception.DevfileException; -import org.eclipse.che.api.workspace.server.devfile.exception.OverrideParameterException; import org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl; import org.eclipse.che.api.workspace.server.model.impl.RecipeImpl; import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl; 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.shared.dto.WorkspaceConfigDto; import org.mockito.Mock; import org.mockito.testng.MockitoTestNGListener; import org.testng.annotations.BeforeMethod; @@ -98,20 +89,6 @@ public void setUp() throws IOException, DevfileException { defaultEditor, defaultPlugin, true, devfileParser, devfileVersionDetector); } - @Test - public void checkDefaultConfiguration() throws Exception { - Map attributes = new HashMap<>(); - attributes.put(WORKSPACE_TOOLING_EDITOR_ATTRIBUTE, defaultEditor); - attributes.put(WORKSPACE_TOOLING_PLUGINS_ATTRIBUTE, defaultPlugin); - // setup environment - WorkspaceConfigDto expectedWsConfig = - newDto(WorkspaceConfigDto.class).withAttributes(attributes).withName("foo"); - - WorkspaceConfigDto actualWsConfigDto = urlFactoryBuilder.buildDefaultWorkspaceConfig("foo"); - - assertEquals(actualWsConfigDto, expectedWsConfig); - } - @Test public void checkWithCustomDevfileAndRecipe() throws Exception { @@ -126,8 +103,6 @@ public void checkWithCustomDevfileAndRecipe() throws Exception { when(devfileParser.parseYamlRaw(anyString())) .thenReturn(new ObjectNode(JsonNodeFactory.instance)); - when(devfileParser.parseJsonNode(any(JsonNode.class), anyMap())).thenReturn(devfile); - when(devfileVersionDetector.devfileMajorVersion(any(JsonNode.class))).thenReturn(1); when(fileContentProvider.fetchContent(anyString())).thenReturn("content"); FactoryMetaDto factory = @@ -141,7 +116,7 @@ public void checkWithCustomDevfileAndRecipe() throws Exception { assertNotNull(factory); assertNull(factory.getSource()); - assertTrue(factory instanceof FactoryDto); + assertTrue(factory instanceof FactoryDevfileV2Dto); } @Test @@ -152,7 +127,6 @@ public void testDevfileV2() throws ApiException, DevfileException, IOException { JsonNode devfile = new ObjectNode(JsonNodeFactory.instance); when(devfileParser.parseYamlRaw(anyString())).thenReturn(devfile); when(devfileParser.convertYamlToMap(devfile)).thenReturn(devfileAsMap); - when(devfileVersionDetector.devfileMajorVersion(devfile)).thenReturn(2); when(fileContentProvider.fetchContent(anyString())).thenReturn("content"); FactoryMetaDto factory = @@ -178,7 +152,6 @@ public void testDevfileV2WithFilename() throws ApiException, DevfileException, I JsonNode devfile = new ObjectNode(JsonNodeFactory.instance); when(devfileParser.parseYamlRaw(anyString())).thenReturn(devfile); when(devfileParser.convertYamlToMap(devfile)).thenReturn(devfileAsMap); - when(devfileVersionDetector.devfileMajorVersion(devfile)).thenReturn(2); when(fileContentProvider.fetchContent(anyString())).thenReturn("content"); RemoteFactoryUrl githubLikeRemoteUrl = @@ -252,7 +225,6 @@ public void testDevfileSpecifyingFilename() throws ApiException, DevfileExceptio JsonNode devfile = new ObjectNode(JsonNodeFactory.instance); when(devfileParser.parseYamlRaw(anyString())).thenReturn(devfile); when(devfileParser.convertYamlToMap(devfile)).thenReturn(devfileAsMap); - when(devfileVersionDetector.devfileMajorVersion(devfile)).thenReturn(2); when(fileContentProvider.fetchContent(anyString())).thenReturn("content"); RemoteFactoryUrl githubLikeRemoteUrl = @@ -337,7 +309,6 @@ public void testShouldReturnV2WithDevworkspacesDisabled() JsonNode devfile = new ObjectNode(JsonNodeFactory.instance); when(devfileParser.parseYamlRaw(anyString())).thenReturn(devfile); when(devfileParser.convertYamlToMap(devfile)).thenReturn(devfileAsMap); - when(devfileVersionDetector.devfileMajorVersion(devfile)).thenReturn(2); when(fileContentProvider.fetchContent(anyString())).thenReturn("content"); URLFactoryBuilder localUrlFactoryBuilder = @@ -383,40 +354,6 @@ public Object[][] devfiles() { return new Object[][] {{justName, NAME}, {justGenerateName, GEN_NAME}, {bothNames, GEN_NAME}}; } - @Test(dataProvider = "devfiles") - public void checkThatDtoHasCorrectNames(DevfileImpl devfile, String expectedGenerateName) - throws ApiException, IOException, OverrideParameterException, DevfileException { - DefaultFactoryUrl defaultFactoryUrl = mock(DefaultFactoryUrl.class); - FileContentProvider fileContentProvider = mock(FileContentProvider.class); - when(defaultFactoryUrl.devfileFileLocations()) - .thenReturn( - singletonList( - new DevfileLocation() { - @Override - public Optional filename() { - return Optional.empty(); - } - - @Override - public String location() { - return "http://foo.bar/anything"; - } - })); - when(fileContentProvider.fetchContent(anyString())).thenReturn("anything"); - when(devfileParser.parseYamlRaw("anything")) - .thenReturn(new ObjectNode(JsonNodeFactory.instance)); - when(devfileParser.parseJsonNode(any(JsonNode.class), anyMap())).thenReturn(devfile); - when(devfileVersionDetector.devfileMajorVersion(any(JsonNode.class))).thenReturn(1); - FactoryDto factory = - (FactoryDto) - urlFactoryBuilder - .createFactoryFromDevfile(defaultFactoryUrl, fileContentProvider, emptyMap(), false) - .get(); - - assertNull(factory.getDevfile().getMetadata().getName()); - assertEquals(factory.getDevfile().getMetadata().getGenerateName(), expectedGenerateName); - } - @Test(dataProvider = "devfileExceptions") public void checkCorrectExceptionThrownDependingOnCause( Throwable cause,