From 7e3a15a988af13e8a4e57ba9c486eea429dad843 Mon Sep 17 00:00:00 2001 From: nomuna Date: Sun, 5 Sep 2021 00:50:11 +0200 Subject: [PATCH 1/4] Fix test failures on windows The "npm" executable can not be found on windows. Using "npm.cmd" instead of "npm" fixes the tests. - Added two constants for *nix and windows executables and use the fitting one after running an os detection. - Tests adjusted to reflect the npm command string change. Fix #312 --- .../github/jhipster/online/service/JHipsterService.java | 8 +++++++- .../jhipster/online/service/GeneratorServiceTest.java | 7 +++++-- .../jhipster/online/service/JHipsterServiceTest.java | 6 ++++-- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/github/jhipster/online/service/JHipsterService.java b/src/main/java/io/github/jhipster/online/service/JHipsterService.java index 159f3ae5..3803eca6 100644 --- a/src/main/java/io/github/jhipster/online/service/JHipsterService.java +++ b/src/main/java/io/github/jhipster/online/service/JHipsterService.java @@ -42,6 +42,10 @@ public class JHipsterService { private static final String SKIP_INSTALL = "--skip-install"; + public static final String NPM_NIX = "npm"; + + public static final String NPM_WIN = "npm.cmd"; + private final LogsService logsService; private final Executor taskExecutor; @@ -62,7 +66,9 @@ public JHipsterService(LogsService logsService, ApplicationProperties applicatio public void installNpmDependencies(String generationId, File workingDir) throws IOException { this.logsService.addLog(generationId, "Installing the JHipster version used by the project"); - this.runProcess(generationId, workingDir, "npm", "install", "--ignore-scripts", "--package-lock-only"); + final String os = System.getProperty("os.name"); + final String command = os.contains("indows") ? NPM_WIN : NPM_NIX; + this.runProcess(generationId, workingDir, command, "install", "--ignore-scripts", "--package-lock-only"); } public void generateApplication(String generationId, File workingDir) throws IOException { diff --git a/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java b/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java index b8066be0..0bf5dcc4 100644 --- a/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java +++ b/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java @@ -70,9 +70,12 @@ void shouldConstructGeneratorService() { @Test void generateZippedApplication() throws IOException { - String result = generatorService.generateZippedApplication(applicationId, applicationConfiguration); + final String expected = "/tmp/jhipster/applications/app-id.zip"; + final String result = generatorService.generateZippedApplication(applicationId, applicationConfiguration); + final String os = System.getProperty("os.name"); + final String workingCopy = os.contains("indows") ? result.replaceAll("\\\\", "/") : result; - assertThat(result).isEqualTo("/tmp/jhipster/applications/app-id.zip"); + assertThat(workingCopy).isEqualTo(expected); verify(logsService).addLog(applicationId, "Creating `.yo-rc.json` file"); verify(jHipsterService).generateApplication(applicationId, new File("/tmp/jhipster/applications/app-id")); assertThat(new File("/tmp/jhipster/applications/app-id/.yo-rc.json")).isFile().hasContent(applicationConfiguration); diff --git a/src/test/java/io/github/jhipster/online/service/JHipsterServiceTest.java b/src/test/java/io/github/jhipster/online/service/JHipsterServiceTest.java index 123d8794..9c685fb5 100644 --- a/src/test/java/io/github/jhipster/online/service/JHipsterServiceTest.java +++ b/src/test/java/io/github/jhipster/online/service/JHipsterServiceTest.java @@ -81,15 +81,17 @@ void shouldRunProcess(@TempDir Path tempDir) throws IOException { @Test void shouldInstallNpmDependencies(@TempDir Path tempDir) throws IOException { String generationId = "generation-id"; + final String os = System.getProperty("os.name"); + final String command = os.contains("indows") ? JHipsterService.NPM_WIN : JHipsterService.NPM_NIX; willDoNothing() .given(jHipsterServiceSpy) - .runProcess(generationId, tempDir.toFile(), "npm", "install", "--ignore" + "-scripts", "--package-lock-only"); + .runProcess(generationId, tempDir.toFile(), command, "install", "--ignore" + "-scripts", "--package-lock-only"); jHipsterServiceSpy.installNpmDependencies(generationId, tempDir.toFile()); verify(logsService).addLog(generationId, "Installing the JHipster version used by the project"); verify(jHipsterServiceSpy) - .runProcess(generationId, tempDir.toFile(), "npm", "install", "--ignore-scripts", "--package" + "-lock" + "-only"); + .runProcess(generationId, tempDir.toFile(), command, "install", "--ignore-scripts", "--package" + "-lock" + "-only"); } @Test From faf455cb049e352e91ca69cf98853a383044d84e Mon Sep 17 00:00:00 2001 From: nomuna Date: Wed, 15 Sep 2021 11:21:08 +0200 Subject: [PATCH 2/4] Fix test failures on windows - hard coded, os specific path string replaced with os-independent version in GeneratorService and GeneratorServiceTest - removed unused imports in GeneratorServiceTest --- .../online/service/GeneratorService.java | 10 +++++- .../online/service/GeneratorServiceTest.java | 36 ++++++++++++------- 2 files changed, 33 insertions(+), 13 deletions(-) diff --git a/src/main/java/io/github/jhipster/online/service/GeneratorService.java b/src/main/java/io/github/jhipster/online/service/GeneratorService.java index ef46c755..c18f1994 100644 --- a/src/main/java/io/github/jhipster/online/service/GeneratorService.java +++ b/src/main/java/io/github/jhipster/online/service/GeneratorService.java @@ -38,6 +38,14 @@ @Service public class GeneratorService { + public static final String JHIPSTER = "jhipster"; + + public static final String APPLICATIONS = "applications"; + + public static final String OS_TEMP_DIR = System.getProperty("java.io.tmpdir"); + + public static final String FILE_SEPARATOR = System.getProperty("file.separator"); + private final Logger log = LoggerFactory.getLogger(GeneratorService.class); private final ApplicationProperties applicationProperties; @@ -87,7 +95,7 @@ public void generateGitApplication( } private File generateApplication(String applicationId, String applicationConfiguration) throws IOException { - File workingDir = new File(applicationProperties.getTmpFolder() + "/jhipster/applications/" + applicationId); + final File workingDir = new File(String.join(FILE_SEPARATOR, OS_TEMP_DIR, JHIPSTER, APPLICATIONS, applicationId)); FileUtils.forceMkdir(workingDir); this.generateYoRc(applicationId, workingDir, applicationConfiguration); log.info(".yo-rc.json created"); diff --git a/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java b/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java index 0bf5dcc4..3f37c588 100644 --- a/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java +++ b/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java @@ -18,10 +18,10 @@ */ package io.github.jhipster.online.service; +import static io.github.jhipster.online.service.GeneratorService.*; +import static java.util.Arrays.*; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import io.github.jhipster.online.config.ApplicationProperties; @@ -34,7 +34,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -70,30 +69,43 @@ void shouldConstructGeneratorService() { @Test void generateZippedApplication() throws IOException { - final String expected = "/tmp/jhipster/applications/app-id.zip"; + final String cwd = buildCwdPath(); + + final String expected = cwd + ".zip"; + final String expectedYoRcPath = cwd + FILE_SEPARATOR + ".yo-rc.json"; + final String result = generatorService.generateZippedApplication(applicationId, applicationConfiguration); - final String os = System.getProperty("os.name"); - final String workingCopy = os.contains("indows") ? result.replaceAll("\\\\", "/") : result; - assertThat(workingCopy).isEqualTo(expected); + assertThat(result).isEqualTo(expected); verify(logsService).addLog(applicationId, "Creating `.yo-rc.json` file"); - verify(jHipsterService).generateApplication(applicationId, new File("/tmp/jhipster/applications/app-id")); - assertThat(new File("/tmp/jhipster/applications/app-id/.yo-rc.json")).isFile().hasContent(applicationConfiguration); + verify(jHipsterService).generateApplication(applicationId, new File(cwd)); + assertThat(new File(expectedYoRcPath)).isFile().hasContent(applicationConfiguration); } @Test void generateGitApplication() throws GitAPIException, IOException, URISyntaxException { User user = mock(User.class); - File workingDir = new File("/tmp/jhipster/applications/app-id"); + final String cwd = buildCwdPath(); + File workingDir = new File(cwd); generatorService.generateGitApplication(user, applicationId, applicationConfiguration, "gh-org", "repo", GitProvider.GITHUB); verify(logsService).addLog(applicationId, "Creating `.yo-rc.json` file"); - verify(jHipsterService).generateApplication(applicationId, new File("/tmp/jhipster/applications/app-id")); - assertThat(new File("/tmp/jhipster/applications/app-id/.yo-rc.json")).isFile().hasContent(applicationConfiguration); + verify(jHipsterService).generateApplication(applicationId, workingDir); + assertThat(new File(cwd + FILE_SEPARATOR + ".yo-rc.json")).isFile().hasContent(applicationConfiguration); verify(logsService).addLog(applicationId, "Pushing the application to the Git remote repository"); verify(gitService).pushNewApplicationToGit(user, workingDir, "gh-org", "repo", GitProvider.GITHUB); verify(logsService).addLog(applicationId, "Application successfully pushed!"); verify(gitService).cleanUpDirectory(workingDir); } + + private String buildCwdPath() { + String workingCopy = OS_TEMP_DIR; // will be /tmp in linux, C:\Users\CurrentUser\AppData\Local\Temp\ in windows + // handling the trailing file separator in case we are in windows + if (OS_TEMP_DIR.endsWith(FILE_SEPARATOR)) { + int length = OS_TEMP_DIR.length(); + workingCopy = OS_TEMP_DIR.substring(0, length - 1); + } + return String.join(FILE_SEPARATOR, asList(workingCopy, JHIPSTER, APPLICATIONS, applicationId)); + } } From b99ddfa3a66bf73efe4d1465b842248820532c46 Mon Sep 17 00:00:00 2001 From: nomuna Date: Wed, 15 Sep 2021 14:24:08 +0200 Subject: [PATCH 3/4] Fix test failures on windows - extended ApplicationProperties for npm process configuration - the default value for tempDir in ApplicationProperties is the OS spec. temporary folder - removed OS detection code from JHipsterService - OS detection and npm path adjustment done to ApplicationProperties before each test --- .../online/config/ApplicationProperties.java | 34 ++++++++++++++++++- .../online/service/GeneratorService.java | 5 ++- .../online/service/JHipsterService.java | 11 +++--- .../online/service/GeneratorServiceTest.java | 10 +++--- .../online/service/JHipsterServiceTest.java | 10 ++++-- 5 files changed, 55 insertions(+), 15 deletions(-) diff --git a/src/main/java/io/github/jhipster/online/config/ApplicationProperties.java b/src/main/java/io/github/jhipster/online/config/ApplicationProperties.java index d5cd380b..27a303bd 100644 --- a/src/main/java/io/github/jhipster/online/config/ApplicationProperties.java +++ b/src/main/java/io/github/jhipster/online/config/ApplicationProperties.java @@ -31,18 +31,28 @@ public class ApplicationProperties { private JhipsterCmd jhipsterCmd = new JhipsterCmd(); + private NpmCmd npmCmd = new NpmCmd(); + private final Github github = new Github(); private final Gitlab gitlab = new Gitlab(); private final Mail mail = new Mail(); - private String tmpFolder = "/tmp"; + private String tmpFolder = System.getProperty("java.io.tmpdir"); public JhipsterCmd getJhipsterCmd() { return jhipsterCmd; } + public NpmCmd getNpmCmd() { + return npmCmd; + } + + public void setNpmCmd(NpmCmd npmCmd) { + this.npmCmd = npmCmd; + } + public void setJhipsterCmd(JhipsterCmd jhipsterCmd) { this.jhipsterCmd = jhipsterCmd; } @@ -89,6 +99,28 @@ public void setTimeout(Integer timeout) { } } + public static class NpmCmd { + + private String cmd = "npm"; + private Integer timeout = 120; + + public String getCmd() { + return cmd; + } + + public void setCmd(String cmd) { + this.cmd = cmd; + } + + public Integer getTimeout() { + return timeout; + } + + public void setTimeout(Integer timeout) { + this.timeout = timeout; + } + } + public static class Github { private String clientId; diff --git a/src/main/java/io/github/jhipster/online/service/GeneratorService.java b/src/main/java/io/github/jhipster/online/service/GeneratorService.java index c18f1994..f7d754bf 100644 --- a/src/main/java/io/github/jhipster/online/service/GeneratorService.java +++ b/src/main/java/io/github/jhipster/online/service/GeneratorService.java @@ -28,6 +28,7 @@ import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.api.errors.GitAPIException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -95,7 +96,9 @@ public void generateGitApplication( } private File generateApplication(String applicationId, String applicationConfiguration) throws IOException { - final File workingDir = new File(String.join(FILE_SEPARATOR, OS_TEMP_DIR, JHIPSTER, APPLICATIONS, applicationId)); + final String fromConfig = applicationProperties.getTmpFolder(); + final String tempDir = StringUtils.isBlank(fromConfig) ? OS_TEMP_DIR : fromConfig; + final File workingDir = new File(String.join(FILE_SEPARATOR, tempDir, JHIPSTER, APPLICATIONS, applicationId)); FileUtils.forceMkdir(workingDir); this.generateYoRc(applicationId, workingDir, applicationConfiguration); log.info(".yo-rc.json created"); diff --git a/src/main/java/io/github/jhipster/online/service/JHipsterService.java b/src/main/java/io/github/jhipster/online/service/JHipsterService.java index 3803eca6..ba7124f0 100644 --- a/src/main/java/io/github/jhipster/online/service/JHipsterService.java +++ b/src/main/java/io/github/jhipster/online/service/JHipsterService.java @@ -42,16 +42,14 @@ public class JHipsterService { private static final String SKIP_INSTALL = "--skip-install"; - public static final String NPM_NIX = "npm"; - - public static final String NPM_WIN = "npm.cmd"; - private final LogsService logsService; private final Executor taskExecutor; private final String jhipsterCommand; + private final String npmCommand; + private final Integer timeout; public JHipsterService(LogsService logsService, ApplicationProperties applicationProperties, Executor taskExecutor) { @@ -59,6 +57,7 @@ public JHipsterService(LogsService logsService, ApplicationProperties applicatio this.taskExecutor = taskExecutor; jhipsterCommand = applicationProperties.getJhipsterCmd().getCmd(); + npmCommand = applicationProperties.getNpmCmd().getCmd(); timeout = applicationProperties.getJhipsterCmd().getTimeout(); log.info("JHipster service will be using \"{}\" to run generator-jhipster.", jhipsterCommand); @@ -66,9 +65,7 @@ public JHipsterService(LogsService logsService, ApplicationProperties applicatio public void installNpmDependencies(String generationId, File workingDir) throws IOException { this.logsService.addLog(generationId, "Installing the JHipster version used by the project"); - final String os = System.getProperty("os.name"); - final String command = os.contains("indows") ? NPM_WIN : NPM_NIX; - this.runProcess(generationId, workingDir, command, "install", "--ignore-scripts", "--package-lock-only"); + this.runProcess(generationId, workingDir, npmCommand, "install", "--ignore-scripts", "--package-lock-only"); } public void generateApplication(String generationId, File workingDir) throws IOException { diff --git a/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java b/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java index 3f37c588..c16bd3a4 100644 --- a/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java +++ b/src/test/java/io/github/jhipster/online/service/GeneratorServiceTest.java @@ -30,6 +30,7 @@ import java.io.File; import java.io.IOException; import java.net.URISyntaxException; +import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.api.errors.GitAPIException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -100,11 +101,12 @@ void generateGitApplication() throws GitAPIException, IOException, URISyntaxExce } private String buildCwdPath() { - String workingCopy = OS_TEMP_DIR; // will be /tmp in linux, C:\Users\CurrentUser\AppData\Local\Temp\ in windows + final String fromConfig = applicationProperties.getTmpFolder(); + String workingCopy = StringUtils.isBlank(fromConfig) ? OS_TEMP_DIR : fromConfig; // handling the trailing file separator in case we are in windows - if (OS_TEMP_DIR.endsWith(FILE_SEPARATOR)) { - int length = OS_TEMP_DIR.length(); - workingCopy = OS_TEMP_DIR.substring(0, length - 1); + if (workingCopy.endsWith(FILE_SEPARATOR)) { + int length = workingCopy.length(); + workingCopy = workingCopy.substring(0, length - 1); } return String.join(FILE_SEPARATOR, asList(workingCopy, JHIPSTER, APPLICATIONS, applicationId)); } diff --git a/src/test/java/io/github/jhipster/online/service/JHipsterServiceTest.java b/src/test/java/io/github/jhipster/online/service/JHipsterServiceTest.java index 9c685fb5..ca419faf 100644 --- a/src/test/java/io/github/jhipster/online/service/JHipsterServiceTest.java +++ b/src/test/java/io/github/jhipster/online/service/JHipsterServiceTest.java @@ -32,6 +32,7 @@ import java.io.IOException; import java.nio.file.Path; import java.util.concurrent.Executor; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -62,6 +63,10 @@ class JHipsterServiceTest { @BeforeEach void shouldConstructJHipsterService() { + final String os = System.getProperty("os.name"); + final String command = os.contains("indows") ? "npm.cmd" : applicationProperties.getNpmCmd().getCmd(); + applicationProperties.getNpmCmd().setCmd(command); + jHipsterService = new JHipsterService(logsService, applicationProperties, taskExecutor); jHipsterServiceSpy = spy(jHipsterService); } @@ -81,8 +86,9 @@ void shouldRunProcess(@TempDir Path tempDir) throws IOException { @Test void shouldInstallNpmDependencies(@TempDir Path tempDir) throws IOException { String generationId = "generation-id"; - final String os = System.getProperty("os.name"); - final String command = os.contains("indows") ? JHipsterService.NPM_WIN : JHipsterService.NPM_NIX; + final String command = applicationProperties.getNpmCmd().getCmd(); + applicationProperties.getNpmCmd().setCmd(command); + willDoNothing() .given(jHipsterServiceSpy) .runProcess(generationId, tempDir.toFile(), command, "install", "--ignore" + "-scripts", "--package-lock-only"); From 15eafed25a1f042e05b28ab17194197c8852d203 Mon Sep 17 00:00:00 2001 From: nomuna Date: Tue, 7 Sep 2021 06:39:00 +0200 Subject: [PATCH 4/4] Fixed Sonar Bugs and some Criticals - removed tests from coverage, and analysis - removed dtos and domain classes from redundancy check since sonar reports common fields in entities/dtos as redundancy - made sonar ignore some useful comments using // NOSONAR marking - removed commented out codes - removed / refactored cases of logging and throwing exceptions - TODO comment wrapped in multiline/javadoc comment so that sonar does not see it as commented out code - Refactored some fields and their getters and setters to conform Java Language Conventions - replaced switch with map lookup and lambda call to reduce the cyclomatic complexity of alert-error.component.ts Fix #209 --- sonar-project.properties | 4 + .../online/config/LiquibaseConfiguration.java | 4 +- .../jhipster/online/service/CiCdService.java | 1 - .../online/service/GeneratorService.java | 10 +-- .../jhipster/online/service/GitService.java | 2 +- .../online/service/JHipsterService.java | 52 +++++------ .../jhipster/online/service/JdlService.java | 1 - .../online/service/StatisticsService.java | 8 +- .../jhipster/online/service/YoRCService.java | 12 +-- .../online/web/rest/CiCdResource.java | 2 +- .../jhipster/online/web/rest/GitResource.java | 63 +++++++------ .../home/jdl-metadata/jdl-metadata.service.ts | 3 +- .../app/shared/alert/alert-error.component.ts | 90 +++++++++---------- 13 files changed, 124 insertions(+), 128 deletions(-) diff --git a/sonar-project.properties b/sonar-project.properties index 3195b6b5..58658e43 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -15,6 +15,10 @@ sonar.typescript.lcov.reportPaths=target/test-results/lcov.info sonar.sourceEncoding=UTF-8 sonar.exclusions=src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/classes/static/**/*.* +sonar.cpd.exclusions=src/**/domain/**/*.*, src/**/dto/**/*.* +sonar.test.exclusions=src/test/java/**/*.* +sonar.coverage.exclusions=**src/test/**/*.* + sonar.issue.ignore.multicriteria=S3437,S4502,S4684,UndocumentedApi,BoldAndItalicTagsCheck # Rule https://sonarcloud.io/coding_rules?open=squid%3AS3437&rule_key=squid%3AS3437 is ignored, as a JPA-managed field cannot be transient sonar.issue.ignore.multicriteria.S3437.resourceKey=src/main/java/**/* diff --git a/src/main/java/io/github/jhipster/online/config/LiquibaseConfiguration.java b/src/main/java/io/github/jhipster/online/config/LiquibaseConfiguration.java index 9a21d375..dcf9a6a6 100644 --- a/src/main/java/io/github/jhipster/online/config/LiquibaseConfiguration.java +++ b/src/main/java/io/github/jhipster/online/config/LiquibaseConfiguration.java @@ -55,8 +55,8 @@ public SpringLiquibase liquibase( ObjectProvider dataSource, DataSourceProperties dataSourceProperties ) { - // If you don't want Liquibase to start asynchronously, substitute by this: - // SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties); + // If you don't want Liquibase to start asynchronously, substitute by this: //NOSONAR + // SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties); //NOSONAR SpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase( this.env, executor, diff --git a/src/main/java/io/github/jhipster/online/service/CiCdService.java b/src/main/java/io/github/jhipster/online/service/CiCdService.java index 9fd7e6e8..dd088a2e 100644 --- a/src/main/java/io/github/jhipster/online/service/CiCdService.java +++ b/src/main/java/io/github/jhipster/online/service/CiCdService.java @@ -93,7 +93,6 @@ public void configureCiCd( this.gitService.createBranch(git, branchName); this.logsService.addLog(ciCdId, "Generating Continuous Integration configuration"); - //this.jHipsterService.installNpmDependencies(ciCdId, workingDir); this.jHipsterService.addCiCd(ciCdId, workingDir, ciCdTool); this.gitService.addAllFilesToRepository(git, workingDir); diff --git a/src/main/java/io/github/jhipster/online/service/GeneratorService.java b/src/main/java/io/github/jhipster/online/service/GeneratorService.java index f7d754bf..54707ff6 100644 --- a/src/main/java/io/github/jhipster/online/service/GeneratorService.java +++ b/src/main/java/io/github/jhipster/online/service/GeneratorService.java @@ -109,12 +109,10 @@ private File generateApplication(String applicationId, String applicationConfigu private void generateYoRc(String applicationId, File workingDir, String applicationConfiguration) throws IOException { this.logsService.addLog(applicationId, "Creating `.yo-rc.json` file"); - try (PrintWriter writer = new PrintWriter(workingDir + "/.yo-rc.json", StandardCharsets.UTF_8)) { - writer.print(applicationConfiguration); - } catch (IOException ioe) { - log.error("Error creating file .yo-rc.json", ioe); - throw ioe; - } + // removed the catch/log/throw since the exception is handled in calling code. + PrintWriter writer = new PrintWriter(workingDir + "/.yo-rc.json", StandardCharsets.UTF_8); + writer.print(applicationConfiguration); + writer.close(); } private void zipResult(File workingDir) { diff --git a/src/main/java/io/github/jhipster/online/service/GitService.java b/src/main/java/io/github/jhipster/online/service/GitService.java index c80360a1..f413715e 100644 --- a/src/main/java/io/github/jhipster/online/service/GitService.java +++ b/src/main/java/io/github/jhipster/online/service/GitService.java @@ -71,7 +71,7 @@ public void pushNewApplicationToGit(User user, File workingDir, String organizat remoteAddCommand.call(); String currentBranch = git.getRepository().getFullBranch(); - if (currentBranch.equals("refs/heads/master")) { + if ("refs/heads/master".equals(currentBranch)) { git.branchRename().setNewName("main").call(); } this.push(git, workingDir, user, organization, applicationName, gitProvider); diff --git a/src/main/java/io/github/jhipster/online/service/JHipsterService.java b/src/main/java/io/github/jhipster/online/service/JHipsterService.java index ba7124f0..80f15303 100644 --- a/src/main/java/io/github/jhipster/online/service/JHipsterService.java +++ b/src/main/java/io/github/jhipster/online/service/JHipsterService.java @@ -109,40 +109,30 @@ public void addCiCd(String generationId, File workingDir, CiCdTool ciCdTool) thr void runProcess(String generationId, File workingDir, String... command) throws IOException { log.info("Running command: \"{}\" in directory: \"{}\"", command, workingDir); - BufferedReader input = null; - try { - String line; - ProcessBuilder processBuilder = new ProcessBuilder() - .directory(workingDir) - .command(command) - .redirectError(ProcessBuilder.Redirect.DISCARD); - Process p = processBuilder.start(); - - taskExecutor.execute( - () -> { - try { - p.waitFor(timeout, TimeUnit.SECONDS); - p.destroyForcibly(); - } catch (InterruptedException e) { - log.error("Unable to execute process successfully.", e); - Thread.currentThread().interrupt(); - } + ProcessBuilder processBuilder = new ProcessBuilder() + .directory(workingDir) + .command(command) + .redirectError(ProcessBuilder.Redirect.DISCARD); + Process p = processBuilder.start(); + + taskExecutor.execute( + () -> { + try { + p.waitFor(timeout, TimeUnit.SECONDS); + p.destroyForcibly(); + } catch (InterruptedException e) { + log.error("Unable to execute process successfully.", e); + Thread.currentThread().interrupt(); } - ); - - input = new BufferedReader(new InputStreamReader(p.getInputStream())); - while ((line = input.readLine()) != null) { - log.debug(line); - this.logsService.addLog(generationId, line); } + ); - input.close(); - } catch (Exception e) { - log.error("Error while running the process", e); - if (input != null) { - input.close(); - } - throw e; + BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); + String line; + while ((line = input.readLine()) != null) { + log.debug(line); + this.logsService.addLog(generationId, line); } + input.close(); } } diff --git a/src/main/java/io/github/jhipster/online/service/JdlService.java b/src/main/java/io/github/jhipster/online/service/JdlService.java index 0a178eb2..0c074c3a 100644 --- a/src/main/java/io/github/jhipster/online/service/JdlService.java +++ b/src/main/java/io/github/jhipster/online/service/JdlService.java @@ -120,7 +120,6 @@ public void applyJdl( ); this.logsService.addLog(applyJdlId, "Generating entities from JDL Model"); - //this.jHipsterService.installNpmDependencies(applyJdlId, workingDir); this.jHipsterService.runImportJdl(applyJdlId, workingDir, this.kebabCaseJdlName(jdlMetadata)); this.gitService.addAllFilesToRepository(git, workingDir); diff --git a/src/main/java/io/github/jhipster/online/service/StatisticsService.java b/src/main/java/io/github/jhipster/online/service/StatisticsService.java index a3c87290..4a5010e7 100644 --- a/src/main/java/io/github/jhipster/online/service/StatisticsService.java +++ b/src/main/java/io/github/jhipster/online/service/StatisticsService.java @@ -43,6 +43,8 @@ public class StatisticsService { private final Logger log = LoggerFactory.getLogger(StatisticsService.class); + public static final String GENERATOR_IDENTITY_WAS_NOT_CORRECTLY_CREATED = "GeneratorIdentity {} was not correctly created"; + private final YoRCService yoRCService; private final GeneratorIdentityService generatorIdentityService; @@ -118,7 +120,7 @@ public void addEntry(String entry, String host) throws IOException { generatorIdentity.get().host(host); yorc.owner(generatorIdentity.get()); } else { - log.info("GeneratorIdentity {} was not correctly created", generatorGuid); + log.info(GENERATOR_IDENTITY_WAS_NOT_CORRECTLY_CREATED, generatorGuid); } yoRCService.save(yoRCMapper.toDto(yorc)); @@ -138,7 +140,7 @@ public void addSubGenEvent(SubGenEventDTO subGenEventDTO, String generatorGuid) if (generatorIdentity.isPresent()) { subGenEvent.owner(generatorIdentity.get()); } else { - log.info("GeneratorIdentity {} was not correctly created", generatorGuid); + log.info(GENERATOR_IDENTITY_WAS_NOT_CORRECTLY_CREATED, generatorGuid); } subGenEventService.save(subGenEventMapper.toDto(subGenEvent)); } @@ -157,7 +159,7 @@ public void addEntityStats(EntityStatsDTO entityStatsDTO, String generatorGuid) if (generatorIdentity.isPresent()) { entityStats.owner(generatorIdentity.get()); } else { - log.info("GeneratorIdentity {} was not correctly created", generatorGuid); + log.info(GENERATOR_IDENTITY_WAS_NOT_CORRECTLY_CREATED, generatorGuid); } entityStatsService.save(entityStatsMapper.toDto(entityStats)); } diff --git a/src/main/java/io/github/jhipster/online/service/YoRCService.java b/src/main/java/io/github/jhipster/online/service/YoRCService.java index f47fd5a0..6e6f0c2e 100644 --- a/src/main/java/io/github/jhipster/online/service/YoRCService.java +++ b/src/main/java/io/github/jhipster/online/service/YoRCService.java @@ -133,13 +133,13 @@ public void save(String applicationConfiguration) { JsonNode jsonNodeRoot = mapper.readTree(applicationConfiguration); JsonNode jsonNodeGeneratorJHipster = jsonNodeRoot.get("generator-jhipster"); YoRCDTO yorc = mapper.treeToValue(jsonNodeGeneratorJHipster, YoRCDTO.class); - - // TODO: do something about apps that are generated by jhonline - // -> Optout settings - // -> What should be the guid for such case ? - // yorc.setOwner( ### ); + /** + * TODO: do something about apps that are generated by jhonline + * -> Optout settings + * -> What should be the guid for such case ? + * yorc.setOwner( ### ); + */ save(yorc); - log.debug("Parsed json:\n{}", yorc); } catch (IOException e) { log.error("Generation failed", e); diff --git a/src/main/java/io/github/jhipster/online/web/rest/CiCdResource.java b/src/main/java/io/github/jhipster/online/web/rest/CiCdResource.java index 21c78fd7..2d5c633d 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/CiCdResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/CiCdResource.java @@ -66,7 +66,7 @@ public ResponseEntity configureCiCd( organizationName = SanitizeInputs.sanitizeInput(organizationName); ciCdTool = SanitizeInputs.sanitizeInput(ciCdTool); boolean isGitHub = gitProvider.equalsIgnoreCase("github"); - log.info("Configuring CI: {} on " + (isGitHub ? "GitHub" : "GitLab") + " {}/{}", ciCdTool, organizationName, projectName); + log.info("Configuring CI: {} on {} {}/{}", ciCdTool, (isGitHub ? "GitHub" : "GitLab"), organizationName, projectName); User user = userService.getUser(); String ciCdId = "ci-" + System.nanoTime(); diff --git a/src/main/java/io/github/jhipster/online/web/rest/GitResource.java b/src/main/java/io/github/jhipster/online/web/rest/GitResource.java index c0c3aef6..d16360fe 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/GitResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/GitResource.java @@ -109,7 +109,8 @@ public RedirectView callback(@PathVariable String gitProvider, String code) { */ @PostMapping("/{gitProvider}/save-token") @Secured(AuthoritiesConstants.USER) - public @ResponseBody ResponseEntity saveToken(@PathVariable String gitProvider, @RequestBody String code) { + public @ResponseBody ResponseEntity saveToken(@PathVariable String gitProvider, @RequestBody String code) + throws InterruptedException { try { String url; GitProvider gitProviderEnum; @@ -118,17 +119,17 @@ public RedirectView callback(@PathVariable String gitProvider, String code) { case GITHUB: url = applicationProperties.getGithub().getHost() + "/login/oauth/access_token"; gitProviderEnum = GitProvider.GITHUB; - request.setClient_id(applicationProperties.getGithub().getClientId()); - request.setClient_secret(applicationProperties.getGithub().getClientSecret()); + request.setClientId(applicationProperties.getGithub().getClientId()); + request.setClientSecret(applicationProperties.getGithub().getClientSecret()); request.setCode(code); break; case GITLAB: url = applicationProperties.getGitlab().getHost() + "/oauth/token"; gitProviderEnum = GitProvider.GITLAB; - request.setClient_id(applicationProperties.getGitlab().getClientId()); - request.setClient_secret(applicationProperties.getGitlab().getClientSecret()); - request.setGrant_type("authorization_code"); - request.setRedirect_uri(applicationProperties.getGitlab().getRedirectUri()); + request.setClientId(applicationProperties.getGitlab().getClientId()); + request.setClientSecret(applicationProperties.getGitlab().getClientSecret()); + request.setGrantType("authorization_code"); + request.setRedirectUri(applicationProperties.getGitlab().getRedirectUri()); request.setCode(code); break; default: @@ -151,7 +152,11 @@ public RedirectView callback(@PathVariable String gitProvider, String code) { String jsonResponse = response.thenApply(HttpResponse::body).get(5, TimeUnit.SECONDS); GitAccessTokenResponse accessTokenResponse = objectMapper.readValue(jsonResponse, GitAccessTokenResponse.class); - this.userService.saveToken(accessTokenResponse.getAccess_token(), gitProviderEnum); + this.userService.saveToken(accessTokenResponse.getAccessToken(), gitProviderEnum); + } catch (InterruptedException e) { + log.warn("Interrupted!", e); + // Restore interrupted state... + Thread.currentThread().interrupt(); } catch (Exception e) { log.error("OAuth2 token could not saved: ", e); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); @@ -161,9 +166,9 @@ public RedirectView callback(@PathVariable String gitProvider, String code) { public static class GitAccessTokenRequest { - private String client_id; + private String clientId; - private String client_secret; + private String clientSecret; private String code; @@ -171,20 +176,20 @@ public static class GitAccessTokenRequest { private String redirectUri; - public String getClient_id() { - return client_id; + public String getClientId() { + return clientId; } - public void setClient_id(String client_id) { - this.client_id = client_id; + public void setClientId(String clientId) { + this.clientId = clientId; } - public String getClient_secret() { - return client_secret; + public String getClientSecret() { + return clientSecret; } - public void setClient_secret(String client_secret) { - this.client_secret = client_secret; + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; } public String getCode() { @@ -195,19 +200,19 @@ public void setCode(String code) { this.code = code; } - public String getGrant_type() { + public String getGrantType() { return grantType; } - public void setGrant_type(String grantType) { + public void setGrantType(String grantType) { this.grantType = grantType; } - public String getRedirect_uri() { + public String getRedirectUri() { return redirectUri; } - public void setRedirect_uri(String redirectUri) { + public void setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; } @@ -216,10 +221,10 @@ public String toString() { return ( "GitAccessTokenRequest{" + "client_id='" + - client_id + + clientId + '\'' + ", client_secret='" + - client_secret + + clientSecret + '\'' + ", code='" + code + @@ -238,14 +243,14 @@ public String toString() { @JsonIgnoreProperties(ignoreUnknown = true) public static class GitAccessTokenResponse { - private String access_token; + private String accessToken; - public String getAccess_token() { - return access_token; + public String getAccessToken() { + return accessToken; } - public void setAccess_token(String access_token) { - this.access_token = access_token; + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; } } diff --git a/src/main/webapp/app/home/jdl-metadata/jdl-metadata.service.ts b/src/main/webapp/app/home/jdl-metadata/jdl-metadata.service.ts index 3516329f..2030edc7 100644 --- a/src/main/webapp/app/home/jdl-metadata/jdl-metadata.service.ts +++ b/src/main/webapp/app/home/jdl-metadata/jdl-metadata.service.ts @@ -51,7 +51,6 @@ export class JdlMetadataService { } private convert(jdlMetadata: JdlMetadata): JdlMetadata { - const copy: JdlMetadata = Object.assign({}, jdlMetadata); - return copy; + return Object.assign({}, jdlMetadata); } } diff --git a/src/main/webapp/app/shared/alert/alert-error.component.ts b/src/main/webapp/app/shared/alert/alert-error.component.ts index 09713323..27003e03 100644 --- a/src/main/webapp/app/shared/alert/alert-error.component.ts +++ b/src/main/webapp/app/shared/alert/alert-error.component.ts @@ -39,8 +39,46 @@ export class AlertErrorComponent implements OnDestroy { alerts: JhiAlert[] = []; errorListener: Subscription; httpErrorListener: Subscription; + caseMap: Map; constructor(private alertService: JhiAlertService, private eventManager: JhiEventManager) { + this.caseMap = new Map(); + /* eslint-disable */ + this.caseMap.set(0, (context: AlertErrorComponent, httpErrorResponse: HttpErrorResponse) => { + context.addErrorAlert('Server not reachable'); + }); + this.caseMap.set(404, (context: AlertErrorComponent, httpErrorResponse: HttpErrorResponse) => { + context.addErrorAlert('Not found'); + }); + /* eslint-enable */ + this.caseMap.set(400, (context: AlertErrorComponent, httpErrorResponse: HttpErrorResponse) => { + const arr = httpErrorResponse.headers.keys(); + let errorHeader = null; + arr.forEach(entry => { + if (entry.toLowerCase().endsWith('app-error')) { + errorHeader = httpErrorResponse.headers.get(entry); + } + }); + if (errorHeader) { + this.addErrorAlert(errorHeader); + } else if (httpErrorResponse.error !== '' && httpErrorResponse.error.fieldErrors) { + const fieldErrors = httpErrorResponse.error.fieldErrors; + for (const fieldError of fieldErrors) { + if (['Min', 'Max', 'DecimalMin', 'DecimalMax'].includes(fieldError.message)) { + fieldError.message = 'Size'; + } + // convert 'something[14].other[4].id' to 'something[].other[].id' so translations can be written to it + const convertedField = fieldError.field.replace(/\[\d*\]/g, '[]'); + const fieldName = convertedField.charAt(0).toUpperCase() + convertedField.slice(1); + this.addErrorAlert('Error on field "' + fieldName + '"'); + } + } else if (httpErrorResponse.error !== '' && httpErrorResponse.error.message) { + this.addErrorAlert(httpErrorResponse.error.message); + } else { + this.addErrorAlert(httpErrorResponse.error); + } + }); + this.errorListener = eventManager.subscribe('jhonlineApp.error', (response: JhiEventWithContent) => { const errorResponse = response.content; this.addErrorAlert(errorResponse.message); @@ -48,51 +86,13 @@ export class AlertErrorComponent implements OnDestroy { this.httpErrorListener = eventManager.subscribe('jhonlineApp.httpError', (response: JhiEventWithContent) => { const httpErrorResponse = response.content; - switch (httpErrorResponse.status) { - // connection refused, server not reachable - case 0: - this.addErrorAlert('Server not reachable'); - break; - - case 400: { - const arr = httpErrorResponse.headers.keys(); - let errorHeader = null; - arr.forEach(entry => { - if (entry.toLowerCase().endsWith('app-error')) { - errorHeader = httpErrorResponse.headers.get(entry); - } - }); - if (errorHeader) { - this.addErrorAlert(errorHeader); - } else if (httpErrorResponse.error !== '' && httpErrorResponse.error.fieldErrors) { - const fieldErrors = httpErrorResponse.error.fieldErrors; - for (const fieldError of fieldErrors) { - if (['Min', 'Max', 'DecimalMin', 'DecimalMax'].includes(fieldError.message)) { - fieldError.message = 'Size'; - } - // convert 'something[14].other[4].id' to 'something[].other[].id' so translations can be written to it - const convertedField = fieldError.field.replace(/\[\d*\]/g, '[]'); - const fieldName = convertedField.charAt(0).toUpperCase() + convertedField.slice(1); - this.addErrorAlert('Error on field "' + fieldName + '"'); - } - } else if (httpErrorResponse.error !== '' && httpErrorResponse.error.message) { - this.addErrorAlert(httpErrorResponse.error.message); - } else { - this.addErrorAlert(httpErrorResponse.error); - } - break; - } - - case 404: - this.addErrorAlert('Not found'); - break; - - default: - if (httpErrorResponse.error !== '' && httpErrorResponse.error.message) { - this.addErrorAlert(httpErrorResponse.error.message); - } else { - this.addErrorAlert(httpErrorResponse.error); - } + const lambda = this.caseMap.get(httpErrorResponse.status); + if (lambda) { + lambda(this, httpErrorResponse); + } else if (httpErrorResponse.error !== '' && httpErrorResponse.error.message) { + this.addErrorAlert(httpErrorResponse.error.message); + } else { + this.addErrorAlert(httpErrorResponse.error); } }); }