diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..4cab1f4d26 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Set the default behavior, in case people don't have core.autocrlf set. +* text=auto diff --git a/README.md b/README.md index f3426e2f27..ace2e7a244 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -* nGrinder 3.5.2 has been released. See https://github.com/naver/ngrinder/releases +* nGrinder 3.5.3 has been released. See https://github.com/naver/ngrinder/releases nGrinder ======== diff --git a/RELEASE-NOTE.md b/RELEASE-NOTE.md index 415fb70f28..7d0ebe6b50 100644 --- a/RELEASE-NOTE.md +++ b/RELEASE-NOTE.md @@ -1,3 +1,24 @@ +3.5.3 (2020.11.27) +================== +- Changes + - Support gradle groovy script + * Maven groovy script is deprecated and can't create any more but, it can still run + - Use maven central repository to manage submodules + * Use maven central repository instead of github repository + - Support UTC + * Use linux timestamp instead of string format of date time. +- Trivial Fix + - Make several UI improvements + - Add identity information to perftest related log + - Make the H2 console optionally available + - Clean up code +- Bug fix + - #669 Prevent lazy initialize exception in spring security authentication object + - #672 Make the modified file distribution handler to be loaded first + - #681 Prevent NPE if start console is failed + - #682 Escape response body in result console + - #684 Fix unstoppable abnormal test + 3.5.2 (2020.09.29) ================== - Changes diff --git a/build.gradle b/build.gradle index 28a4f3a73d..0a93d11f2c 100644 --- a/build.gradle +++ b/build.gradle @@ -1,8 +1,12 @@ +plugins { + id "com.jfrog.bintray" version "1.8.5" +} + allprojects { apply plugin: "idea" group = "org.ngrinder" - version = "3.5.2" + version = "3.5.3" idea { module { @@ -21,6 +25,7 @@ allprojects { subprojects { apply plugin: "java" apply plugin: "maven-publish" + apply plugin: "com.jfrog.bintray" compileJava.options.encoding = "UTF-8" compileTestJava.options.encoding = "UTF-8" @@ -29,7 +34,7 @@ subprojects { targetCompatibility = 1.8 ext { - profile = project.hasProperty('profile') ? profile : 'production' + profile = project.hasProperty("profile") ? profile : "production" slf4j_version = "1.7.28" spring_security_version = "5.3.4.RELEASE" spring_boot_version = "2.3.3.RELEASE" @@ -68,12 +73,60 @@ subprojects { from components.java artifact sourceJar artifact javadocJar + pom { + name = "org.ngrinder:${project.name}" + description = "${project.name} module" + url = "https://github.com/naver/ngrinder" + licenses { + license { + name = "The Apache License, Version 2.0" + url = "http://www.apache.org/licenses/LICENSE-2.0.txt" + } + } +// Below field is required to publish to the Maven central. Please modify before publishing. +// developers { +// developer { +// id = "{please_input_your_id}" +// name = "{please_input_your_name}" +// email = "{please_input_your_email}" +// } +// } + scm { + connection = "scm:git:git://github.com/naver/ngrinder.git" + developerConnection = "scm:git:ssh://github.com/naver/ngrinder.git" + url = "https://github.com/naver/ngrinder" + } + } } } - repositories { - maven { - url = "file:../../ngrinder.maven.repo/releases/" + } + + bintray { + user = project.hasProperty("bintrayUser") ? bintrayUser : "" + key = project.hasProperty("bintrayKey") ? bintrayKey : "" + publications = ["nGrinerModules"] + publish = true + override = true + + pkg { + repo = "ngrinder" + name = project.name + userOrg = "navercorp" + licenses = ["Apache-2.0"] + websiteUrl = "https://github.com/naver/ngrinder" + issueTrackerUrl = "https://github.com/naver/ngrinder/issues" + vcsUrl = "https://github.com/naver/ngrinder.git" + labels = ["ngrinder"] + publicDownloadNumbers = true + version { + name = project.version + released = new Date() + gpg { + sign = true + passphrase = project.hasProperty("bintrayGpgPassphrase") ? bintrayGpgPassphrase : "" + } } } } + } diff --git a/docker/controller/Dockerfile b/docker/controller/Dockerfile index f1cc4de4df..7543c487f6 100644 --- a/docker/controller/Dockerfile +++ b/docker/controller/Dockerfile @@ -1,11 +1,37 @@ FROM jeanblanchard/java:serverjre-8 MAINTAINER JunHo Yoon "junoyoon@gmail.com" -RUN apk update; apk add curl bash +RUN apk update; apk add curl bash tar + +ARG MAVEN_VERSION=3.6.3 +ARG MAVEN_DOWNLOAD_BASE_URL=https://apache.osuosl.org/maven/maven-3/${MAVEN_VERSION}/binaries + +ARG GRADLE_VERSION=6.7.1 +ARG GRADLE_DOWNLOAD_BASE_URL=https://services.gradle.org/distributions + +# Install maven +RUN mkdir -p /usr/share/maven \ + && echo "Downloading maven" \ + && curl -fsSL -o /tmp/apache-maven.tar.gz ${MAVEN_DOWNLOAD_BASE_URL}/apache-maven-${MAVEN_VERSION}-bin.tar.gz \ + && echo "Unziping maven" \ + && tar -xzf /tmp/apache-maven.tar.gz -C /usr/share/maven --strip-components=1 \ + && rm -f /tmp/apache-maven.tar.gz + +# Install gradle +RUN mkdir -p /usr/share/gradle \ + && echo "Downloading gradle" \ + && curl -fsSL -o /tmp/gradle.zip ${GRADLE_DOWNLOAD_BASE_URL}/gradle-${GRADLE_VERSION}-bin.zip \ + && echo "Unziping gradle" \ + && unzip -d /usr/share/gradle /tmp/gradle.zip \ + && rm -f /tmp/gradle.zip # Set up environment variables ENV BASE_DIR=/opt \ - NGRINDER_HOME=/opt/ngrinder-controller + NGRINDER_HOME=/opt/ngrinder-controller \ + MAVEN_HOME=/usr/share/maven \ + GRADLE_HOME=/usr/share/gradle/gradle-${GRADLE_VERSION} + +ENV PATH=$PATH:$GRADLE_HOME/bin:$MAVEN_HOME/bin # Expose ports EXPOSE 80 16001 12000-12009 diff --git a/docker/controller/scripts/run.sh b/docker/controller/scripts/run.sh index 63b8ad6a7e..1854f0a443 100755 --- a/docker/controller/scripts/run.sh +++ b/docker/controller/scripts/run.sh @@ -1,3 +1,7 @@ #!/usr/bin/env bash -echo "wait a while extracting war files... It takes time for the first run." +echo "Installed build tools." +mvn -version +gradle -version + +echo "Wait a while extracting war files... It takes time for the first run." java -jar ${BASE_DIR}/ngrinder-*.war --port 80 diff --git a/docker/prepare.sh b/docker/prepare.sh index b96f96616f..2ba3c37db6 100755 --- a/docker/prepare.sh +++ b/docker/prepare.sh @@ -2,4 +2,4 @@ echo "copying ngrinder-controller" mkdir -p controller/binary rm controller/binary/ngrinder* -cp ../ngrinder-controller/target/*.war controller/binary/ +cp ../ngrinder-controller/build/libs/*.war controller/binary/ diff --git a/ngrinder-controller/build.gradle b/ngrinder-controller/build.gradle index 6717b58464..16d88f1076 100644 --- a/ngrinder-controller/build.gradle +++ b/ngrinder-controller/build.gradle @@ -45,14 +45,6 @@ dependencies { compile (group: "org.python", name: "jython-standalone", version: "2.5.3") compile (group: "com.google.guava", name: "guava", version: "20.0") compile (group: "org.springframework.security", name: "spring-security-taglibs", version: spring_security_version) - - compile (group: "org.apache.maven", name: "maven-embedder", version: "3.6.3") - compile (group: "org.apache.maven", name: "maven-compat", version: "3.6.3") - compile (group: "org.eclipse.aether", name: "aether-connector-basic", version: "1.1.0") - compile (group: "org.eclipse.aether", name: "aether-transport-wagon", version: "1.1.0") - compile (group: "org.apache.maven.wagon", name: "wagon-http", version: "2.8") - compile (group: "org.apache.maven.wagon", name: "wagon-provider-api", version: "2.8") - compile (group: "org.liquibase", name: "liquibase-core", version: "3.5.3") compile (group: "org.hibernate", name: "hibernate-jcache", version: hibernate_version) compile (group: "com.github.ben-manes.caffeine", name: "caffeine", version: "2.6.2") @@ -75,17 +67,17 @@ dependencies { compile (group: "com.hazelcast", name: "hazelcast-spring", version: hazelcast_version) compile (group: "org.kohsuke", name: "github-api", version: "1.99") compile (group: "commons-validator", name: "commons-validator", version: "1.6") - compile (group: 'org.codehaus.groovy', name: 'groovy-jsr223', version: groovy_version) - compile group: 'com.unboundid', name: 'unboundid-ldapsdk', version: '5.1.1' + compile (group: "org.codehaus.groovy", name: "groovy-jsr223", version: groovy_version) + compile (group: "com.unboundid", name: "unboundid-ldapsdk", version: "5.1.1") compileOnly (group: "org.projectlombok", name: "lombok", version: "1.18.8") annotationProcessor (group: "org.projectlombok", name: "lombok", version: "1.18.8") - providedRuntime (group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat', version: spring_boot_version) + providedRuntime (group: "org.springframework.boot", name: "spring-boot-starter-tomcat", version: spring_boot_version) - testCompile (group: 'junit', name: 'junit', version: '4.13') + testCompile (group: "junit", name: "junit", version: "4.13") testCompile (group: "org.easytesting", name: "fest-assert", version: "1.4") - testCompile (group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: spring_boot_version) + testCompile (group: "org.springframework.boot", name: "spring-boot-starter-test", version: spring_boot_version) testCompileOnly (group: "org.projectlombok", name: "lombok", version: "1.18.8") testAnnotationProcessor (group: "org.projectlombok", name: "lombok", version: "1.18.8") diff --git a/ngrinder-core/src/main/java/net/grinder/console/distribution/FileDistributionHandlerImplementation.java b/ngrinder-controller/src/main/java/net/grinder/console/distribution/FileDistributionHandlerImplementation.java similarity index 100% rename from ngrinder-core/src/main/java/net/grinder/console/distribution/FileDistributionHandlerImplementation.java rename to ngrinder-controller/src/main/java/net/grinder/console/distribution/FileDistributionHandlerImplementation.java diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentDownloadController.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentDownloadController.java index 3150455b4b..4f4739b75d 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentDownloadController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentDownloadController.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.agent.controller; @@ -57,7 +57,7 @@ public class AgentDownloadController { * @param fileName file path of agent * @param response response. */ - @GetMapping("/{fileName:[a-zA-Z0-9\\.\\-_]+}") + @GetMapping("/{fileName:[a-zA-Z0-9.\\-_]+}") public void download(@PathVariable String fileName, HttpServletResponse response) { File home = config.getHome().getDownloadDirectory(); File ngrinderFile = new File(home, fileName); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerApiController.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerApiController.java index 14cd20cec9..0298ff68b1 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerApiController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerApiController.java @@ -40,6 +40,7 @@ /** * @since 3.5.0 */ +@SuppressWarnings("unused") @RestController @RequestMapping("/agent/api") @PreAuthorize("hasAnyRole('A', 'S')") diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerController.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerController.java index 682029fe89..2596776c36 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerController.java @@ -26,6 +26,7 @@ * * @since 3.1 */ +@SuppressWarnings("unused") @Controller @RequestMapping("/agent") @GlobalControllerModel diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/MonitorDownloadController.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/MonitorDownloadController.java index e7220eb947..a456a9d3ea 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/MonitorDownloadController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/MonitorDownloadController.java @@ -53,8 +53,7 @@ public class MonitorDownloadController { * @param fileName monitor file name. * @param response response. */ - - @GetMapping("/{fileName:[a-zA-Z0-9\\.\\-_]+}") + @GetMapping("/{fileName:[a-zA-Z0-9.\\-_]+}") public void download(@PathVariable String fileName, HttpServletResponse response) { File home = config.getHome().getDownloadDirectory(); File monitorFile = new File(home, fileName); @@ -64,6 +63,7 @@ public void download(@PathVariable String fileName, HttpServletResponse response /** * Download monitor. */ + @SuppressWarnings("SpringMVCViewInspection") @GetMapping("") public String download(ModelMap model) { try { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/MonitorManagerApiController.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/MonitorManagerApiController.java index 82acb56385..02fc923d4f 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/MonitorManagerApiController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/MonitorManagerApiController.java @@ -68,7 +68,7 @@ public Future getAsyncSystemInfo(String ip, int port) { * Close the monitor JXM connection to the given target. * * @param ip target host IP - * @return success if succeeded. + * */ @GetMapping("/close") public void closeMonitorConnection(@RequestParam String ip) { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/model/Connection.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/model/Connection.java index 4c98dd72c7..761e3fa75c 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/agent/model/Connection.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/model/Connection.java @@ -6,6 +6,7 @@ import javax.persistence.Entity; import javax.persistence.Table; +@SuppressWarnings("JpaDataSourceORMInspection") @Getter @Setter @ToString diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/repository/AgentManagerSpecification.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/repository/AgentManagerSpecification.java index 9227146cad..bf2628dfd8 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/agent/repository/AgentManagerSpecification.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/repository/AgentManagerSpecification.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,15 +9,13 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.agent.repository; import org.ngrinder.model.AgentInfo; import org.springframework.data.jpa.domain.Specification; -import javax.persistence.criteria.*; - /** * Agent Manager JPA Specification. * @@ -34,5 +32,5 @@ public abstract class AgentManagerSpecification { public static Specification idEqual(final Long id) { return (Specification) (root, query, cb) -> cb.equal(root.get("id"), id); } - + } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentPackageService.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentPackageService.java index 1488f34ede..936ddf0a88 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentPackageService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentPackageService.java @@ -2,7 +2,6 @@ import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.FilenameUtils; import org.ngrinder.infra.config.Config; import org.ngrinder.packages.AgentPackageHandler; import org.ngrinder.packages.PackageHandler; @@ -14,13 +13,10 @@ import java.net.URL; import java.net.URLClassLoader; import java.util.Set; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; import lombok.RequiredArgsConstructor; import static org.apache.commons.lang.StringUtils.isNotEmpty; -import static org.ngrinder.common.util.CompressionUtils.*; import static org.ngrinder.common.util.EncodingUtils.decodePathWithUTF8; import static org.ngrinder.common.util.StringUtils.replaceLast; @@ -137,30 +133,4 @@ protected boolean isDependentLib(File libFile, Set libs) { name = name.substring(0, (libVersionStartIndex == -1) ? name.lastIndexOf(".") : libVersionStartIndex); return libs.contains(name); } - - static class TarArchivingZipEntryProcessor implements ZipEntryProcessor { - private TarArchiveOutputStream tao; - private FilePredicate filePredicate; - private String basePath; - private int mode; - - TarArchivingZipEntryProcessor(TarArchiveOutputStream tao, FilePredicate filePredicate, String basePath, int mode) { - this.tao = tao; - this.filePredicate = filePredicate; - this.basePath = basePath; - this.mode = mode; - } - - @Override - public void process(ZipFile file, ZipEntry entry) throws IOException { - try (InputStream inputStream = file.getInputStream(entry)) { - if (filePredicate.evaluate(entry)) { - addInputStreamToTar(this.tao, inputStream, basePath + FilenameUtils.getName(entry.getName()), - entry.getSize(), - this.mode); - } - } - } - } - } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentService.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentService.java index b91e723bd5..07a75ab63a 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentService.java @@ -40,6 +40,7 @@ import org.ngrinder.infra.hazelcast.topic.subscriber.TopicSubscriber; import org.ngrinder.infra.schedule.ScheduledTaskService; import org.ngrinder.model.AgentInfo; +import org.ngrinder.model.PerfTest; import org.ngrinder.model.User; import org.ngrinder.monitor.controller.model.SystemDataModel; import org.ngrinder.perftest.service.AgentManager; @@ -73,7 +74,7 @@ import static org.ngrinder.common.constant.CacheConstants.*; import static org.ngrinder.common.constant.ControllerConstants.PROP_CONTROLLER_ENABLE_AGENT_AUTO_APPROVAL; import static org.ngrinder.common.util.CollectionUtils.newHashMap; -import static org.ngrinder.common.util.ExceptionUtils.processException; +import static org.ngrinder.common.util.LoggingUtils.format; import static org.ngrinder.common.util.TypeConvertUtils.cast; /** @@ -337,13 +338,14 @@ private boolean isCommonAgent(AgentInfo agentInfo) { /** * Assign the agents on the given console. * - * @param user user - * @param singleConsole {@link SingleConsole} to which agents will be assigned + * @param perfTest current performance test. + * @param singleConsole {@link SingleConsole} to which agents will be assigned. * @param grinderProperties {@link GrinderProperties} to be distributed. * @param agentCount the count of agents. */ - public synchronized void runAgent(User user, final SingleConsole singleConsole, + public synchronized void runAgent(PerfTest perfTest, final SingleConsole singleConsole, final GrinderProperties grinderProperties, final Integer agentCount) { + User user = perfTest.getCreatedBy(); final Set allFreeAgents = getAllAttachedFreeApprovedAgentsForUser(user.getUserId()); final Set necessaryAgents = selectAgent(user, allFreeAgents, agentCount); @@ -357,11 +359,11 @@ public synchronized void runAgent(User user, final SingleConsole singleConsole, "\nPlease restart perftest after few minutes."); } - hazelcastService.put(CACHE_RECENTLY_USED_AGENTS, user.getUserId(), necessaryAgents); + hazelcastService.put(DIST_MAP_NAME_RECENTLY_USED_AGENTS, user.getUserId(), necessaryAgents); - LOGGER.info("{} agents are starting for user {}", agentCount, user.getUserId()); + LOGGER.info(format(perfTest, "{} agents are starting.", agentCount)); for (AgentInfo agentInfo : necessaryAgents) { - LOGGER.info("- Agent {}", agentInfo.getName()); + LOGGER.info(format(perfTest, "- Agent {}", agentInfo.getName())); } agentManager.runAgent(singleConsole, grinderProperties, necessaryAgents); } @@ -386,7 +388,7 @@ private boolean hasOldVersionAgent(Set agentInfos) { * @return selected agents. */ Set selectAgent(User user, Set allFreeAgents, int agentCount) { - Set recentlyUsedAgents = hazelcastService.getOrDefault(CACHE_RECENTLY_USED_AGENTS, user.getUserId(), emptySet()); + Set recentlyUsedAgents = hazelcastService.getOrDefault(DIST_MAP_NAME_RECENTLY_USED_AGENTS, user.getUserId(), emptySet()); Comparator recentlyUsedPriorityComparator = (agent1, agent2) -> { if (recentlyUsedAgents.contains(agent1)) { @@ -525,7 +527,7 @@ public void update(Map model = (BaseModel) object; - Date lastModifiedDate = new Date(); - model.setLastModifiedDate(lastModifiedDate); + Instant lastModifiedAt = now(); + model.setLastModifiedAt(lastModifiedAt); User currentUser = userContext.getCurrentUser(); long currentUserId = currentUser.getId(); - model.setLastModifiedUser(userRepository.findOne(idEqual(currentUserId)) + model.setLastModifiedBy(userRepository.findOne(idEqual(currentUserId)) .orElseThrow(() -> new IllegalArgumentException("No user found with id : " + currentUserId))); - if (!model.exist() || model.getCreatedUser() == null) { + if (!model.exist() || model.getCreatedBy() == null) { long factualUserId = currentUser.getFactualUser().getId(); - model.setCreatedDate(lastModifiedDate); - model.setCreatedUser(userRepository.findOne(idEqual(factualUserId)) + model.setCreatedAt(lastModifiedAt); + model.setCreatedBy(userRepository.findOne(idEqual(factualUserId)) .orElseThrow(() -> new IllegalArgumentException("No user found with id : " + factualUserId))); } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/common/util/EncodingUtils.java b/ngrinder-controller/src/main/java/org/ngrinder/common/util/EncodingUtils.java index 48d0c889e6..3e21405c61 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/common/util/EncodingUtils.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/common/util/EncodingUtils.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; @@ -27,7 +27,7 @@ /** * Automatic encoding detection utility. - * + * * @since 3.0 */ public abstract class EncodingUtils { @@ -36,7 +36,7 @@ public abstract class EncodingUtils { /** * Decode the byte array with auto encoding detection feature. - * + * * @param data * byte array * @param defaultEncoding @@ -51,16 +51,14 @@ public static String getAutoDecodedString(byte[] data, String defaultEncoding) t /** * Detect encoding of given data. - * + * * @param data * byte array * @param defaultEncoding * the default encoding if no encoding is sure. * @return encoding name detected encoding name - * @throws IOException - * occurs when the detection is failed. */ - public static String detectEncoding(byte[] data, String defaultEncoding) throws IOException { + public static String detectEncoding(byte[] data, String defaultEncoding) { CharsetDetector detector = new CharsetDetector(); detector.setText(data); CharsetMatch cm = detector.detect(); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileDownloadUtils.java b/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileDownloadUtils.java index 0dc703448f..5584a1b85d 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileDownloadUtils.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileDownloadUtils.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,28 +9,25 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; import javax.servlet.http.HttpServletResponse; import java.io.*; +import static org.apache.commons.io.IOUtils.copyLarge; + /** * File download utilities. * * @since 3.0 */ +@Slf4j public abstract class FileDownloadUtils { - private static final int FILE_DOWNLOAD_BUFFER_SIZE = 4096; - private static final Logger LOGGER = LoggerFactory.getLogger(FileDownloadUtils.class); - public static final int FILE_CHUNK_BUFFER_SIZE = 1024 * 1024; - /** * Download the given file to the given {@link HttpServletResponse}. * @@ -54,32 +51,24 @@ public static boolean downloadFile(HttpServletResponse response, File file) { if (file == null || !file.exists()) { return false; } + boolean result = true; response.reset(); response.addHeader("Content-Disposition", "attachment;filename=" + file.getName()); response.setContentType("application/octet-stream"); response.addHeader("Content-Length", "" + file.length()); - InputStream fis = null; - byte[] buffer = new byte[FILE_DOWNLOAD_BUFFER_SIZE]; - OutputStream toClient = null; - try { - fis = new BufferedInputStream(new FileInputStream(file)); - toClient = new BufferedOutputStream(response.getOutputStream()); - int readLength; - while (((readLength = fis.read(buffer)) != -1)) { - toClient.write(buffer, 0, readLength); - } - toClient.flush(); + + try (InputStream fis = new BufferedInputStream(new FileInputStream(file)); + OutputStream toClient = new BufferedOutputStream(response.getOutputStream())) { + copyLarge(fis, toClient); } catch (FileNotFoundException e) { - LOGGER.error("file not found:" + file.getAbsolutePath(), e); + log.error("file not found:" + file.getAbsolutePath(), e); result = false; } catch (IOException e) { - LOGGER.error("read file error:" + file.getAbsolutePath(), e); + log.error("read file error:" + file.getAbsolutePath(), e); result = false; - } finally { - IOUtils.closeQuietly(fis); - IOUtils.closeQuietly(toClient); } + return result; } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileUtils.java b/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileUtils.java index 1aff112da9..22f5534f12 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileUtils.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileUtils.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; @@ -18,11 +18,12 @@ import java.io.IOException; import java.io.InputStream; -import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; +import static org.apache.commons.io.IOUtils.copy; + /** * Convenient File utilities. * @@ -39,17 +40,11 @@ public abstract class FileUtils { * @since 3.2 */ public static void copyResourceToFile(String resourcePath, File file) { - InputStream io = null; - FileOutputStream fos = null; - try { - io = new ClassPathResource(resourcePath).getInputStream(); - fos = new FileOutputStream(file); - IOUtils.copy(io, fos); + try (InputStream io = new ClassPathResource(resourcePath).getInputStream(); + FileOutputStream fos = new FileOutputStream(file)) { + copy(io, fos); } catch (IOException e) { LOGGER.error("error while writing {}", resourcePath, e); - } finally { - IOUtils.closeQuietly(io); - IOUtils.closeQuietly(fos); } } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileWatchdog.java b/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileWatchdog.java index e001e56d8f..dba74c0cff 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileWatchdog.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/common/util/FileWatchdog.java @@ -5,9 +5,9 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,7 +25,7 @@ /** * Check every now and then that a certain file has not changed. If it has, then * call the {@link #doOnChange} method. - * + * * @since 3.1.1 */ public abstract class FileWatchdog extends Thread { @@ -38,15 +38,14 @@ public abstract class FileWatchdog extends Thread { /** * The name of the file to observe for changes. */ - private String filename; + private final String filename; + private final File file; /** * The delay to observe between every check. By default set * {@link #DEFAULT_DELAY}. */ private long delay = DEFAULT_DELAY; - - private File file; private long lastModified = 0; private boolean warnedAlready = false; private boolean interrupted = false; @@ -60,7 +59,7 @@ protected FileWatchdog(String filename) { /** * Set the delay to observe between each check of the file changes. - * + * * @param delay * the frequency of file watch. */ @@ -101,6 +100,7 @@ protected void checkAndConfigure() { } } + @SuppressWarnings("BusyWait") @Override public void run() { while (!interrupted && !isInterrupted()) { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/common/util/HttpContainerContext.java b/ngrinder-controller/src/main/java/org/ngrinder/common/util/HttpContainerContext.java index aa12f9e30e..c0a1cdf4e5 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/common/util/HttpContainerContext.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/common/util/HttpContainerContext.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; @@ -21,6 +21,7 @@ import javax.servlet.http.HttpServletRequest; +import static java.util.Objects.requireNonNull; import static org.ngrinder.common.constant.ControllerConstants.PROP_CONTROLLER_URL; import static org.ngrinder.common.util.TypeConvertUtils.cast; @@ -58,7 +59,7 @@ public String getCurrentContextUrlFromUserRequest() { // if empty HttpServletRequest request = cast(RequestContextHolder.currentRequestAttributes().resolveReference("request")); - int serverPort = request.getServerPort(); + int serverPort = requireNonNull(request).getServerPort(); // If it's http default port it will ignore the port part. // However, if ngrinder is provided in HTTPS.. it can be a problem. // FIXME : Later fix above. @@ -74,6 +75,6 @@ public String getCurrentContextUrlFromUserRequest() { public boolean isUnixUser() { SecurityContextHolderAwareRequestWrapper request = cast(RequestContextHolder.currentRequestAttributes() .resolveReference("request")); - return !StringUtils.containsIgnoreCase(request.getHeader("User-Agent"), "Win"); + return !StringUtils.containsIgnoreCase(requireNonNull(request).getHeader("User-Agent"), "Win"); } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/common/util/LoggingUtils.java b/ngrinder-controller/src/main/java/org/ngrinder/common/util/LoggingUtils.java new file mode 100644 index 0000000000..5badc479be --- /dev/null +++ b/ngrinder-controller/src/main/java/org/ngrinder/common/util/LoggingUtils.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2012-present NAVER Corp. + * + * This file is part of The nGrinder software distribution. Refer to + * the file LICENSE which is part of The nGrinder distribution for + * licensing details. The nGrinder distribution is available on the + * Internet at https://naver.github.io/ngrinder + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ngrinder.common.util; + +import org.ngrinder.model.PerfTest; + +import static org.ngrinder.common.util.NoOp.noOp; +import static org.slf4j.helpers.MessageFormatter.arrayFormat; + +public class LoggingUtils { + + public static String format(PerfTest perfTest, String format, Object... params) { + String prefix = ""; + try { + prefix = String.format("[%d][%s] ", perfTest.getId(), perfTest.getCreatedBy().getUserId()); + } catch (RuntimeException e) { + noOp(); + } + return arrayFormat(prefix + format, params).getMessage(); + } +} diff --git a/ngrinder-controller/src/main/java/org/ngrinder/compatibility/perftest/controller/PerfTestFormTypeApiController.java b/ngrinder-controller/src/main/java/org/ngrinder/compatibility/perftest/controller/PerfTestFormTypeApiController.java index 6d0f368336..f83e133b0a 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/compatibility/perftest/controller/PerfTestFormTypeApiController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/compatibility/perftest/controller/PerfTestFormTypeApiController.java @@ -15,7 +15,6 @@ import org.ngrinder.script.service.FileEntryService; import org.ngrinder.user.service.UserContext; import org.ngrinder.user.service.UserService; -import org.springframework.context.MessageSource; import org.springframework.context.annotation.Profile; import org.springframework.web.bind.annotation.*; @@ -35,8 +34,12 @@ @Deprecated public class PerfTestFormTypeApiController extends PerfTestApiController { - public PerfTestFormTypeApiController(PerfTestService perfTestService, TagService tagService, AgentManager agentManager, RegionService regionService, AgentService agentService, FileEntryService fileEntryService, UserService userService, HazelcastService hazelcastService, ScriptHandlerFactory scriptHandlerFactory, UserContext userContext, Config config, MessageSource messageSource) { - super(perfTestService, tagService, agentManager, regionService, agentService, fileEntryService, userService, hazelcastService, scriptHandlerFactory, userContext, config, messageSource); + public PerfTestFormTypeApiController(PerfTestService perfTestService, TagService tagService, AgentManager agentManager, + RegionService regionService, AgentService agentService, FileEntryService fileEntryService, + UserService userService, HazelcastService hazelcastService, ScriptHandlerFactory scriptHandlerFactory, + UserContext userContext, Config config) { + super(perfTestService, tagService, agentManager, regionService, agentService, fileEntryService, + userService, hazelcastService,scriptHandlerFactory, userContext, config); } @PostMapping("/save") diff --git a/ngrinder-controller/src/main/java/org/ngrinder/home/controller/HealthCheckApiController.java b/ngrinder-controller/src/main/java/org/ngrinder/home/controller/HealthCheckApiController.java index 3be7183c87..989eec3557 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/home/controller/HealthCheckApiController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/home/controller/HealthCheckApiController.java @@ -16,7 +16,6 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.ngrinder.common.constant.ControllerConstants; -import org.ngrinder.common.controller.annotation.GlobalControllerModel; import org.ngrinder.common.util.ThreadUtils; import org.ngrinder.infra.config.Config; import org.ngrinder.region.service.RegionService; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/home/controller/HomeController.java b/ngrinder-controller/src/main/java/org/ngrinder/home/controller/HomeController.java index cfee850017..ba959df1bc 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/home/controller/HomeController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/home/controller/HomeController.java @@ -45,6 +45,7 @@ * * @since 3.0 */ +@SuppressWarnings("SpringMVCViewInspection") @Slf4j @Controller @GlobalControllerModel diff --git a/ngrinder-controller/src/main/java/org/ngrinder/home/service/HomeService.java b/ngrinder-controller/src/main/java/org/ngrinder/home/service/HomeService.java index 398999a2df..91bbd97d69 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/home/service/HomeService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/home/service/HomeService.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.home.service; @@ -18,7 +18,6 @@ import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.XmlReader; import lombok.RequiredArgsConstructor; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.ngrinder.home.model.PanelEntry; import org.ngrinder.infra.config.UserDefinedMessageSource; @@ -31,8 +30,8 @@ import java.net.URL; import java.util.*; -import static org.ngrinder.common.constant.CacheConstants.CACHE_LEFT_PANEL_ENTRIES; -import static org.ngrinder.common.constant.CacheConstants.CACHE_RIGHT_PANEL_ENTRIES; +import static org.ngrinder.common.constant.CacheConstants.LOCAL_CACHE_LEFT_PANEL_ENTRIES; +import static org.ngrinder.common.constant.CacheConstants.LOCAL_CACHE_RIGHT_PANEL_ENTRIES; import static org.ngrinder.common.util.TypeConvertUtils.cast; /** @@ -55,8 +54,7 @@ public class HomeService { * @param feedURL feed url * @return the list of {@link PanelEntry} */ - @SuppressWarnings("unchecked") - @Cacheable(CACHE_LEFT_PANEL_ENTRIES) + @Cacheable(LOCAL_CACHE_LEFT_PANEL_ENTRIES) public List getLeftPanelEntries(String feedURL) { return getPanelEntries(feedURL, PANEL_ENTRY_SIZE, false); } @@ -68,7 +66,7 @@ public List getLeftPanelEntries(String feedURL) { * @param feedURL rss url message * @return {@link PanelEntry} list */ - @Cacheable(CACHE_RIGHT_PANEL_ENTRIES) + @Cacheable(LOCAL_CACHE_RIGHT_PANEL_ENTRIES) public List getRightPanelEntries(String feedURL) { return getPanelEntries(feedURL, PANEL_ENTRY_SIZE, true); } @@ -88,37 +86,39 @@ public Map getUserDefinedMessageSources(String locale) { */ public List getPanelEntries(String feedURL, int maxSize, boolean includeReply) { SyndFeedInput input = new SyndFeedInput(); - XmlReader reader = null; HttpURLConnection feedConnection = null; + try { List panelEntries = new ArrayList<>(); URL url = new URL(feedURL); feedConnection = (HttpURLConnection) url.openConnection(); feedConnection.setConnectTimeout(8000); feedConnection.setReadTimeout(8000); - reader = new XmlReader(feedConnection); - SyndFeed feed = input.build(reader); - int count = 0; - - for (Object eachObj : feed.getEntries()) { - SyndEntryImpl each = cast(eachObj); - if (!includeReply && StringUtils.startsWithIgnoreCase(each.getTitle(), "Re: ")) { - continue; - } - if (count++ >= maxSize) { - break; + + try (XmlReader reader = new XmlReader(feedConnection)) { + SyndFeed feed = input.build(reader); + int count = 0; + + for (Object eachObj : feed.getEntries()) { + SyndEntryImpl each = cast(eachObj); + if (!includeReply && StringUtils.startsWithIgnoreCase(each.getTitle(), "Re: ")) { + continue; + } + if (count++ >= maxSize) { + break; + } + panelEntries.add(getPanelEntry(each)); } - panelEntries.add(getPanelEntry(each)); + Collections.sort(panelEntries); + return panelEntries; } - Collections.sort(panelEntries); - return panelEntries; + } catch (Exception e) { LOG.error("Error while patching the feed entries for {} : {}", feedURL, e.getMessage()); } finally { if (feedConnection != null) { feedConnection.disconnect(); } - IOUtils.closeQuietly(reader); } return Collections.emptyList(); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ApplicationListenerBean.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ApplicationListenerBean.java index 7f1c3477ea..0d1d9658ab 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ApplicationListenerBean.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ApplicationListenerBean.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.config; @@ -18,15 +18,16 @@ import org.ngrinder.common.model.Home; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.lang.NonNull; import org.springframework.stereotype.Service; import lombok.RequiredArgsConstructor; /** * Application life-cycle event listener. - * + * * This class is used to clean up the several locks. - * + * * @since 3.1 */ @Service @@ -35,6 +36,7 @@ public class ApplicationListenerBean implements ApplicationListener systemConfListeners = new ListenerSupport<>(); + private Home home = null; private Home exHome = null; private PropertiesWrapper internalProperties; @@ -80,11 +82,7 @@ public class Config extends AbstractConfig implements ControllerConstants, Clust private String announcement = ""; private Date announcementDate; private boolean verbose; - - - public static final String NONE_REGION = "NONE"; private boolean cluster; - private ListenerSupport systemConfListeners = new ListenerSupport(); protected PropertiesKeyMapper internalPropertiesKeyMapper = PropertiesKeyMapper.create("internal-properties.map"); protected PropertiesKeyMapper databasePropertiesKeyMapper = PropertiesKeyMapper.create("database-properties.map"); @@ -214,6 +212,7 @@ public int getMonitorPort() { * * @return true if enabled. */ + @SuppressWarnings("unused") public boolean isUsageReportEnabled() { return getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_USAGE_REPORT); } @@ -297,6 +296,7 @@ public static String getUserHome() { CoreLogger.LOGGER.warn(" '" + userHomeFromProperty + "' is accepted."); } String userHome = StringUtils.defaultIfEmpty(userHomeFromProperty, userHomeFromEnv); + if (isEmpty(userHome)) { userHome = System.getProperty("user.home") + File.separator + NGRINDER_DEFAULT_FOLDER; } else if (StringUtils.startsWith(userHome, "~" + File.separator)) { @@ -348,17 +348,13 @@ protected Home resolveExHome() { * Load internal properties which is not modifiable by user. */ protected void loadInternalProperties() { - InputStream inputStream = null; Properties properties = new Properties(); - try { - inputStream = new ClassPathResource("/internal.properties").getInputStream(); + try (InputStream inputStream = new ClassPathResource("/internal.properties").getInputStream()) { properties.load(inputStream); internalProperties = new PropertiesWrapper(properties, internalPropertiesKeyMapper); } catch (IOException e) { CoreLogger.LOGGER.error("Error while load internal.properties", e); internalProperties = new PropertiesWrapper(properties, internalPropertiesKeyMapper); - } finally { - IOUtils.closeQuietly(inputStream); } } @@ -440,11 +436,8 @@ protected void doOnChange() { try { CoreLogger.LOGGER.info("System configuration(system.conf) is changed."); loadProperties(); - systemConfListeners.apply(new Informer() { - @Override - public void inform(PropertyChangeListener listener) { - listener.propertyChange(null); - } + systemConfListeners.apply(listener -> { + listener.propertyChange(null); }); CoreLogger.LOGGER.info("New system configuration is applied."); } catch (Exception e) { @@ -659,12 +652,12 @@ public String getCurrentIP() { } } - /** * Check if the current ngrinder instance is hidden instance from the cluster. * * @return true if hidden. */ + @SuppressWarnings("unused") public boolean isInvisibleRegion() { return getClusterProperties().getPropertyBoolean(PROP_CLUSTER_HIDDEN_REGION); } @@ -715,8 +708,6 @@ public PropertiesWrapper getLdapProperties() { /** * Get the time out milliseconds which would be used between the console and the agent while preparing to test. - * - * @return */ public long getInactiveClientTimeOut() { return getControllerProperties().getPropertyLong(PROP_CONTROLLER_INACTIVE_CLIENT_TIME_OUT); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/Database.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/Database.java index 1499c427d4..2c93a2199b 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/Database.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/Database.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.config; @@ -38,7 +38,7 @@ public enum Database { /** * MYSQL. */ - mysql(com.mysql.cj.jdbc.Driver.class, MYSQLExDialect.class, "jdbc:mysql://%s?characterEncoding=utf8&serverTimezone=%s&%s") { + mysql(com.mysql.cj.jdbc.Driver.class, MYSQLExDialect.class, "jdbc:mysql://%s?characterEncoding=utf8&allowMultiQueries=true&serverTimezone=%s&%s") { @Override protected void setupVariants(BasicDataSource dataSource, PropertiesWrapper databaseProperties) { String databaseUrlOption = databaseProperties.getProperty(DatabaseConfig.PROP_DATABASE_URL_OPTION); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/DatabaseConfig.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/DatabaseConfig.java index 7e2ff460a0..4302de67b7 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/DatabaseConfig.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/DatabaseConfig.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.config; @@ -26,8 +26,6 @@ import org.springframework.context.annotation.DependsOn; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo; -import org.springframework.orm.jpa.persistenceunit.PersistenceUnitPostProcessor; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import javax.persistence.Entity; @@ -88,14 +86,11 @@ public LocalContainerEntityManagerFactoryBean emf() { emf.setJpaVendorAdapter(hibernateJpaVendorAdapter); // To search entity packages from other jar files.. emf.setPackagesToScan("empty"); - emf.setPersistenceUnitPostProcessors(new PersistenceUnitPostProcessor() { - @Override - public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) { - Reflections reflections = new Reflections(ControllerConstants.DEFAULT_PACKAGE_NAME); - for (Class each : reflections.getTypesAnnotatedWith(Entity.class)) { - LOGGER.trace("Entity class {} is detected as the SpringData entity.", each.getName()); - pui.addManagedClassName(each.getName()); - } + emf.setPersistenceUnitPostProcessors(pui -> { + Reflections reflections = new Reflections(ControllerConstants.DEFAULT_PACKAGE_NAME); + for (Class each : reflections.getTypesAnnotatedWith(Entity.class)) { + LOGGER.trace("Entity class {} is detected as the SpringData entity.", each.getName()); + pui.addManagedClassName(each.getName()); } }); return emf; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/DynamicCacheConfig.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/DynamicCacheConfig.java index 2e5c6ea52f..bd681f7204 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/DynamicCacheConfig.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/DynamicCacheConfig.java @@ -149,16 +149,16 @@ public CacheConfigHolder cacheConfigMap() { cm.addDistMap(DIST_MAP_NAME_SAMPLING, 15); cm.addDistMap(DIST_MAP_NAME_MONITORING, 15); cm.addDistMap(DIST_MAP_NAME_AGENT, 10); + cm.addDistMap(DIST_MAP_NAME_RECENTLY_USED_AGENTS, 1 * DAY); - cm.addDistCache(CACHE_USERS, 30, 300); - cm.addDistCache(CACHE_FILE_ENTRIES, 1 * HOUR + 40 * MIN, 300); + cm.addDistCache(DIST_CACHE_USERS, 30, 300); + cm.addDistCache(DIST_CACHE_FILE_ENTRIES, 1 * HOUR + 40 * MIN, 300); - cm.addLocalCache(CACHE_GITHUB_SCRIPTS, 5 * MIN, 300); - cm.addLocalCache(CACHE_RIGHT_PANEL_ENTRIES, 1 * DAY, 1); - cm.addLocalCache(CACHE_LEFT_PANEL_ENTRIES, 1 * DAY, 1); - cm.addLocalCache(CACHE_CURRENT_PERFTEST_STATISTICS, 5, 1); - cm.addLocalCache(CACHE_GITHUB_IS_MAVEN_GROOVY, 5 * MIN, 300); - cm.addLocalCache(CACHE_RECENTLY_USED_AGENTS, 1 * DAY, 100); + cm.addLocalCache(LOCAL_CACHE_GITHUB_SCRIPTS, 5 * MIN, 300); + cm.addLocalCache(LOCAL_CACHE_RIGHT_PANEL_ENTRIES, 1 * DAY, 1); + cm.addLocalCache(LOCAL_CACHE_LEFT_PANEL_ENTRIES, 1 * DAY, 1); + cm.addLocalCache(LOCAL_CACHE_CURRENT_PERFTEST_STATISTICS, 5, 1); + cm.addLocalCache(LOCAL_CACHE_GITHUB_GROOVY_PROJECT_SCRIPT_TYPE, 5 * MIN, 300); return cm; } @@ -177,6 +177,7 @@ void addDistMap(String cacheName, int timeout) { hazelcastCacheConfigs.put(cacheName, mapConfig); } + @SuppressWarnings("SameParameterValue") void addDistCache(String cacheName, int timeout, int count) { MapConfig mapConfig = createDistMapConfig(cacheName, timeout); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/JacksonConfig.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/JacksonConfig.java index 79e5836c67..94a80c939e 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/JacksonConfig.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/JacksonConfig.java @@ -21,22 +21,27 @@ package org.ngrinder.infra.config; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.text.SimpleDateFormat; - @Configuration public class JacksonConfig { + @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return customizer -> { customizer.serializationInclusion(JsonInclude.Include.NON_NULL); customizer.indentOutput(true); - customizer.timeZone("GMT"); - customizer.dateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); customizer.modules(new NumberModule()); + customizer.modules(new JavaTimeModule()); + + customizer.featuresToEnable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + customizer.featuresToDisable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS); + customizer.featuresToDisable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS); }; } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/SecurityConfig.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/SecurityConfig.java index 738399df91..11956fb538 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/SecurityConfig.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/SecurityConfig.java @@ -171,13 +171,14 @@ protected void configure(HttpSecurity http) throws Exception { .key("ngrinder") .userDetailsService(ngrinderUserDetailsService) .and() - .csrf().disable().exceptionHandling().authenticationEntryPoint(delegatingAuthenticationEntryPoint()); + .csrf().disable().exceptionHandling().authenticationEntryPoint(delegatingAuthenticationEntryPoint()) + .and() + .headers().frameOptions().sameOrigin(); } /** * configure static resource and login page * @param web WebSecurity - * @throws Exception */ @Override public void configure(WebSecurity web) { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ServletConfig.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ServletConfig.java index 4f76baf1f7..7e5005b474 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ServletConfig.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ServletConfig.java @@ -10,9 +10,8 @@ @Configuration public class ServletConfig { @Bean - @SuppressWarnings("unchecked") - public ServletRegistrationBean appServletRegisterBean() { - ServletRegistrationBean appServletRegistrationBean = new ServletRegistrationBean(dispatcherServlet(), dispatcherServletPath().getPath()); + public ServletRegistrationBean appServletRegisterBean() { + ServletRegistrationBean appServletRegistrationBean = new ServletRegistrationBean<>(dispatcherServlet(), dispatcherServletPath().getPath()); appServletRegistrationBean.setLoadOnStartup(1); appServletRegistrationBean.setName("appServlet"); return appServletRegistrationBean; @@ -24,9 +23,8 @@ public DispatcherServlet dispatcherServlet() { } @Bean - @SuppressWarnings("unchecked") - public ServletRegistrationBean svnDavServletRegisterBean() { - ServletRegistrationBean svnDavServletRegistrationBean = new ServletRegistrationBean(new HttpRequestHandlerServlet(), "/svn/*"); + public ServletRegistrationBean svnDavServletRegisterBean() { + ServletRegistrationBean svnDavServletRegistrationBean = new ServletRegistrationBean<>(new HttpRequestHandlerServlet(), "/svn/*"); svnDavServletRegistrationBean.setLoadOnStartup(1); svnDavServletRegistrationBean.setName("svnDavServlet"); return svnDavServletRegistrationBean; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ServletFilterConfig.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ServletFilterConfig.java index 8f2f551dc2..08154f56e0 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ServletFilterConfig.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/ServletFilterConfig.java @@ -10,7 +10,6 @@ import javax.servlet.Filter; @Configuration -@SuppressWarnings("unchecked") public class ServletFilterConfig { @Value("${server.default-encoding}") diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/SvnSecurityConfig.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/SvnSecurityConfig.java index a8db26b9d9..9f0ce05f74 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/SvnSecurityConfig.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/SvnSecurityConfig.java @@ -68,7 +68,6 @@ public class SvnSecurityConfig extends WebSecurityConfigurerAdapter { * @return ShaPasswordEncoder with "SHA-256" algorithm if ngrinder.security.sha256=true. Otherwise * returns with "SHA-1" */ - @SuppressWarnings("deprecation") @Bean public ShaPasswordEncoder shaPasswordEncoder() { boolean useEnhancedEncoding = config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_USER_PASSWORD_SHA256); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/UserDefinedMessageSource.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/UserDefinedMessageSource.java index da27254c76..5181b7e2e9 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/UserDefinedMessageSource.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/UserDefinedMessageSource.java @@ -1,7 +1,6 @@ package org.ngrinder.infra.config; import java.io.File; -import java.io.IOException; import java.io.StringReader; import java.text.MessageFormat; import java.util.*; @@ -47,8 +46,8 @@ public class UserDefinedMessageSource extends AbstractMessageSource { */ static class LocaleAndCode { - private String locale; - private String code; + private final String locale; + private final String code; public LocaleAndCode(String locale, String code) { this.locale = locale; @@ -66,14 +65,6 @@ public boolean equals(Object obj) { } } - /** - * Refresh i18n messages. - * @throws IOException IO exception - */ - public void refresh() throws IOException { - init(); - } - /** * Initialize. */ @@ -127,6 +118,7 @@ private Map getMessageMap(String locale) { .collect(Collectors.toMap(entry -> entry.getKey().code, entry -> entry.getValue().toPattern())); } + @SuppressWarnings("NullableProblems") @Override protected MessageFormat resolveCode(String code, Locale locale) { MessageFormat resolved = langMessageMap.get(new LocaleAndCode(locale.getLanguage(), code)); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/WebMvcConfig.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/WebMvcConfig.java index e51299deb4..64a5da9862 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/config/WebMvcConfig.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/WebMvcConfig.java @@ -1,11 +1,11 @@ package org.ngrinder.infra.config; import com.github.jknack.handlebars.springmvc.HandlebarsViewResolver; +import lombok.RequiredArgsConstructor; import org.ngrinder.infra.interceptor.DefaultSuccessJsonInterceptor; import org.ngrinder.infra.spring.ApiExceptionHandlerResolver; import org.ngrinder.infra.spring.RemainedPathMethodArgumentResolver; import org.ngrinder.infra.spring.UserHandlerMethodArgumentResolver; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.context.annotation.Bean; @@ -32,19 +32,17 @@ useDefaultFilters = false, includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = org.springframework.stereotype.Controller.class)} ) +@RequiredArgsConstructor public class WebMvcConfig implements WebMvcConfigurer { @Value("${server.default-encoding}") private String defaultEncoding; - @Autowired - private LocaleChangeInterceptor localeChangeInterceptor; + private final LocaleChangeInterceptor localeChangeInterceptor; - @Autowired - private DefaultSuccessJsonInterceptor defaultSuccessJsonInterceptor; + private final DefaultSuccessJsonInterceptor defaultSuccessJsonInterceptor; - @Autowired - private ResourceProperties resourceProperties = new ResourceProperties(); + private final ResourceProperties resourceProperties; @Override public void addArgumentResolvers(List argumentResolvers) { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/hazelcast/task/AgentStateTask.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/hazelcast/task/AgentStateTask.java index fa533c0882..943fc5898e 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/hazelcast/task/AgentStateTask.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/hazelcast/task/AgentStateTask.java @@ -17,8 +17,8 @@ */ @SpringAware public class AgentStateTask implements Callable, Serializable { - private String ip; - private String name; + private final String ip; + private final String name; public AgentStateTask(String ip, String name) { this.ip = ip; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/hazelcast/task/ConnectionAgentTask.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/hazelcast/task/ConnectionAgentTask.java index d55df1ec79..fff48de299 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/hazelcast/task/ConnectionAgentTask.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/hazelcast/task/ConnectionAgentTask.java @@ -11,8 +11,8 @@ @SpringAware public class ConnectionAgentTask implements Callable, Serializable { - private String ip; - private int port; + private final String ip; + private final int port; public ConnectionAgentTask(String ip, int port) { this.ip = ip; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/init/ClusterConfigurationVerifier.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/init/ClusterConfigurationVerifier.java index b6b3b9b8da..a534e68191 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/init/ClusterConfigurationVerifier.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/init/ClusterConfigurationVerifier.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.init; @@ -20,7 +20,6 @@ import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; -import java.io.IOException; import static org.ngrinder.common.util.Preconditions.checkState; @@ -43,11 +42,9 @@ public class ClusterConfigurationVerifier { /** * Check cluster configurations. - * - * @throws IOException exception */ @PostConstruct - public void init() throws IOException { + public void init() { if (config.isClustered() && !config.isDevMode()) { checkDB(); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/init/DBInit.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/init/DBInit.java index 76131207e6..0aa25c6f99 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/init/DBInit.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/init/DBInit.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.init; @@ -22,8 +22,9 @@ import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; -import java.util.Date; +import java.time.Instant; +import static java.time.Instant.now; import static org.ngrinder.common.constant.ControllerConstants.PROP_CONTROLLER_ADMIN_PASSWORD_RESET; import static org.ngrinder.model.Role.*; @@ -89,11 +90,11 @@ private void createUser(String userId, String password, Role role, String userNa user.setUserName(userName); user.setEmail(email); - Date now = new Date(); - user.setCreatedDate(now); - user.setLastModifiedDate(now); - user.setCreatedUser(user); - user.setLastModifiedUser(user); + Instant now = now(); + user.setCreatedAt(now); + user.setLastModifiedAt(now); + user.setCreatedBy(user); + user.setLastModifiedBy(user); user = userRepository.save(user); fileEntryService.prepare(user); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/interceptor/DefaultSuccessJsonInterceptor.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/interceptor/DefaultSuccessJsonInterceptor.java index f000156b7e..7adf467c6a 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/interceptor/DefaultSuccessJsonInterceptor.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/interceptor/DefaultSuccessJsonInterceptor.java @@ -23,6 +23,7 @@ public class DefaultSuccessJsonInterceptor implements HandlerInterceptor, WebCon @Autowired private ObjectMapper objectMapper; + @SuppressWarnings("NullableProblems") @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if (modelAndView == null && !response.isCommitted() && diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/plugin/extension/NGrinderPluginManager.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/plugin/extension/NGrinderPluginManager.java index 03393936a1..0d462172d6 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/plugin/extension/NGrinderPluginManager.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/plugin/extension/NGrinderPluginManager.java @@ -3,7 +3,6 @@ import org.ngrinder.infra.config.Config; import org.pf4j.ExtensionFactory; import org.pf4j.JarPluginManager; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @@ -18,12 +17,11 @@ @Component public class NGrinderPluginManager extends JarPluginManager { - @Autowired - private ApplicationContext applicationContext; + private final ApplicationContext applicationContext; - @Autowired - public NGrinderPluginManager(Config config) { + public NGrinderPluginManager(Config config, ApplicationContext applicationContext) { super(config.getHome().getPluginsDirectory().toPath()); + this.applicationContext = applicationContext; } @PostConstruct diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/schedule/ScheduledTaskService.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/schedule/ScheduledTaskService.java index 6eb6086b56..6237d2a641 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/schedule/ScheduledTaskService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/schedule/ScheduledTaskService.java @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.schedule; @@ -41,7 +41,7 @@ public class ScheduledTaskService implements IScheduledTaskService { private final TransactionService transactionService; - private Map scheduledRunnable = new ConcurrentHashMap<>(); + private final Map scheduledRunnable = new ConcurrentHashMap<>(); public void addFixedDelayedScheduledTask(Runnable runnable, int delay) { final ScheduledFuture scheduledFuture = taskScheduler.scheduleWithFixedDelay(runnable, delay); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/servlet/PluggableServletFilter.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/servlet/PluggableServletFilter.java index d72b36d11a..1247c0682d 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/servlet/PluggableServletFilter.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/servlet/PluggableServletFilter.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.servlet; @@ -47,8 +47,6 @@ public class PluggableServletFilter implements Filter { /** * Initialize the servlet filter plugins. - * - * @throws ServletException */ @PostConstruct public void init() { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/ApiExceptionHandlerResolver.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/ApiExceptionHandlerResolver.java index 3b8fbafa52..dae3c63e8d 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/ApiExceptionHandlerResolver.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/ApiExceptionHandlerResolver.java @@ -14,7 +14,6 @@ package org.ngrinder.infra.spring; import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.io.IOUtils; import org.ngrinder.common.util.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -69,6 +68,7 @@ public int getOrder() { * javax.servlet.http.HttpServletResponse, java.lang.Object, * java.lang.Exception) */ + @SuppressWarnings("NullableProblems") @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { if (!(handler instanceof HandlerMethod)) { @@ -85,9 +85,10 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp Throwable throwable = ExceptionUtils.sanitize(ex); StringWriter out = new StringWriter(); - PrintWriter printWriter = new PrintWriter(out); - throwable.printStackTrace(printWriter); - IOUtils.closeQuietly(printWriter); + + try (PrintWriter printWriter = new PrintWriter(out)) { + throwable.printStackTrace(printWriter); + } Map jsonResponse = buildMap( JSON_SUCCESS, false, diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/RemainedPathMethodArgumentResolver.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/RemainedPathMethodArgumentResolver.java index 2d8bd18924..11b7522013 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/RemainedPathMethodArgumentResolver.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/RemainedPathMethodArgumentResolver.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.spring; @@ -24,25 +24,27 @@ import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; +import static java.util.Objects.requireNonNull; + /** * Custom argument resolver to catch the unresolved remaining path. - * + * *
  *  @RequestMapping("hello/**")
  * 	public String handleURL(@RemainedPath String path) {
  *   ....
  * 	}
  * 
- * + * * When hello/world/1 url is called, world/1 will be provided in path. - * + * * @since 3.0 */ public class RemainedPathMethodArgumentResolver implements HandlerMethodArgumentResolver { /* * (non-Javadoc) - * + * * @see * org.springframework.web.method.support.HandlerMethodArgumentResolver#supportsParameter(org * .springframework.core.MethodParameter) @@ -54,8 +56,8 @@ public boolean supportsParameter(MethodParameter parameter) { /* * (non-Javadoc) - * - * + * + * * @see * org.springframework.web.method.support.HandlerMethodArgumentResolver#resolveArgument(org. * springframework.core.MethodParameter, @@ -65,24 +67,22 @@ public boolean supportsParameter(MethodParameter parameter) { */ @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, - NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { AntPathMatcher pathMatcher = new AntPathMatcher(); RequestMapping requestMappingOnMethod = parameter.getMethodAnnotation(RequestMapping.class); RequestMapping requestMappingOnClass = getDeclaringClassRequestMapping(parameter); - String combine = pathMatcher.combine(requestMappingOnClass.value()[0], requestMappingOnMethod.value()[0]); + String combine = pathMatcher.combine(requestMappingOnClass.value()[0], requireNonNull(requestMappingOnMethod).value()[0]); String path = ((ServletWebRequest) webRequest).getRequest().getRequestURI().substring(webRequest.getContextPath().length()); return PathUtils.removePrependedSlash(pathMatcher.extractPathWithinPattern(combine, EncodingUtils.decodePathWithUTF8(path))); } /** * Get the request mapping annotation on the given parameter. - * - * @param parameter - * parameter + * + * @param parameter parameter * @return {@link RequestMapping} annotation */ - @SuppressWarnings("unchecked") protected RequestMapping getDeclaringClassRequestMapping(MethodParameter parameter) { - return (RequestMapping) parameter.getDeclaringClass().getAnnotation(RequestMapping.class); + return parameter.getDeclaringClass().getAnnotation(RequestMapping.class); } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/SpringContext.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/SpringContext.java index 851a83a8b6..96e78db2d5 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/SpringContext.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/SpringContext.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.spring; @@ -40,6 +40,7 @@ public boolean isAuthenticationContext() { * @return always false. * @see MockSpringContext */ + @SuppressWarnings("JavadocReference") public boolean isUnitTestContext() { return false; } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/UserHandlerMethodArgumentResolver.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/UserHandlerMethodArgumentResolver.java index 7cf32d96ad..ec8770c16b 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/UserHandlerMethodArgumentResolver.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/UserHandlerMethodArgumentResolver.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.spring; @@ -30,9 +30,9 @@ /** * {@link HandlerMethodArgumentResolver} for {@link User} argument. - * + * * It passes the current user instance on {@link User} argument. - * + * * @since 3.0 */ public class UserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { @@ -48,9 +48,10 @@ public boolean supportsParameter(MethodParameter parameter) { return parameter.getParameterIndex() == 0 && parameter.getParameterType().equals(User.class); } + @SuppressWarnings("NullableProblems") @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, - NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { User currentUser = getUserContext().getCurrentUser(); String userParam = webRequest.getParameter("ownerId"); @@ -71,11 +72,11 @@ public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer m } // Let this can be done with parameter as well. switchUser = StringUtils.defaultIfBlank(webRequest.getParameter("switchUser"), switchUser); - + if (currentUser.getUserId().equals(switchUser)) { currentUser.setOwnerUser(null); } else if (StringUtils.isNotEmpty(switchUser)) { - User ownerUser = getUserService().getOne(switchUser); + User ownerUser = getUserService().getOneWithEagerFetch(switchUser); // CurrentUser should remember whose status he used if (currentUser.getRole().hasPermission(Permission.SWITCH_TO_ANYONE) || (ownerUser.getFollowers() != null && ownerUser.getFollowers().contains(currentUser))) { @@ -96,7 +97,7 @@ Cookie[] getCookies(NativeWebRequest webRequest) { /** * Get current user context.
* This method is provided for XML based spring bean injection. - * + * * @return user context */ public UserContext getUserContext() { @@ -106,7 +107,7 @@ public UserContext getUserContext() { /** * Set the current user context.
* This method is provided for XML based spring bean injection. - * + * * @param userContext * user context. */ diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/listener/ApplicationPreparedListener.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/listener/ApplicationPreparedListener.java index ce6f3522b5..5fe57a4c7f 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/listener/ApplicationPreparedListener.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/spring/listener/ApplicationPreparedListener.java @@ -1,21 +1,25 @@ package org.ngrinder.infra.spring.listener; import com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider; -import org.springframework.boot.context.event.ApplicationPreparedEvent; +import org.springframework.boot.context.event.ApplicationContextInitializedEvent; import org.springframework.context.ApplicationListener; import javax.cache.Caching; import javax.cache.spi.CachingProvider; import java.util.Iterator; +import static org.ngrinder.starter.InstallationChecker.checkAll; + /** * @since 3.5.0 * */ -public class ApplicationPreparedListener implements ApplicationListener { +public class ApplicationPreparedListener implements ApplicationListener { + @SuppressWarnings("NullableProblems") @Override - public void onApplicationEvent(ApplicationPreparedEvent event) { + public void onApplicationEvent(ApplicationContextInitializedEvent event) { removeCacheProviderExceptCaffeineCacheProvider(); + checkAll(); } /** @@ -30,4 +34,5 @@ private static void removeCacheProviderExceptCaffeineCacheProvider() { } } } + } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/controller/WebhookApiController.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/controller/WebhookApiController.java index 4a2bfb3e14..3582275046 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/controller/WebhookApiController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/controller/WebhookApiController.java @@ -62,8 +62,8 @@ public WebhookConfig getOne(User user) { } @GetMapping("/activation") - public List getActivations(@RequestParam String createdUserId, + public List getActivations(@RequestParam String creatorId, @PageableDefault Pageable pageable) { - return webhookActivationService.findAll(createdUserId, pageable); + return webhookActivationService.findAll(creatorId, pageable); } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/ContentType.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/ContentType.java index 7b05688b06..5569f92e0e 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/ContentType.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/ContentType.java @@ -47,9 +47,9 @@ public enum ContentType { JSON("application/json", APPLICATION_JSON), FORM_URL_ENCODED("application/x-www-form-urlencoded", APPLICATION_FORM_URLENCODED); - private String name; + private final String name; - private MediaType mediaType; + private final MediaType mediaType; public static class ContentTypeDeserializer extends JsonDeserializer { @Override diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/Event.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/Event.java index bef5fc0622..b71e2d11d2 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/Event.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/Event.java @@ -26,10 +26,11 @@ import org.ngrinder.model.Status; import org.ngrinder.model.User; +import java.time.Instant; import java.util.Map; import java.util.function.Function; -import static java.time.LocalDateTime.now; +import static java.time.Instant.now; import static org.ngrinder.common.util.AccessUtils.getSafe; import static org.ngrinder.common.util.CollectionUtils.newHashMap; import static org.ngrinder.model.Status.UNKNOWN; @@ -46,7 +47,7 @@ public enum Event { START(perfTest -> { Map payload = createBasePayload(perfTest); payload.put("eventType", "START"); - payload.put("startTime", now().toString()); + payload.put("startTime", now()); return payload; }), @@ -58,7 +59,7 @@ public enum Event { Status status = getSafe(finishedPerfTest.getStatus(), UNKNOWN); payload.put("eventType", "FINISH"); - payload.put("finishTime", now().toString()); + payload.put("finishTime", now()); payload.put("peakTPS", getSafe(finishedPerfTest.getPeakTps(), 0.0)); payload.put("TPS", getSafe(finishedPerfTest.getTps(), 0.0)); payload.put("errors", errors); @@ -78,9 +79,9 @@ private static Map createBasePayload(PerfTest perfTest) { int vuserPerAgent = getSafe(perfTest.getVuserPerAgent(), 0); int agentCount = getSafe(perfTest.getAgentCount(), 0); - User createdUser = getSafe(perfTest.getCreatedUser(), new User()); + User createdBy = getSafe(perfTest.getCreatedBy(), new User()); - payload.put("createdUserId", getSafe(createdUser.getUserId(), "")); + payload.put("createdBy", getSafe(createdBy.getUserId(), "")); payload.put("testId", getSafe(perfTest.getId(), 0L)); payload.put("testName", getSafe(perfTest.getTestName(), "")); payload.put("scriptName", getSafe(perfTest.getScriptName(), "")); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/WebhookActivation.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/WebhookActivation.java index b16e2ce252..34543afdc5 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/WebhookActivation.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/WebhookActivation.java @@ -29,13 +29,14 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; -import java.util.Date; +import java.time.Instant; /** * Webhook activation model. * * @since 3.5.2 */ +@SuppressWarnings("JpaDataSourceORMInspection") @Getter @Setter @Entity @@ -44,11 +45,11 @@ @Table(name = "WEBHOOK_ACTIVATION") public class WebhookActivation extends BaseEntity { - @Column(name = "created_user_id") - private String createdUserId; + @Column(name = "creator_id") + private String creatorId; - @Column(name = "created_time") - private Date createdTime; + @Column(name = "created_at") + private Instant createdAt; private String request; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/WebhookConfig.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/WebhookConfig.java index d93c5df0f6..08da33f914 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/WebhookConfig.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/WebhookConfig.java @@ -24,11 +24,11 @@ import org.ngrinder.model.BaseEntity; import javax.persistence.*; -import java.util.Date; +import java.time.Instant; import java.util.Set; +import static java.time.Instant.now; import static org.apache.commons.lang.StringUtils.isEmpty; -import static org.ngrinder.common.util.AccessUtils.getSafe; import static org.ngrinder.common.util.CollectionUtils.newHashSet; /** @@ -36,6 +36,7 @@ * * @since 3.5.2 */ +@SuppressWarnings("JpaDataSourceORMInspection") @Getter @Setter @Entity @@ -44,8 +45,8 @@ @Table(name = "WEBHOOK_CONFIG") public class WebhookConfig extends BaseEntity { - @Column(name = "created_user_id") - private String createdUserId; + @Column(name = "creator_id") + private String creatorId; private boolean active; @@ -58,11 +59,11 @@ public class WebhookConfig extends BaseEntity { private String events; - @Column(name = "created_time") - private Date createdTime; + @Column(name = "created_at") + private Instant createdAt; - @Column(name = "last_modified_time") - private Date lastModifiedTime; + @Column(name = "last_modified_at") + private Instant lastModifiedAt; @Transient @Getter(value = AccessLevel.NONE) @@ -70,7 +71,7 @@ public class WebhookConfig extends BaseEntity { @PreUpdate public void preUpdate() { - this.lastModifiedTime = new Date(); + this.lastModifiedAt = now(); } public Set getEvents() { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/plugin/NGrinderWebhookPlugin.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/plugin/NGrinderWebhookPlugin.java index 29fa61b3f3..8455cdfc52 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/plugin/NGrinderWebhookPlugin.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/plugin/NGrinderWebhookPlugin.java @@ -30,6 +30,7 @@ import org.ngrinder.model.PerfTest; import org.ngrinder.service.IPerfTestService; +import static org.ngrinder.common.util.LoggingUtils.format; import static org.ngrinder.infra.webhook.model.Event.FINISH; import static org.ngrinder.infra.webhook.model.Event.START; @@ -38,22 +39,21 @@ * * @since 3.5.2 */ -@SuppressWarnings("DuplicatedCode") @Slf4j @AllArgsConstructor public class NGrinderWebhookPlugin implements OnTestLifeCycleRunnable { // Be injected manually for backward compatibility. - private WebhookService webhookService; + private final WebhookService webhookService; - private WebhookConfigService webhookConfigService; + private final WebhookConfigService webhookConfigService; @Override public void start(PerfTest perfTest, IPerfTestService perfTestService, String version) { try { sendWebhookRequest(perfTest, START); } catch (RuntimeException e) { - log.error("[{}] An exception occurred while sending the webhook start request.", perfTest.getId(), e); + log.error(format(perfTest, "An exception occurred while sending the webhook start request."), e); } } @@ -62,12 +62,12 @@ public void finish(PerfTest perfTest, String stopReason, IPerfTestService perfTe try { sendWebhookRequest(perfTest, FINISH); } catch (RuntimeException e) { - log.error("[{}] An exception occurred while sending the webhook finish request.", perfTest.getId(), e); + log.error(format(perfTest, "An exception occurred while sending the webhook finish request."), e); } } private void sendWebhookRequest(PerfTest perfTest, Event event) { - WebhookConfig webhookConfig = webhookConfigService.getOne(perfTest.getCreatedUser().getUserId()); + WebhookConfig webhookConfig = webhookConfigService.getOne(perfTest.getCreatedBy().getUserId()); if (webhookConfig == null) { return; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookActivationRepository.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookActivationRepository.java index 717447b7b5..f819cb610f 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookActivationRepository.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookActivationRepository.java @@ -34,6 +34,7 @@ */ public interface WebhookActivationRepository extends JpaRepository, JpaSpecificationExecutor { + @SuppressWarnings("NullableProblems") @Override Page findAll(Specification spec, Pageable pageable); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookActivationSpecification.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookActivationSpecification.java index c5b0dcc814..429e2a1f42 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookActivationSpecification.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookActivationSpecification.java @@ -30,7 +30,7 @@ */ public abstract class WebhookActivationSpecification { - public static Specification createdUserIdEqual(String createdUerId) { - return (Specification) (root, query, cb) -> cb.equal(root.get("createdUserId"), createdUerId); + public static Specification creatorIdEqual(String creatorId) { + return (Specification) (root, query, cb) -> cb.equal(root.get("creatorId"), creatorId); } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookConfigSpecification.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookConfigSpecification.java index 0d8f05e6ad..57e9ac508c 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookConfigSpecification.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/repository/WebhookConfigSpecification.java @@ -30,7 +30,7 @@ */ public abstract class WebhookConfigSpecification { - public static Specification createdUserIdEqual(String createdUerId) { - return (Specification) (root, query, cb) -> cb.equal(root.get("createdUserId"), createdUerId); + public static Specification creatorIdEqual(String creatorId) { + return (Specification) (root, query, cb) -> cb.equal(root.get("creatorId"), creatorId); } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/NGrinderWebhookClient.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/NGrinderWebhookClient.java index 258cabc5eb..55f6c0d5a9 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/NGrinderWebhookClient.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/NGrinderWebhookClient.java @@ -42,6 +42,7 @@ public class NGrinderWebhookClient { private final WebClient webClient; + @SuppressWarnings("BlockingMethodInNonBlockingContext") Mono> post(String url, MediaType mediaType, Map payLoad) { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookActivationService.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookActivationService.java index f5cc541da8..736c374c1b 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookActivationService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookActivationService.java @@ -31,7 +31,7 @@ import java.util.List; import static org.ngrinder.common.util.Preconditions.checkNotNull; -import static org.ngrinder.infra.webhook.repository.WebhookActivationSpecification.createdUserIdEqual; +import static org.ngrinder.infra.webhook.repository.WebhookActivationSpecification.creatorIdEqual; @Slf4j @Service @@ -40,8 +40,8 @@ public class WebhookActivationService { private final WebhookActivationRepository webhookActivationRepository; - public List findAll(String createdUserId, Pageable pageable) { - Page webhookActivation = webhookActivationRepository.findAll(createdUserIdEqual(createdUserId), pageable); + public List findAll(String creatorId, Pageable pageable) { + Page webhookActivation = webhookActivationRepository.findAll(creatorIdEqual(creatorId), pageable); return webhookActivation.getContent(); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookConfigService.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookConfigService.java index b63022e702..b058b4f7c6 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookConfigService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookConfigService.java @@ -27,11 +27,11 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.Date; import java.util.Optional; +import static java.time.Instant.now; import static org.ngrinder.common.util.Preconditions.checkNotNull; -import static org.ngrinder.infra.webhook.repository.WebhookConfigSpecification.createdUserIdEqual; +import static org.ngrinder.infra.webhook.repository.WebhookConfigSpecification.creatorIdEqual; @Slf4j @Service @@ -43,18 +43,18 @@ public class WebhookConfigService { @Transactional public void save(WebhookConfig webhookConfig) { checkNotNull(webhookConfig); - Optional findOne = webhookConfigRepository.findOne(createdUserIdEqual(webhookConfig.getCreatedUserId())); + Optional findOne = webhookConfigRepository.findOne(creatorIdEqual(webhookConfig.getCreatorId())); if (findOne.isPresent()) { WebhookConfig existingWebhookConfig = findOne.get(); existingWebhookConfig.update(webhookConfig); return; } - webhookConfig.setCreatedTime(new Date()); + webhookConfig.setCreatedAt(now()); webhookConfigRepository.save(webhookConfig); } - public WebhookConfig getOne(String createdUserId) { - Optional webhookConfig = webhookConfigRepository.findOne(createdUserIdEqual(createdUserId)); + public WebhookConfig getOne(String createdBy) { + Optional webhookConfig = webhookConfigRepository.findOne(creatorIdEqual(createdBy)); return webhookConfig.orElse(null); } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookService.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookService.java index 9e1f7c08cf..0035f6997b 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/service/WebhookService.java @@ -33,11 +33,11 @@ import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; -import java.util.Date; import java.util.Map; import java.util.UUID; import static java.time.Duration.ofSeconds; +import static java.time.Instant.now; import static org.ngrinder.common.util.AccessUtils.getSafe; import static org.ngrinder.common.util.CollectionUtils.newHashMap; import static org.springframework.http.HttpStatus.BAD_REQUEST; @@ -73,7 +73,7 @@ public void sendWebhookRequest(PerfTest perfTest, public void sendDummyWebhookRequest(User user, WebhookConfig webhookConfig, Event event) { PerfTest perfTest = new PerfTest(); - perfTest.setCreatedUser(user); + perfTest.setCreatedBy(user); sendWebhookRequest(perfTest, webhookConfig, event); } @@ -89,7 +89,7 @@ private void saveWebhookActivation(PerfTest perfTest, } WebhookActivation webhookActivation = new WebhookActivation(); - webhookActivation.setCreatedUserId(perfTest.getCreatedUser().getUserId()); + webhookActivation.setCreatorId(perfTest.getCreatedBy().getUserId()); webhookActivation.setUuid(UUID.randomUUID().toString()); try { @@ -103,7 +103,7 @@ private void saveWebhookActivation(PerfTest perfTest, } catch (JsonProcessingException e) { webhookActivation.setResponse(response.toString()); } - webhookActivation.setCreatedTime(new Date()); + webhookActivation.setCreatedAt(now()); webhookActivationService.save(webhookActivation); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/AnnouncementController.java b/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/AnnouncementController.java index 23045f6362..12caf78785 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/AnnouncementController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/AnnouncementController.java @@ -29,6 +29,7 @@ @PreAuthorize("hasAnyRole('A', 'S')") public class AnnouncementController { + @SuppressWarnings("SpringMVCViewInspection") @GetMapping("") public String open() { return "app"; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/ScriptConsoleController.java b/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/ScriptConsoleController.java index d050e81fbe..8d992e3319 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/ScriptConsoleController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/ScriptConsoleController.java @@ -27,6 +27,7 @@ @PreAuthorize("hasAnyRole('A')") public class ScriptConsoleController { + @SuppressWarnings("SpringMVCViewInspection") @GetMapping({"", "/"}) public String scriptConsole() { return "app"; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/SystemConfigController.java b/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/SystemConfigController.java index c661accd5d..d032e87b53 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/SystemConfigController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/SystemConfigController.java @@ -30,6 +30,7 @@ @PreAuthorize("hasAnyRole('A')") public class SystemConfigController { + @SuppressWarnings("SpringMVCViewInspection") @GetMapping("") public String systemConfig() { return "app"; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/operation/service/AnnouncementService.java b/ngrinder-controller/src/main/java/org/ngrinder/operation/service/AnnouncementService.java index 960f7f0740..e2f77391b3 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/operation/service/AnnouncementService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/operation/service/AnnouncementService.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.operation.service; @@ -28,7 +28,7 @@ /** * Announcement operating service. - * + * * @since 3.1 */ @Service @@ -41,7 +41,7 @@ public class AnnouncementService { /** * Get announcement.conf file content. - * + * * @return file content. */ public String getOne() { @@ -50,7 +50,7 @@ public String getOne() { /** * Check the announcement was changed since 1 week ago. - * + * * @return true if it's new one */ public boolean isNew() { @@ -65,10 +65,8 @@ public boolean isNew() { /** * Save content to announcement.conf file. - * - * @param content - * file content. - * @return save successfully or not. + * + * @param content file content. */ public void save(String content) { try { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/operation/service/SystemConfigService.java b/ngrinder-controller/src/main/java/org/ngrinder/operation/service/SystemConfigService.java index 38f9385edb..3d7fec052b 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/operation/service/SystemConfigService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/operation/service/SystemConfigService.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.operation.service; @@ -26,7 +26,7 @@ /** * System configuration operation service. - * + * * @since 3.1 */ @Service @@ -39,7 +39,7 @@ public class SystemConfigService { /** * Get system configuration file content. - * + * * @return file content. */ public String getOne() { @@ -53,10 +53,8 @@ public String getOne() { /** * Save content to system configuration file. - * - * @param content - * file content. - * @return save successfully or not. + * + * @param content ile content. */ public void save(String content) { try { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/packages/AgentPackageHandler.java b/ngrinder-controller/src/main/java/org/ngrinder/packages/AgentPackageHandler.java index 29948b6bed..d85c120395 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/packages/AgentPackageHandler.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/packages/AgentPackageHandler.java @@ -1,10 +1,8 @@ package org.ngrinder.packages; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang.StringUtils; import org.ngrinder.infra.schedule.ScheduledTaskService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -15,17 +13,14 @@ import static org.ngrinder.common.util.CollectionUtils.newHashMap; @Component("agentPackageHandler") +@RequiredArgsConstructor public class AgentPackageHandler extends PackageHandler { - private Logger LOGGER = LoggerFactory.getLogger(AgentPackageHandler.class); - - @Autowired - private ScheduledTaskService scheduledTaskService; + private final ScheduledTaskService scheduledTaskService; @PostConstruct public void cleanUpCachedPackageDir() { cleanUpPackageDir(true); - scheduledTaskService.addFixedDelayedScheduledTask(() -> cleanUpPackageDir(false), TIME_MILLIS_OF_DAY); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/packages/MonitorPackageHandler.java b/ngrinder-controller/src/main/java/org/ngrinder/packages/MonitorPackageHandler.java index 5eae95c804..2802e0afb8 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/packages/MonitorPackageHandler.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/packages/MonitorPackageHandler.java @@ -13,7 +13,7 @@ public class MonitorPackageHandler extends PackageHandler { @Override public Map getConfigParam(String regionName, String controllerIP, int port, String owner) { - return buildMap("monitorPort", (Object) String.valueOf(port)); + return buildMap("monitorPort", String.valueOf(port)); } @Override diff --git a/ngrinder-controller/src/main/java/org/ngrinder/packages/PackageHandler.java b/ngrinder-controller/src/main/java/org/ngrinder/packages/PackageHandler.java index 5602921d81..3617381269 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/packages/PackageHandler.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/packages/PackageHandler.java @@ -20,10 +20,13 @@ import java.io.*; import java.net.URLClassLoader; +import java.nio.charset.Charset; import java.util.HashSet; import java.util.Map; import java.util.Set; +import static freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS; +import static java.nio.charset.Charset.defaultCharset; import static org.apache.commons.lang.StringUtils.isNotEmpty; import static org.apache.commons.lang.StringUtils.trimToEmpty; import static org.ngrinder.common.util.CompressionUtils.*; @@ -42,7 +45,7 @@ public abstract class PackageHandler { protected Set getDependentLibs(URLClassLoader urlClassLoader) { Set libs = new HashSet<>(); try (InputStream dependencyStream = urlClassLoader.getResourceAsStream(this.getDependenciesFileName())) { - final String dependencies = IOUtils.toString(dependencyStream); + final String dependencies = IOUtils.toString(dependencyStream, defaultCharset()); for (String each : StringUtils.split(dependencies, ";")) { libs.add(each.trim().replace("-SNAPSHOT", "")); } @@ -147,9 +150,9 @@ private String getFilenamePostFix(String value) { */ private String convertToConfigString(Map values) { try (StringWriter writer = new StringWriter()) { - Configuration config = new Configuration(); + Configuration config = new Configuration(DEFAULT_INCOMPATIBLE_IMPROVEMENTS); config.setClassForTemplateLoading(this.getClass(), "/ngrinder_agent_home_template"); - config.setObjectWrapper(new DefaultObjectWrapper()); + config.setObjectWrapper(new DefaultObjectWrapper(DEFAULT_INCOMPATIBLE_IMPROVEMENTS)); Template template = config.getTemplate(getTemplateName()); template.process(values, writer); return writer.toString(); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestApiController.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestApiController.java index e7c8599149..14e28d0977 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestApiController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestApiController.java @@ -38,7 +38,6 @@ import org.ngrinder.user.service.UserContext; import org.ngrinder.user.service.UserService; import org.python.google.common.collect.Maps; -import org.springframework.context.MessageSource; import org.springframework.context.annotation.Profile; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -99,8 +98,6 @@ public class PerfTestApiController { private final Config config; - private final MessageSource messageSource; - /** * Get the perf test lists. * @@ -127,7 +124,7 @@ public Map getAllList(User user, result.put("size", tests.getSize()); result.put("queryFilter", queryFilter); result.put("query", query); - result.put("createdUserId", user.getUserId()); + result.put("createdBy", user.getUserId()); result.put("tests", tests.getContent()); putPageIntoModelMap(result, pageable); return result; @@ -290,7 +287,7 @@ public Map getOneDetail(User user, @PathVariable Long id) { // Retrieve the agent count map based on create user, if the test is // created by the others. - user = test.getCreatedUser(); + user = test.getCreatedBy(); result.putAll(getDefaultAttributes(user)); return result; } @@ -402,7 +399,7 @@ private PerfTest getOneWithPermissionCheck(User user, Long id, boolean withTag) if (user.getRole().equals(Role.ADMIN) || user.getRole().equals(Role.SUPER_USER)) { return perfTest; } - if (perfTest != null && !user.equals(perfTest.getCreatedUser())) { + if (perfTest != null && !user.equals(perfTest.getCreatedBy())) { throw processException("User " + user.getUserId() + " has no right on PerfTest " + id); } return perfTest; @@ -472,11 +469,10 @@ private String getStatusMessage(PerfTest perfTest) { message += progressMessage + "
"; } message += "" + perfTest.getLastProgressMessage() + "
"; - message += perfTest.getLastModifiedDateToStr(); + message += perfTest.getLastModifiedAtToStr(); return replace(message, "\n", "
"); } - @SuppressWarnings("ConstantConditions") private void validate(User user, PerfTest oldOne, PerfTest newOne) { if (oldOne == null) { oldOne = new PerfTest(); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestController.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestController.java index b3eac268ba..4afb2f7072 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/controller/PerfTestController.java @@ -39,6 +39,7 @@ /** * Performance Test Controller. */ +@SuppressWarnings({"SpringMVCViewInspection", "unused"}) @Controller @RequestMapping("/perftest") @GlobalControllerModel @@ -127,22 +128,19 @@ public void showLog(User user, @PathVariable("id") long id, @RemainedPath String response.reset(); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); - FileInputStream fileInputStream = null; - try { - fileInputStream = new FileInputStream(targetFile); + + try (FileInputStream fileInputStream = new FileInputStream(targetFile)) { ServletOutputStream outputStream = response.getOutputStream(); if (FilenameUtils.isExtension(targetFile.getName(), "zip")) { // Limit log view to 1MB outputStream.println(" Only the last 1MB of a log shows.\n"); outputStream.println("==========================================================================\n\n"); - LogCompressUtils.decompress(fileInputStream, outputStream, 1 * 1024 * 1024); + LogCompressUtils.decompress(fileInputStream, outputStream, 1024 * 1024); } else { IOUtils.copy(fileInputStream, outputStream); } } catch (Exception e) { CoreLogger.LOGGER.error("Error while processing log. {}", targetFile, e); - } finally { - IOUtils.closeQuietly(fileInputStream); } } @@ -162,7 +160,7 @@ public String getReport(@PathVariable long id) { * @param id test id * @return perftest/detail_report/perf */ - @SuppressWarnings({"MVCPathVariableInspection", "UnusedParameters"}) + @SuppressWarnings("UnusedParameters") @GetMapping("/{id}/detail_report/perf") public String getDetailPerfReport(@PathVariable("id") long id) { return "perftest/detail_report/perf"; @@ -202,12 +200,13 @@ public String getDetailPluginReport(@PathVariable("id") long id, } + @SuppressWarnings("SameParameterValue") private PerfTest getOneWithPermissionCheck(User user, Long id, boolean withTag) { PerfTest perfTest = withTag ? perfTestService.getOneWithTag(id) : perfTestService.getOne(id); if (user.getRole().equals(Role.ADMIN) || user.getRole().equals(Role.SUPER_USER)) { return perfTest; } - if (perfTest != null && !user.equals(perfTest.getCreatedUser())) { + if (perfTest != null && !user.equals(perfTest.getCreatedBy())) { throw processException("User " + user.getUserId() + " has no right on PerfTest " + id); } return perfTest; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/model/SamplingModel.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/model/SamplingModel.java index 7ae631b7e0..1486ab2c6f 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/model/SamplingModel.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/model/SamplingModel.java @@ -11,8 +11,8 @@ */ @Getter public class SamplingModel implements Serializable { - private String runningSample; - private String agentState; + private final String runningSample; + private final String agentState; public SamplingModel(String runningSample, String agentState) { this.runningSample = runningSample; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/PerfTestRepository.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/PerfTestRepository.java index 50920ee408..e7dbec7ff0 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/PerfTestRepository.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/PerfTestRepository.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.repository; @@ -30,6 +30,7 @@ * * @since 3.0 */ +@SuppressWarnings("JavaDoc") public interface PerfTestRepository extends JpaRepository, JpaSpecificationExecutor { /** * Find the paged {@link PerfTest}s based on the given spec. @@ -38,6 +39,7 @@ public interface PerfTestRepository extends JpaRepository, JpaSp * @param pageable page info * @return {@link PerfTest} list */ + @SuppressWarnings("NullableProblems") Page findAll(Specification spec, Pageable pageable); @@ -68,8 +70,9 @@ public interface PerfTestRepository extends JpaRepository, JpaSp * @param region region * @return {@link PerfTest} list */ + @SuppressWarnings("JpaQlInspection") @Query("select p from PerfTest p where p.startTime between ?1 and ?2 and region=?3") - List findAllByCreatedTimeAndRegion(Date start, Date end, String region); + List findAllByCreatedAtAndRegion(Date start, Date end, String region); /** * Find all {@link PerfTest} created between the given start and end dates. @@ -79,5 +82,5 @@ public interface PerfTestRepository extends JpaRepository, JpaSp * @return {@link PerfTest} list */ @Query("select p from PerfTest p where p.startTime between ?1 and ?2") - List findAllByCreatedTime(Date start, Date end); + List findAllByCreatedAt(Date start, Date end); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/PerfTestSpecification.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/PerfTestSpecification.java index 4ff0fbc1e0..a9c9772d2f 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/PerfTestSpecification.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/PerfTestSpecification.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,14 +9,10 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.repository; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import javax.persistence.criteria.SetJoin; import org.ngrinder.model.PerfTest; @@ -127,7 +123,7 @@ public static Specification likeTestNameOrDescription(final String que * @return {@link Specification} */ public static Specification createdBy(final User user) { - return (Specification) (root, query, cb) -> cb.or(cb.equal(root.get("createdUser"), user)); + return (Specification) (root, query, cb) -> cb.or(cb.equal(root.get("createdBy"), user)); } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/TagSpecification.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/TagSpecification.java index b4d72cc7c8..82fdd57204 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/TagSpecification.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/repository/TagSpecification.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,14 +9,10 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.repository; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import javax.persistence.criteria.SetJoin; import org.apache.commons.lang.StringUtils; @@ -44,14 +40,14 @@ public static Specification valueIn(final String[] values) { } /** - * Get lastModifiedUser and createBy {@link Specification} to get the {@link Tag} whose creator or last modifier is + * Get lastModifiedBy and createBy {@link Specification} to get the {@link Tag} whose creator or last modifier is * the given user. * * @param user user * @return {@link Specification} */ public static Specification lastModifiedOrCreatedBy(final User user) { - return (Specification) (root, query, cb) -> cb.or(cb.equal(root.get("lastModifiedUser"), user), cb.equal(root.get("createdUser"), user)); + return (Specification) (root, query, cb) -> cb.or(cb.equal(root.get("lastModifiedBy"), user), cb.equal(root.get("createdBy"), user)); } /** diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/AgentManager.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/AgentManager.java index 6e3ed35824..cea93c6133 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/AgentManager.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/AgentManager.java @@ -28,7 +28,6 @@ import net.grinder.engine.controller.AgentControllerIdentityImplementation; import net.grinder.message.console.AgentControllerState; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.ngrinder.agent.service.AgentPackageService; @@ -332,9 +331,8 @@ public Set getAttachedAgentStatusSetConnectingToPort(final int sing public synchronized AgentUpdateGrinderMessage onAgentDownloadRequested(String version, int offset) { final int updateChunkSize = getUpdateChunkSize(); byte[] buffer = new byte[updateChunkSize]; - RandomAccessFile agentPackageReader = null; - try { - agentPackageReader = new RandomAccessFile(agentPackageService.createAgentPackage(), "r"); + + try (RandomAccessFile agentPackageReader = new RandomAccessFile(agentPackageService.createAgentPackage(), "r")) { agentPackageReader.seek(offset); int count = agentPackageReader.read(buffer, 0, updateChunkSize); byte[] bytes = buffer; @@ -347,8 +345,6 @@ public synchronized AgentUpdateGrinderMessage onAgentDownloadRequested(String ve CRC32ChecksumUtils.getCRC32Checksum(bytes)); } catch (Exception e) { LOGGER.error("Error while reading agent package, its offset is {} and details {}:", offset, e); - } finally { - IOUtils.closeQuietly(agentPackageReader); } return AgentUpdateGrinderMessage.getNullAgentUpdateGrinderMessage(version); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/ConsoleEntry.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/ConsoleEntry.java index 943947e656..f092dc8a3d 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/ConsoleEntry.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/ConsoleEntry.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; @@ -30,7 +30,7 @@ */ public class ConsoleEntry { - private String ip; + private final String ip; /** * Console port number. */ @@ -60,15 +60,13 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } + ConsoleEntry other = (ConsoleEntry) obj; + if (port == null) { - if (other.port != null) { - return false; - } - } else if (!port.equals(other.port)) { - return false; + return other.port == null; } - return true; + return port.equals(other.port); } @Override diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/ConsoleManager.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/ConsoleManager.java index 87f7a2dca8..573fa186bb 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/ConsoleManager.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/ConsoleManager.java @@ -55,6 +55,8 @@ public class ConsoleManager { private static final int MAX_PORT_NUMBER = 65000; private static final Logger LOG = LoggerFactory.getLogger(ConsoleManager.class); private volatile ArrayBlockingQueue consoleQueue; + + @SuppressWarnings("FieldMayBeFinal") private volatile List consoleInUse = Collections.synchronizedList(new ArrayList<>()); private final Config config; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestRunnable.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestRunnable.java index ebe05775f1..bf56d2880a 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestRunnable.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestRunnable.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; @@ -17,7 +17,6 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; import net.grinder.SingleConsole; -import net.grinder.SingleConsole.ConsoleShutdownListener; import net.grinder.StopReason; import net.grinder.common.GrinderProperties; import net.grinder.console.model.ConsoleProperties; @@ -25,7 +24,6 @@ import net.grinder.util.ListenerSupport; import net.grinder.util.UnitUtils; import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.time.DateUtils; import org.ngrinder.agent.service.AgentService; import org.ngrinder.common.constant.ControllerConstants; import org.ngrinder.common.exception.PerfTestPrepareException; @@ -51,12 +49,14 @@ import javax.annotation.PreDestroy; import java.io.File; import java.io.IOException; -import java.util.Calendar; -import java.util.Date; +import java.time.Instant; import java.util.List; import java.util.Set; +import static java.time.Instant.*; +import static java.time.temporal.ChronoUnit.MINUTES; import static java.util.Arrays.asList; +import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toSet; import static net.grinder.util.FileUtils.*; import static org.apache.commons.lang.ObjectUtils.defaultIfNull; @@ -64,6 +64,8 @@ import static org.ngrinder.common.constant.CacheConstants.DIST_MAP_NAME_SAMPLING; import static org.ngrinder.common.constant.ClusterConstants.PROP_CLUSTER_SAFE_DIST; import static org.ngrinder.common.util.AccessUtils.getSafe; +import static org.ngrinder.common.util.LoggingUtils.format; +import static org.ngrinder.common.util.TypeConvertUtils.cast; import static org.ngrinder.model.Status.*; /** @@ -174,10 +176,9 @@ private boolean canExecuteMore() { } private boolean isScheduledNow(PerfTest test) { - Date current = new Date(); - Date scheduledDate = DateUtils - .truncate((Date) defaultIfNull(test.getScheduledTime(), current), Calendar.MINUTE); - return current.after(scheduledDate); + Instant now = now(); + Instant scheduledTime = cast(defaultIfNull(test.getScheduledTime(), now)); + return (now.truncatedTo(MINUTES).getEpochSecond() - scheduledTime.truncatedTo(MINUTES).getEpochSecond()) >= 0; } /** @@ -187,7 +188,7 @@ private boolean isScheduledNow(PerfTest test) { * @return true if enough agents */ protected boolean hasEnoughFreeAgents(PerfTest test) { - int size = agentService.getAllAttachedFreeApprovedAgentsForUser(test.getCreatedUser().getUserId()).size(); + int size = agentService.getAllAttachedFreeApprovedAgentsForUser(test.getCreatedBy().getUserId()).size(); if (test.getAgentCount() != null && test.getAgentCount() > size) { perfTestService.markProgress(test, "The test is tried to execute but there is not enough free agents." + "\n- Current free agent count : " + size + " / Requested : " + test.getAgentCount() + "\n"); @@ -213,17 +214,19 @@ public void doTest(final PerfTest perfTest) { singleConsole.setReportPath(perfTestService.getReportFileDirectory(perfTest)); runTestOn(perfTest, grinderProperties, checkCancellation(singleConsole)); } catch (PerfTestPrepareException ex) { + LOG.error(format(perfTest, "Error while preparing a test : {} ", ex.getMessage())); perfTestService.markProgressAndStatusAndFinishTimeAndStatistics(perfTest, Status.STOP_BY_ERROR, ex.getMessage()); } catch (SingleConsoleCancellationException ex) { // In case of error, mark the occurs error on perftest. - doCancel(perfTest, singleConsole); + LOG.error(format(perfTest, "Error while preparing a single console : {} ", ex.getMessage())); + doCancel(perfTest, requireNonNull(singleConsole)); notifyFinish(perfTest, StopReason.CANCEL_BY_USER); - } catch (Exception e) { + } catch (Exception ex) { // In case of error, mark the occurs error on perftest. - LOG.error("Error while executing test: {} - {} ", perfTest.getTestIdentifier(), e.getMessage()); - LOG.debug("Stack Trace is : ", e); - doTerminate(perfTest, singleConsole, e.getMessage()); + LOG.error(format(perfTest, "Error while executing a test: {}", ex.getMessage())); + LOG.debug("Stack Trace is : ", ex); + doTerminate(perfTest, singleConsole, ex.getMessage()); notifyFinish(perfTest, StopReason.ERROR_WHILE_PREPARE); } } @@ -273,6 +276,7 @@ private void prepareFileDistribution(PerfTest perfTest, SingleConsole singleCons Set distFilesDigest = getFilesDigest(distDir, distFiles); singleConsole.sendDistFilesDigestToAgents(distFilesDigest); + LOG.info(format(perfTest, "Send digest of distribution files to agent for refresh agent's cache directory.")); deleteCachedDistFiles(distDir, distFiles, distFilesDigest, singleConsole.getAgentCachedDistFilesDigestList()); } @@ -326,6 +330,7 @@ public void distributed(String fileName) { perfTestService.markProgress(perfTest, " - " + fileName); } + @SuppressWarnings("ConstantConditions") @Override public boolean start(File dir, boolean safe) { if (safe) { @@ -372,7 +377,7 @@ void startAgentsOn(PerfTest perfTest, GrinderProperties grinderProperties, Singl int agentCount = perfTest.getAgentCount(); perfTestService.markStatusAndProgress(perfTest, START_AGENTS, getSafe(agentCount) + " agents are starting."); - agentService.runAgent(perfTest.getCreatedUser(), singleConsole, grinderProperties, getSafe(agentCount)); + agentService.runAgent(perfTest, singleConsole, grinderProperties, getSafe(agentCount)); singleConsole.waitUntilAgentPrepared(agentCount); perfTestService.markStatusAndProgress(perfTest, START_AGENTS_FINISHED, getSafe(agentCount) + " agents are ready."); @@ -395,19 +400,21 @@ void runTestOn(final PerfTest perfTest, GrinderProperties grinderProperties, fin // Run test perfTestService.markStatusAndProgress(perfTest, START_TESTING, "The test is ready to start."); // Add listener to detect abnormal condition and mark the perfTest - singleConsole.addListener(new ConsoleShutdownListener() { - @Override - public void readyToStop(StopReason stopReason) { + + singleConsole.addListener(stopReason -> { + PerfTest fetchedPerftest = perfTestService.getOne(perfTest.getId()); + if (fetchedPerftest.getStatus().isStoppable()) { perfTestService.markAbnormalTermination(perfTest, stopReason); - LOG.error("Abnormal test {} due to {}", perfTest.getId(), stopReason.name()); + LOG.error(format(perfTest, "Abnormal test due to {}", stopReason.name())); } }); + long startTime = singleConsole.startTest(grinderProperties); - perfTest.setStartTime(new Date(startTime)); + perfTest.setStartTime(ofEpochMilli(startTime)); addSamplingListeners(perfTest, singleConsole); perfTestService.markStatusAndProgress(perfTest, TESTING, "The test is started."); singleConsole.startSampling(); - + LOG.info(format(perfTest, "Sampling is started")); } protected void addSamplingListeners(final PerfTest perfTest, final SingleConsole singleConsole) { @@ -415,7 +422,7 @@ protected void addSamplingListeners(final PerfTest perfTest, final SingleConsole singleConsole.addSamplingLifeCycleListener(new PerfTestSamplingCollectorListener(singleConsole, perfTest.getId(), perfTestService, scheduledTaskService)); singleConsole.addSamplingLifeCycleListener(new AgentLostDetectionListener(singleConsole, perfTest, - perfTestService, scheduledTaskService));; + perfTestService, scheduledTaskService)); List testSamplingPlugins = pluginManager.getEnabledModulesByClass (OnTestSamplingRunnable.class, asList(new MonitorCollectorPlugin(config, scheduledTaskService, perfTestService, perfTest.getId()), new TooManyErrorCheckPlugin())); @@ -467,17 +474,17 @@ protected void doFinish(boolean initial) { void doFinish() { for (PerfTest each : perfTestService.getAllAbnormalTesting()) { - LOG.info("Terminate {}", each.getId()); SingleConsole consoleUsingPort = consoleManager.getConsoleUsingPort(each.getPort()); doTerminate(each, consoleUsingPort); + LOG.info(format(each, "Abnormal test is terminated.", each.getId())); cleanUp(each); notifyFinish(each, StopReason.TOO_MANY_ERRORS); } for (PerfTest each : perfTestService.getAllStopRequested()) { - LOG.info("Stop test {}", each.getId()); SingleConsole consoleUsingPort = consoleManager.getConsoleUsingPort(each.getPort()); doCancel(each, consoleUsingPort); + LOG.info(format(each, "Test is Stopped.")); cleanUp(each); notifyFinish(each, StopReason.CANCEL_BY_USER); } @@ -486,6 +493,7 @@ void doFinish() { SingleConsole consoleUsingPort = consoleManager.getConsoleUsingPort(each.getPort()); if (isTestFinishCandidate(each, consoleUsingPort)) { doNormalFinish(each, consoleUsingPort); + LOG.info(format(each, "Test is finished.", each.getId())); cleanUp(each); notifyFinish(each, StopReason.NORMAL); } @@ -514,24 +522,20 @@ private boolean isTestFinishCandidate(PerfTest perfTest, SingleConsole singleCon // Give 5 seconds to be finished if (perfTest.isThresholdDuration() && singleConsoleInUse.isCurrentRunningTimeOverDuration(perfTest.getDuration())) { - LOG.debug( - "Test {} is ready to finish. Current : {}, Planned : {}", - perfTest.getTestIdentifier(), singleConsoleInUse.getCurrentRunningTime(), - perfTest.getDuration()); + LOG.debug(format(perfTest, + "Test is ready to finish. Current : {}, Planned : {}", + singleConsoleInUse.getCurrentRunningTime(), perfTest.getDuration())); return true; } else if (perfTest.isThresholdRunCount() && singleConsoleInUse.getCurrentExecutionCount() >= perfTest.getTotalRunCount()) { - LOG.debug("Test {} is ready to finish. Current : {}, Planned : {}", - perfTest.getTestIdentifier(), singleConsoleInUse.getCurrentExecutionCount(), - perfTest.getTotalRunCount()); + LOG.debug(format(perfTest, "Test is ready to finish. Current : {}, Planned : {}", + singleConsoleInUse.getCurrentExecutionCount(), perfTest.getTotalRunCount())); return true; } else if (singleConsoleInUse instanceof NullSingleConsole) { - LOG.debug("Test {} is ready to finish. Current : {}, Planned : {}", - perfTest.getTestIdentifier(), singleConsoleInUse.getCurrentExecutionCount(), - perfTest.getTotalRunCount()); + LOG.debug(format(perfTest, "Test is ready to finish. Current : {}, Planned : {}", + singleConsoleInUse.getCurrentExecutionCount(), perfTest.getTotalRunCount())); return true; } - return false; } @@ -543,14 +547,15 @@ private boolean isTestFinishCandidate(PerfTest perfTest, SingleConsole singleCon * {@link PerfTest} */ public void doCancel(PerfTest perfTest, SingleConsole singleConsoleInUse) { - LOG.info("Cancel test {} by user request.", perfTest.getId()); + LOG.info(format(perfTest, "Cancel test.")); singleConsoleInUse.unregisterSampling(); + LOG.info(format(perfTest, "Sampling is stopped")); try { perfTestService.markProgressAndStatusAndFinishTimeAndStatistics(perfTest, CANCELED, "Stop requested by user"); } catch (Exception e) { - LOG.error("Error while canceling test {} : {}", perfTest.getId(), e.getMessage()); - LOG.debug("Details : ", e); + LOG.error(format(perfTest,"Error while canceling test : {}", e.getMessage())); + LOG.debug(format(perfTest, "Details : "), e); } consoleManager.returnBackConsole(perfTest.getTestIdentifier(), singleConsoleInUse); } @@ -568,7 +573,10 @@ public void doTerminate(PerfTest perfTest, SingleConsole singleConsoleInUse) { * @param errorMessage error message */ public void doTerminate(PerfTest perfTest, SingleConsole singleConsoleInUse, String errorMessage) { - singleConsoleInUse.unregisterSampling(); + if (singleConsoleInUse != null) { + singleConsoleInUse.unregisterSampling(); + LOG.info(format(perfTest, "Sampling is stopped")); + } String progressMessage = "Stopped by error"; if (!errorMessage.isEmpty()) { @@ -579,8 +587,8 @@ public void doTerminate(PerfTest perfTest, SingleConsole singleConsoleInUse, Str perfTestService.markProgressAndStatusAndFinishTimeAndStatistics(perfTest, Status.STOP_BY_ERROR, progressMessage); } catch (Exception e) { - LOG.error("Error while terminating {} : {}", perfTest.getTestIdentifier(), e.getMessage()); - LOG.debug("Details : ", e); + LOG.error(format(perfTest, "Error while terminating : {}", e.getMessage())); + LOG.debug(format(perfTest, "Details : "), e); } consoleManager.returnBackConsole(perfTest.getTestIdentifier(), singleConsoleInUse); } @@ -593,9 +601,9 @@ public void doTerminate(PerfTest perfTest, SingleConsole singleConsoleInUse, Str * {@link PerfTest} */ public void doNormalFinish(PerfTest perfTest, SingleConsole singleConsoleInUse) { - LOG.debug("PerfTest {} status - currentRunningTime {} ", perfTest.getId(), - singleConsoleInUse.getCurrentRunningTime()); + LOG.debug(format(perfTest, "PerfTest status - currentRunningTime {} ", singleConsoleInUse.getCurrentRunningTime())); singleConsoleInUse.unregisterSampling(); + LOG.info(format(perfTest, "Sampling is stopped")); try { // stop target host monitor if (perfTestService.hasTooManyError(perfTest)) { @@ -610,8 +618,8 @@ public void doNormalFinish(PerfTest perfTest, SingleConsole singleConsoleInUse) } } catch (Exception e) { perfTestService.markStatusAndProgress(perfTest, Status.STOP_BY_ERROR, e.getMessage()); - LOG.error("Error while finishing {} : {}", perfTest.getTestIdentifier(), e.getMessage()); - LOG.debug("Details : ", e); + LOG.error(format(perfTest, "Error while finishing : {}", e.getMessage())); + LOG.debug(format(perfTest, "Details : "), e); } consoleManager.returnBackConsole(perfTest.getTestIdentifier(), singleConsoleInUse); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java index 86c470fd6d..89a0c1388e 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java @@ -27,7 +27,6 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.lang.BooleanUtils; @@ -72,7 +71,10 @@ import java.util.*; import java.util.Map.Entry; +import static java.lang.Long.parseLong; import static java.lang.Long.valueOf; +import static java.time.Instant.now; +import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; import static org.apache.commons.io.FileUtils.deleteQuietly; import static java.util.Arrays.asList; @@ -84,12 +86,12 @@ import static org.ngrinder.common.util.AopUtils.proxy; import static org.ngrinder.common.util.CollectionUtils.*; import static org.ngrinder.common.util.ExceptionUtils.processException; +import static org.ngrinder.common.util.LoggingUtils.format; import static org.ngrinder.common.util.NoOp.noOp; import static org.ngrinder.common.util.Preconditions.checkNotEmpty; import static org.ngrinder.common.util.Preconditions.checkNotNull; import static org.ngrinder.common.util.TypeConvertUtils.cast; -import static org.ngrinder.model.Status.PREPARE_DISTRIBUTION; -import static org.ngrinder.model.Status.getProcessingOrTestingTestStatus; +import static org.ngrinder.model.Status.*; import static org.ngrinder.perftest.repository.PerfTestSpecification.*; /** @@ -99,6 +101,7 @@ * * @since 3.0 */ +@SuppressWarnings({"ResultOfMethodCallIgnored", "BooleanMethodIsAlwaysInverted", "UnusedReturnValue", "SameParameterValue", "ConstantConditions"}) @RequiredArgsConstructor public class PerfTestService extends AbstractPerfTestService implements ControllerConstants, GrinderConstants { @@ -200,7 +203,7 @@ public List getAll(User user, Long[] ids) { if (user.getRole().equals(Role.USER)) { spec = spec.and(createdBy(user)); } - spec = spec.and(idSetEqual(ids)); + spec = requireNonNull(spec).and(idSetEqual(ids)); return perfTestRepository.findAll(spec); } @@ -230,7 +233,7 @@ public List getAll(User user, Status[] statuses) { spec = spec.and(createdBy(user)); } if (statuses.length != 0) { - spec = spec.and(statusSetEqual(statuses)); + spec = requireNonNull(spec).and(statusSetEqual(statuses)); } return perfTestRepository.findAll(spec); @@ -376,7 +379,7 @@ public PerfTest markProgressAndStatus(PerfTest perfTest, Status status, String m */ @Transactional public PerfTest markProgressAndStatusAndFinishTimeAndStatistics(PerfTest perfTest, Status status, String message) { - perfTest.setFinishTime(new Date()); + perfTest.setFinishTime(now()); updatePerfTestAfterTestFinish(perfTest); return markProgressAndStatus(perfTest, status, message); } @@ -446,10 +449,10 @@ protected List filterCurrentlyRunningTestUsersTest(List perf List currentlyRunningTests = getCurrentlyRunningTest(); final Set currentlyRunningTestOwners = newHashSet(); for (PerfTest each : currentlyRunningTests) { - currentlyRunningTestOwners.add(each.getCreatedUser()); + currentlyRunningTestOwners.add(each.getCreatedBy()); } return perfTestLists.stream() - .filter(perfTest -> !currentlyRunningTestOwners.contains(perfTest.getCreatedUser())) + .filter(perfTest -> !currentlyRunningTestOwners.contains(perfTest.getCreatedBy())) .collect(toList()); } @@ -560,7 +563,7 @@ public GrinderProperties getGrinderProperties(PerfTest perfTest, ScriptHandler s // Use default properties first GrinderProperties grinderProperties = new GrinderProperties(config.getHome().getDefaultGrinderProperties()); - User user = perfTest.getCreatedUser(); + User user = perfTest.getCreatedBy(); // Get all files in the script path String scriptName = perfTest.getScriptName(); @@ -584,9 +587,7 @@ public GrinderProperties getGrinderProperties(PerfTest perfTest, ScriptHandler s grinderProperties.setInt(GRINDER_PROP_RUNS, 0); } else { grinderProperties.setInt(GRINDER_PROP_RUNS, getSafe(perfTest.getRunCount())); - if (grinderProperties.containsKey(GRINDER_PROP_DURATION)) { - grinderProperties.remove(GRINDER_PROP_DURATION); - } + grinderProperties.remove(GRINDER_PROP_DURATION); } grinderProperties.setProperty(GRINDER_PROP_ETC_HOSTS, StringUtils.defaultIfBlank(perfTest.getTargetHosts(), "")); @@ -607,7 +608,7 @@ public GrinderProperties getGrinderProperties(PerfTest perfTest, ScriptHandler s grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, 0); } grinderProperties.setInt(GRINDER_PROP_REPORT_TO_CONSOLE, 500); - grinderProperties.setProperty(GRINDER_PROP_USER, perfTest.getCreatedUser().getUserId()); + grinderProperties.setProperty(GRINDER_PROP_USER, perfTest.getCreatedBy().getUserId()); grinderProperties.setProperty(GRINDER_PROP_JVM_USER_LIBRARY_CLASSPATH, geUserLibraryClassPath(perfTest)); grinderProperties.setInt(GRINDER_PROP_IGNORE_SAMPLE_COUNT, getSafe(perfTest.getIgnoreSampleCount())); grinderProperties.setBoolean(GRINDER_PROP_SECURITY, config.isSecurityEnabled()); @@ -626,7 +627,7 @@ public GrinderProperties getGrinderProperties(PerfTest perfTest, ScriptHandler s grinderProperties.setProperty(GRINDER_PROP_JVM_ARGUMENTS, property); } } - LOGGER.info("Grinder Properties : {} ", grinderProperties); + LOGGER.info(format(perfTest, "Grinder Properties : {} ", grinderProperties)); return grinderProperties; } catch (Exception e) { throw processException("error while prepare grinder property for " + perfTest.getTestName(), e); @@ -642,7 +643,7 @@ public GrinderProperties getGrinderProperties(PerfTest perfTest, ScriptHandler s */ public ScriptHandler prepareDistribution(PerfTest perfTest) throws IOException { File perfTestDistDirectory = getDistributionPath(perfTest); - User user = perfTest.getCreatedUser(); + User user = perfTest.getCreatedBy(); String scm = perfTest.getScm(); FileEntry scriptEntry; @@ -656,7 +657,7 @@ public ScriptHandler prepareDistribution(PerfTest perfTest) throws IOException { String scriptName = perfTest.getScriptName(); gitHubFileEntryService.checkoutGitHubScript(perfTest, ghRepository, gitHubConfig); scriptEntry = gitHubFileEntryService.getOne(ghRepository, gitHubConfig, scriptName); - gitHubFileEntryService.evictGitHubMavenGroovyCache(ghRepository, scriptName, gitHubConfig.getBranch()); + gitHubFileEntryService.evictGitHubGroovyProjectScriptTypeCache(ghRepository, scriptName, gitHubConfig.getBranch()); } else { scriptEntry = checkNotNull( fileEntryService.getOne(user, @@ -666,12 +667,12 @@ public ScriptHandler prepareDistribution(PerfTest perfTest) throws IOException { // Get all files in the script path. ScriptHandler handler = scriptHandlerFactory.getHandler(scriptEntry); - LOGGER.info("Script type is '{}'.", handler.getKey()); + LOGGER.info(format(perfTest, "Script type is '{}'.", handler.getKey())); ProcessingResultPrintStream processingResult = new ProcessingResultPrintStream(new ByteArrayOutputStream()); - handler.prepareDist(perfTest.getId(), user, scriptEntry, perfTestDistDirectory, config.getControllerProperties(), + handler.prepareDist(perfTest, user, scriptEntry, perfTestDistDirectory, config.getControllerProperties(), processingResult); - LOGGER.info("File write is completed in {}", perfTestDistDirectory); + LOGGER.info(format(perfTest, "File write is completed in {}", perfTestDistDirectory)); if (!processingResult.isSuccess()) { File logDir = new File(getLogFileDirectory(perfTest), "distribution_log.txt"); try { @@ -679,7 +680,8 @@ public ScriptHandler prepareDistribution(PerfTest perfTest) throws IOException { } catch (IOException e) { noOp(); } - throw processException("Error while file distribution is prepared."); + throw processException("Error while file distribution is prepared.\n" + + "If you run groovy project type script, Please check your build script and make sure Maven or Gradle is installed."); } return handler; } @@ -762,25 +764,14 @@ public int getReportDataInterval(long testId, String dataType, int imgWidth) { LOGGER.warn("Report {} for test {} does not exist.", dataType, testId); return 0; } - LineNumberReader lnr = null; - FileInputStream in = null; - InputStreamReader isr = null; - try { - in = new FileInputStream(targetFile); - isr = new InputStreamReader(in); - lnr = new LineNumberReader(isr); + try (LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(targetFile)))) { lnr.skip(targetFile.length()); int lineNumber = lnr.getLineNumber() + 1; interval = Math.max(lineNumber / pointCount, 1); } catch (Exception e) { LOGGER.error("Failed to get report data for {}", dataType, e); - } finally { - IOUtils.closeQuietly(lnr); - IOUtils.closeQuietly(isr); - IOUtils.closeQuietly(in); } - return interval; } @@ -838,7 +829,7 @@ public List getLogFiles(long testId) { if (!logFileDirectory.exists() || !logFileDirectory.isDirectory()) { return Collections.emptyList(); } - return asList(logFileDirectory.list()); + return asList(requireNonNull(logFileDirectory.list())); } /** @@ -983,7 +974,7 @@ public void updatePerfTestAfterTestFinish(PerfTest perfTest) { Map result = consoleManager.getConsoleUsingPort(perfTest.getPort()).getStatisticsData(); @SuppressWarnings("unchecked") Map totalStatistics = MapUtils.getMap(result, "totalStatistics", MapUtils.EMPTY_MAP); - LOGGER.info("Total Statistics for test {} is {}", perfTest.getId(), totalStatistics); + LOGGER.info(format(perfTest, "Total Statistics is {}", totalStatistics)); perfTest.setTps(parseDoubleWithSafety(totalStatistics, "TPS", 0D)); perfTest.setMeanTestTime(parseDoubleWithSafety(totalStatistics, "Mean_Test_Time_(ms)", 0D)); perfTest.setPeakTps(parseDoubleWithSafety(totalStatistics, "Peak_TPS", 0D)); @@ -1032,7 +1023,6 @@ public void stop(User user, Long id) { // This will be not be effective on cluster mode. consoleManager.getConsoleUsingPort(perfTest.getPort()).cancel(); perfTest.setStopRequest(true); - perfTestRepository.save(perfTest); } /** @@ -1044,7 +1034,7 @@ public void stop(User user, Long id) { * @return true if it has */ public boolean hasPermission(PerfTest perfTest, User user, Permission type) { - return perfTest != null && (user.getRole().hasPermission(type) || user.equals(perfTest.getCreatedUser())); + return perfTest != null && (user.getRole().hasPermission(type) || user.equals(perfTest.getCreatedBy())); } /* @@ -1079,16 +1069,16 @@ public void addCommentOn(User user, Long testId, String testComment, String tagS * * @return PerfTestStatisticsList PerfTestStatistics list */ - @Cacheable(CACHE_CURRENT_PERFTEST_STATISTICS) + @Cacheable(LOCAL_CACHE_CURRENT_PERFTEST_STATISTICS) @Transactional public Collection getCurrentPerfTestStatistics() { Map perfTestPerUser = newHashMap(); for (PerfTest each : getAll(null, getProcessingOrTestingTestStatus())) { - User lastModifiedUser = each.getCreatedUser().getUserBaseInfo(); - PerfTestStatistics perfTestStatistics = perfTestPerUser.get(lastModifiedUser); + User lastModifiedBy = each.getCreatedBy().getUserBaseInfo(); + PerfTestStatistics perfTestStatistics = perfTestPerUser.get(lastModifiedBy); if (perfTestStatistics == null) { - perfTestStatistics = new PerfTestStatistics(lastModifiedUser); - perfTestPerUser.put(lastModifiedUser, perfTestStatistics); + perfTestStatistics = new PerfTestStatistics(lastModifiedBy); + perfTestPerUser.put(lastModifiedBy, perfTestStatistics); } perfTestStatistics.addPerfTest(each); } @@ -1172,14 +1162,8 @@ public int getMonitorGraphInterval(long testId, String targetIP, int imageWidth) MONITOR_FILE_PREFIX + targetIP + ".data"); int pointCount = Math.max(imageWidth, MAX_POINT_COUNT); - FileInputStream in = null; - InputStreamReader isr = null; - LineNumberReader lnr = null; int interval = 0; - try { - in = new FileInputStream(monitorDataFile); - isr = new InputStreamReader(in); - lnr = new LineNumberReader(isr); + try (LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(monitorDataFile)))) { lnr.skip(monitorDataFile.length()); int lineNumber = lnr.getLineNumber() + 1; interval = Math.max(lineNumber / pointCount, 1); @@ -1187,10 +1171,6 @@ public int getMonitorGraphInterval(long testId, String targetIP, int imageWidth) LOGGER.info("Monitor data file does not exist at {}", monitorDataFile); } catch (IOException e) { LOGGER.info("Error while getting monitor:{} data file:{}", targetIP, monitorDataFile); - } finally { - IOUtils.closeQuietly(lnr); - IOUtils.closeQuietly(isr); - IOUtils.closeQuietly(in); } return interval; } @@ -1207,9 +1187,10 @@ public int getMonitorGraphInterval(long testId, String targetIP, int imageWidth) public Map getMonitorGraph(long testId, String targetIP, int dataInterval) { Map returnMap = Maps.newHashMap(); File monitorDataFile = new File(config.getHome().getPerfTestReportDirectory(String.valueOf(testId)), - MONITOR_FILE_PREFIX + targetIP + ".data"); - BufferedReader br = null; - try { + MONITOR_FILE_PREFIX + targetIP + ".data"); + + try (BufferedReader br = new BufferedReader(new FileReader(monitorDataFile))) { + List userMemoryMetrics = new ArrayList<>(); List cpuUsedMetrics = new ArrayList<>(); List networkReceivedMetrics = new ArrayList<>(); @@ -1220,7 +1201,6 @@ public Map getMonitorGraph(long testId, String targetIP, int dat List customData4Metrics = new ArrayList<>(); List customData5Metrics = new ArrayList<>(); - br = new BufferedReader(new FileReader(monitorDataFile)); br.readLine(); // skip the header. // "ip,system,collectTime,freeMemory,totalMemory,cpuUsedPercentage,receivedPerSec,sentPerSec" String line = br.readLine(); @@ -1237,7 +1217,7 @@ public Map getMonitorGraph(long testId, String targetIP, int dat if (NULL_STRING.equals(dataList[4]) || UNDEFINED_STRING.equals(dataList[4])) { userMemoryMetrics.add(null); } else { - userMemoryMetrics.add(valueOf(dataList[4]) - valueOf(dataList[3])); + userMemoryMetrics.add(parseLong(dataList[4]) - parseLong(dataList[3])); } addCustomData(cpuUsedMetrics, 5, dataList); addCustomData(networkReceivedMetrics, 6, dataList); @@ -1260,9 +1240,8 @@ public Map getMonitorGraph(long testId, String targetIP, int dat returnMap.put("customData5", customData5Metrics); } catch (IOException e) { LOGGER.info("Error while getting monitor {} data file at {}", targetIP, monitorDataFile); - } finally { - IOUtils.closeQuietly(br); } + return returnMap; } @@ -1336,14 +1315,8 @@ private File getReportPluginDataFile(Long testId, String plugin, String kind) { */ private int getRecordInterval(int imageWidth, File dataFile) { int pointCount = Math.max(imageWidth, MAX_POINT_COUNT); - FileInputStream in = null; - InputStreamReader isr = null; - LineNumberReader lnr = null; int interval = 0; - try { - in = new FileInputStream(dataFile); - isr = new InputStreamReader(in); - lnr = new LineNumberReader(isr); + try (LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(dataFile)))) { lnr.skip(dataFile.length()); interval = Math.max((lnr.getLineNumber() + 1) / pointCount, 1); } catch (FileNotFoundException e) { @@ -1352,10 +1325,6 @@ private int getRecordInterval(int imageWidth, File dataFile) { } catch (IOException e) { LOGGER.error("Error while getting data file:{}", dataFile); LOGGER.error(e.getMessage(), e); - } finally { - IOUtils.closeQuietly(lnr); - IOUtils.closeQuietly(isr); - IOUtils.closeQuietly(in); } return interval; } @@ -1373,11 +1342,10 @@ private int getRecordInterval(int imageWidth, File dataFile) { public Map getReportPluginGraph(long testId, String plugin, String kind, int interval) { Map returnMap = Maps.newHashMap(); File pluginDataFile = getReportPluginDataFile(testId, plugin, kind); - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(pluginDataFile)); - String header = br.readLine(); + try (BufferedReader br = new BufferedReader(new FileReader(pluginDataFile))) { + + String header = br.readLine(); StringBuilder headerSB = new StringBuilder("["); String[] headers = StringUtils.split(header, ","); String[] refinedHeaders = StringUtils.split(header, ","); @@ -1422,9 +1390,8 @@ public Map getReportPluginGraph(long testId, String plugin, Stri } catch (IOException e) { LOGGER.error("Error while getting monitor: {} data file:{}", plugin, pluginDataFile); LOGGER.error(e.getMessage(), e); - } finally { - IOUtils.closeQuietly(br); } + return returnMap; } @@ -1480,7 +1447,7 @@ public List getReportDataFiles(long testId, String key) { File reportFolder = config.getHome().getPerfTestReportDirectory(String.valueOf(testId)); FileFilter fileFilter = new WildcardFileFilter(key + "*.data"); File[] files = reportFolder.listFiles(fileFilter); - return Arrays.stream(files) + return Arrays.stream(requireNonNull(files)) .sorted(Comparator.comparing(o -> FilenameUtils.getBaseName(o.getName()))) .collect(toList()); } @@ -1491,9 +1458,7 @@ private List getFileDataAsList(File targetFile, int interval) { } List metrics = new ArrayList<>(); - try (FileReader reader = new FileReader(targetFile); - BufferedReader br = new BufferedReader(reader);){ - + try (BufferedReader br = new BufferedReader(new FileReader(targetFile))) { String data = br.readLine(); int current = 0; while (StringUtils.isNotBlank(data)) { @@ -1523,7 +1488,7 @@ private List getFileDataAsList(File targetFile, int interval) { */ @Override public List getAll(Date start, Date end) { - return perfTestRepository.findAllByCreatedTime(start, end); + return perfTestRepository.findAllByCreatedAt(start, end); } /* @@ -1533,7 +1498,7 @@ public List getAll(Date start, Date end) { */ @Override public List getAll(Date start, Date end, String region) { - return perfTestRepository.findAllByCreatedTimeAndRegion(start, end, region); + return perfTestRepository.findAllByCreatedAtAndRegion(start, end, region); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/TagService.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/TagService.java index 22302a03ce..1c9462c691 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/TagService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/TagService.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; @@ -24,8 +24,11 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.time.Instant; import java.util.*; +import static java.time.Instant.now; +import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; import static org.ngrinder.perftest.repository.TagSpecification.*; @@ -33,9 +36,9 @@ /** * Tag Service. Tag support which is used to categorize {@link PerfTest} - * + * * @since 3.0 - * + * */ @Service @RequiredArgsConstructor @@ -47,7 +50,7 @@ public class TagService { /** * Add tags. - * + * * @param user user * @param tags tag string list * @return inserted tags @@ -75,7 +78,7 @@ public SortedSet addTags(User user, String[] tags) { /** * Get all tags which belongs to given user and start with given string. - * + * * @param user user * @param startWith string * @return found tags @@ -84,14 +87,14 @@ public List getAllTags(User user, String startWith) { Specification spec = Specification.where(hasPerfTest()); spec = spec.and(lastModifiedOrCreatedBy(user)); if (StringUtils.isNotBlank(startWith)) { - spec = spec.and(isStartWith(StringUtils.trimToEmpty(startWith))); + spec = requireNonNull(spec).and(isStartWith(StringUtils.trimToEmpty(startWith))); } return tagRepository.findAll(spec); } /** * Get all tags which belongs to given user and start with given string. - * + * * @param user user * @param query query string * @return found tag string lists @@ -106,28 +109,29 @@ public List getAllTagStrings(User user, String query) { /** * Save Tag. Because this method can be called in {@link TagService} internally, so created user * / data should be set directly. - * + * * @param user user * @param tag tag * @return saved {@link Tag} instance */ public Tag saveTag(User user, Tag tag) { - Date createdDate = new Date(); - if (tag.getCreatedUser() == null) { - tag.setCreatedUser(user); - tag.setCreatedDate(createdDate); + Instant createdAt = now(); + if (tag.getCreatedBy() == null) { + tag.setCreatedBy(user); + tag.setCreatedAt(createdAt); } - tag.setLastModifiedUser(user); - tag.setLastModifiedDate(createdDate); + tag.setLastModifiedBy(user); + tag.setLastModifiedAt(createdAt); return tagRepository.save(tag); } /** * Delete a tag. - * + * * @param user user * @param tag tag */ + @SuppressWarnings("unused") @Transactional public void deleteTag(User user, Tag tag) { for (PerfTest each : tag.getPerfTests()) { @@ -139,7 +143,7 @@ public void deleteTag(User user, Tag tag) { /** * Delete all tags belonging to given user. - * + * * @param user user */ @Transactional diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/monitor/MonitorClientService.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/monitor/MonitorClientService.java index 7d8bdb75ca..38d664cde2 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/monitor/MonitorClientService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/monitor/MonitorClientService.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service.monitor; @@ -48,9 +48,9 @@ public class MonitorClientService implements Closeable, MonitorConstants { } } - private String ip; - - private int port; + private final String ip; + private final int port; + private SystemInfo systemInfo = SystemInfo.NullSystemInfo.getNullSystemInfo(); private long lastAccessedTime; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/AgentLostDetectionListener.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/AgentLostDetectionListener.java index ddd37b99dd..e24a4081ce 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/AgentLostDetectionListener.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/AgentLostDetectionListener.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service.samplinglistener; @@ -44,17 +44,14 @@ public class AgentLostDetectionListener implements SamplingLifeCycleListener { public AgentLostDetectionListener(final SingleConsole singleConsole, final PerfTest perfTest, final PerfTestService perfTestService, ScheduledTaskService scheduledTaskService) { this.scheduledTaskService = scheduledTaskService; - this.runnable = new Runnable() { - @Override - public void run() { - if (singleConsole.getAllAttachedAgentsCount() == 0) { - if (lostAgentDetectionTrial++ > 10) { - perfTestService.markStatusAndProgress(perfTest, Status.ABNORMAL_TESTING, - "[ERROR] All agents are unexpectedly lost."); - } - } else { - lostAgentDetectionTrial = 0; + this.runnable = () -> { + if (singleConsole.getAllAttachedAgentsCount() == 0) { + if (lostAgentDetectionTrial++ > 10) { + perfTestService.markStatusAndProgress(perfTest, Status.ABNORMAL_TESTING, + "[ERROR] All agents are unexpectedly lost."); } + } else { + lostAgentDetectionTrial = 0; } }; } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/MonitorCollectorPlugin.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/MonitorCollectorPlugin.java index 2c1142cc72..1a269acd82 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/MonitorCollectorPlugin.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/MonitorCollectorPlugin.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,12 +9,11 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service.samplinglistener; import net.grinder.statistics.ImmutableStatisticsSet; -import org.apache.commons.io.IOUtils; import org.ngrinder.common.constant.ControllerConstants; import org.ngrinder.common.constants.MonitorConstants; import org.ngrinder.extension.OnTestSamplingRunnable; @@ -40,6 +39,7 @@ import static org.apache.commons.io.IOUtils.closeQuietly; import static org.ngrinder.common.util.CollectionUtils.newHashMap; +import static org.ngrinder.common.util.LoggingUtils.format; /** * Monitor data collector plugin. @@ -48,12 +48,13 @@ */ public class MonitorCollectorPlugin implements OnTestSamplingRunnable, Runnable, MonitorConstants { private static final Logger LOGGER = LoggerFactory.getLogger(MonitorCollectorPlugin.class); + + private final Map clientMap = new ConcurrentHashMap<>(); private final int port; - private Map clientMap = new ConcurrentHashMap<>(); + private final Long perfTestId; private final IScheduledTaskService scheduledTaskService; private final PerfTestService perfTestService; - private Long perfTestId; /** * Constructor. @@ -79,29 +80,24 @@ public void startSampling(final ISingleConsole singleConsole, PerfTest perfTest, final List targetHostIP = perfTest.getTargetHostIP(); final Integer samplingInterval = perfTest.getSamplingInterval(); for (final String target : targetHostIP) { - scheduledTaskService.runAsync(new Runnable() { - @Override - public void run() { - LOGGER.info("Start JVM monitoring for IP:{}", target); - MonitorClientService client = new MonitorClientService(target, MonitorCollectorPlugin.this.port); - client.init(); - if (client.isConnected()) { - File testReportDir = singleConsole.getReportPath(); - File dataFile = null; - FileWriter fw = null; - BufferedWriter bw = null; - try { - dataFile = new File(testReportDir, MONITOR_FILE_PREFIX + target + ".data"); - fw = new FileWriter(dataFile, false); - bw = new BufferedWriter(fw); - // write header info - bw.write(SystemInfo.HEADER); - bw.newLine(); - bw.flush(); - clientMap.put(client, bw); - } catch (IOException e) { - LOGGER.error("Error to write to file:{}, Error:{}", dataFile.getPath(), e.getMessage()); - } + scheduledTaskService.runAsync(() -> { + LOGGER.info(format(perfTest, "Start JVM monitoring for IP:{}", target)); + MonitorClientService client = new MonitorClientService(target, MonitorCollectorPlugin.this.port); + client.init(); + if (client.isConnected()) { + File testReportDir = singleConsole.getReportPath(); + File dataFile = null; + BufferedWriter bw; + try { + dataFile = new File(testReportDir, MONITOR_FILE_PREFIX + target + ".data"); + bw = new BufferedWriter(new FileWriter(dataFile, false)); + // write header info + bw.write(SystemInfo.HEADER); + bw.newLine(); + bw.flush(); + clientMap.put(client, bw); + } catch (IOException e) { + LOGGER.error(format(perfTest, "Error to write to file: {}, Error: {}", dataFile.getPath(), e.getMessage())); } } }); @@ -122,7 +118,7 @@ public void sampling(ISingleConsole singleConsole, PerfTest perfTest, IPerfTestS bw.write(currentInfo.toRecordString()); bw.newLine(); } catch (IOException e) { - LOGGER.error("Error while saving file :" + e.getMessage()); + LOGGER.error(format(perfTest, "Error while saving file: {}", e.getMessage())); } } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/PerfTestSamplingCollectorListener.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/PerfTestSamplingCollectorListener.java index fc5afb554d..955c4209a3 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/PerfTestSamplingCollectorListener.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/PerfTestSamplingCollectorListener.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service.samplinglistener; @@ -28,7 +28,7 @@ */ public class PerfTestSamplingCollectorListener implements SamplingLifeCycleListener { private final ScheduledTaskService scheduledTaskService; - private Runnable runnable; + private final Runnable runnable; /** * Constructor. diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/TooManyErrorCheckPlugin.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/TooManyErrorCheckPlugin.java index 10eb6ad182..6749b8cac1 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/TooManyErrorCheckPlugin.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/TooManyErrorCheckPlugin.java @@ -11,6 +11,7 @@ import org.ngrinder.service.ISingleConsole; import static net.grinder.util.NoOp.noOp; +import static org.ngrinder.common.util.LoggingUtils.format; @Slf4j public class TooManyErrorCheckPlugin implements OnTestSamplingRunnable { @@ -64,8 +65,8 @@ private void checkTooManyError(ISingleConsole singleConsole, if (lastMomentWhenErrorsMoreThanHalfOfTotalTPSValue == 0) { lastMomentWhenErrorsMoreThanHalfOfTotalTPSValue = System.currentTimeMillis(); } else if (isOverLowTpsThreshold()) { - log.warn("Stop the test because the count of test error is more than" - + " half of total tps for last {} seconds.", TOO_MANY_ERROR_TIME / 1000); + log.warn(format(perfTest, "Stop the test because the count of test error is more than" + + " half of total tps for last {} seconds.", TOO_MANY_ERROR_TIME / 1000)); if (perfTest.getStatus() != Status.ABNORMAL_TESTING) { perfTestService.markStatusAndProgress(perfTest, Status.ABNORMAL_TESTING, "Too many errors"); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/region/model/RegionInfo.java b/ngrinder-controller/src/main/java/org/ngrinder/region/model/RegionInfo.java index c3b96ff810..6c7e8328b5 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/region/model/RegionInfo.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/region/model/RegionInfo.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.region.model; @@ -28,13 +28,16 @@ public class RegionInfo implements Serializable { private static final long serialVersionUID = 1L; + + private final Integer controllerPort; + + private String regionName; + @Setter private String ip; - private Integer controllerPort; + @Setter private boolean visible = true; - private String regionName; - /** * Constructor with true visibility. diff --git a/ngrinder-controller/src/main/java/org/ngrinder/region/service/RegionService.java b/ngrinder-controller/src/main/java/org/ngrinder/region/service/RegionService.java index a7eb15239c..68a8f08ec0 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/region/service/RegionService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/region/service/RegionService.java @@ -56,7 +56,7 @@ public class RegionService { private final HazelcastInstance hazelcastInstance; - private Supplier> allRegions = Suppliers.memoizeWithExpiration(new Supplier>() { + private final Supplier> allRegions = Suppliers.memoizeWithExpiration(new Supplier>() { @Override public Map get() { Map regions = Maps.newHashMap(); @@ -73,14 +73,14 @@ public Map get() { } }, REGION_CACHE_TIME_TO_LIVE_SECONDS, TimeUnit.SECONDS); - private Supplier> allRegionNames = Suppliers.memoizeWithExpiration(new Supplier>() { + private final Supplier> allRegionNames = Suppliers.memoizeWithExpiration(new Supplier>() { @Override public List get() { Set members = hazelcastInstance.getCluster().getMembers(); List regionNames = new ArrayList<>(); for (Member member : members) { if (member.getAttributes().containsKey(REGION_ATTR_KEY)) { - regionNames.add((String) member.getAttributes().get(REGION_ATTR_KEY)); + regionNames.add(member.getAttributes().get(REGION_ATTR_KEY)); } } return regionNames; diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/controller/FileEntryApiController.java b/ngrinder-controller/src/main/java/org/ngrinder/script/controller/FileEntryApiController.java index 6d54ee2c06..6fd3c73e4b 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/controller/FileEntryApiController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/controller/FileEntryApiController.java @@ -388,7 +388,7 @@ public void deleteOne(User user, @RemainedPath String path) { @PostMapping("/validate") public String validate(User user, @RequestBody ScriptValidationParams scriptValidationParams) { FileEntry fileEntry = scriptValidationParams.getFileEntry(); - fileEntry.setCreatedUser(user); + fileEntry.setCreatedBy(user); return scriptValidationService.validate(user, fileEntry, false, scriptValidationParams.getHostString()); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/controller/FileEntryController.java b/ngrinder-controller/src/main/java/org/ngrinder/script/controller/FileEntryController.java index fb7ad9c7fc..5bc57e6170 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/controller/FileEntryController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/controller/FileEntryController.java @@ -26,6 +26,7 @@ * * @since 3.0 */ +@SuppressWarnings({"SpringMVCViewInspection", "unused"}) @Controller @RequestMapping("/script") @GlobalControllerModel diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/controller/SvnDavController.java b/ngrinder-controller/src/main/java/org/ngrinder/script/controller/SvnDavController.java index 460475600e..980478ca97 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/controller/SvnDavController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/controller/SvnDavController.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.controller; @@ -40,7 +40,6 @@ import javax.annotation.PostConstruct; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -56,7 +55,7 @@ * * @since 3.0 */ -@SuppressWarnings({"unchecked", "rawtypes"}) +@SuppressWarnings({"unchecked", "rawtypes", "NullableProblems", "SameParameterValue"}) @Controller("svnDavServlet") @RequiredArgsConstructor public class SvnDavController implements HttpRequestHandler, ServletConfig, ServletContextAware { @@ -80,7 +79,7 @@ public void init() { } } - private Map initParam = new HashMap<>(); + private final Map initParam = new HashMap<>(); private DAVConfig myDAVConfig; private ServletContext servletContext; @@ -107,13 +106,10 @@ public ServletConfig getServletConfig() { * * @param request request * @param response response - * @throws ServletException occurs when servlet has a problem. * @throws IOException occurs when file system has a problem. */ @Override - public void handleRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, - IOException { + public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { if (LOGGER.isTraceEnabled()) { logRequest(request); @@ -131,7 +127,7 @@ public void handleRequest(HttpServletRequest request, HttpServletResponse respon StringWriter sw = new StringWriter(); svne.printStackTrace(new PrintWriter(sw)); - /** + /* * truncate status line if it is to long */ String msg = sw.getBuffer().toString(); @@ -163,44 +159,42 @@ public void handleRequest(HttpServletRequest request, HttpServletResponse respon } } - @SuppressWarnings("StringConcatenationInsideStringBufferAppend") private void logRequest(HttpServletRequest request) { - StringBuilder logBuffer = new StringBuilder(); - logBuffer.append('\n'); - logBuffer.append("request.getAuthType(): " + request.getAuthType()); - logBuffer.append('\n'); - logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding()); - logBuffer.append('\n'); - logBuffer.append("request.getContentType(): " + request.getContentType()); - logBuffer.append('\n'); - logBuffer.append("request.getContextPath(): " + request.getContextPath()); - logBuffer.append('\n'); - logBuffer.append("request.getContentLength(): " + request.getContentLength()); - logBuffer.append('\n'); - logBuffer.append("request.getMethod(): " + request.getMethod()); - logBuffer.append('\n'); - logBuffer.append("request.getPathInfo(): " + request.getPathInfo()); - logBuffer.append('\n'); - logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated()); - logBuffer.append('\n'); - logBuffer.append("request.getQueryString(): " + request.getQueryString()); - logBuffer.append('\n'); - logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr()); - logBuffer.append('\n'); - logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost()); - logBuffer.append('\n'); - logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser()); - logBuffer.append('\n'); - logBuffer.append("request.getRequestURI(): " + request.getRequestURI()); - logBuffer.append('\n'); - logBuffer.append("request.getServerName(): " + request.getServerName()); - logBuffer.append('\n'); - logBuffer.append("request.getServerPort(): " + request.getServerPort()); - logBuffer.append('\n'); - logBuffer.append("request.getServletPath(): " + request.getServletPath()); - logBuffer.append('\n'); - logBuffer.append("request.getRequestURL(): " + request.getRequestURL()); - LOGGER.trace(logBuffer.toString()); + String logBuffer = '\n' + + "request.getAuthType(): " + request.getAuthType() + + '\n' + + "request.getCharacterEncoding(): " + request.getCharacterEncoding() + + '\n' + + "request.getContentType(): " + request.getContentType() + + '\n' + + "request.getContextPath(): " + request.getContextPath() + + '\n' + + "request.getContentLength(): " + request.getContentLength() + + '\n' + + "request.getMethod(): " + request.getMethod() + + '\n' + + "request.getPathInfo(): " + request.getPathInfo() + + '\n' + + "request.getPathTranslated(): " + request.getPathTranslated() + + '\n' + + "request.getQueryString(): " + request.getQueryString() + + '\n' + + "request.getRemoteAddr(): " + request.getRemoteAddr() + + '\n' + + "request.getRemoteHost(): " + request.getRemoteHost() + + '\n' + + "request.getRemoteUser(): " + request.getRemoteUser() + + '\n' + + "request.getRequestURI(): " + request.getRequestURI() + + '\n' + + "request.getServerName(): " + request.getServerName() + + '\n' + + "request.getServerPort(): " + request.getServerPort() + + '\n' + + "request.getServletPath(): " + request.getServletPath() + + '\n' + + "request.getRequestURL(): " + request.getRequestURL(); + LOGGER.trace(logBuffer); } /** diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyGradleProjectScriptHandler.java b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyGradleProjectScriptHandler.java new file mode 100644 index 0000000000..e9108f0a57 --- /dev/null +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyGradleProjectScriptHandler.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2012-present NAVER Corp. + * + * This file is part of The nGrinder software distribution. Refer to + * the file LICENSE which is part of The nGrinder distribution for + * licensing details. The nGrinder distribution is available on the + * Internet at https://naver.github.io/ngrinder + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ngrinder.script.handler; + +import org.apache.commons.io.IOUtils; +import org.ngrinder.common.util.PathUtils; +import org.ngrinder.infra.config.Config; +import org.ngrinder.model.User; +import org.ngrinder.script.model.FileEntry; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import static java.lang.System.getenv; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.nio.file.Paths.get; +import static org.apache.commons.io.FileUtils.deleteQuietly; +import static org.apache.commons.io.FilenameUtils.normalize; +import static org.apache.commons.lang.StringUtils.EMPTY; +import static org.apache.commons.lang.StringUtils.isNotEmpty; +import static org.ngrinder.common.util.AccessUtils.getSafe; +import static org.ngrinder.common.util.CollectionUtils.buildMap; +import static org.ngrinder.common.util.ExceptionUtils.processException; +import static org.ngrinder.common.util.UrlUtils.getHost; +import static org.ngrinder.script.model.FileCategory.SCRIPT; +import static org.ngrinder.script.model.FileType.DIR; + +/** + * Groovy gradle project {@link ScriptHandler}. + * + * @since 3.5.3 + */ +@Component +public class GroovyGradleProjectScriptHandler extends GroovyProjectScriptHandler { + + public static final String GRADLE_HOME_ENV_NAME = "GRADLE_HOME"; + + private final String ngrinderHomePath; + private String gradlePath; + + public GroovyGradleProjectScriptHandler(Config config) { + super("groovy_gradle", "", "Groovy Gradle Project", "groovy", "build.gradle", true); + + gradlePath = getSafe(getenv(GRADLE_HOME_ENV_NAME), ""); + if (isNotEmpty(gradlePath)) { + gradlePath += "/bin/"; + } + + ngrinderHomePath = config.getHome().getDirectory().getAbsolutePath(); + } + + @Override + protected String getCopyDependenciesCommand(File distDir) { + String distDirPath = distDir.getAbsolutePath(); + return gradlePath + "gradle -I " + ngrinderHomePath + "/init.gradle -p" + distDirPath + + " __copyDependencies -PoutputDirectory=" + distDirPath + "/lib"; + } + + @Override + protected boolean isSuccess(List results) { + if (results.isEmpty()) { + return false; + } + return results.stream().noneMatch(str -> str.contains("FAILED")); + } + + @Override + public boolean prepareScriptEnv(User user, String path, String fileName, String name, // LF + String url, boolean createLib, String scriptContent) { + path = PathUtils.join(path, fileName); + // Create Dir entry + createBaseDirectory(user, path); + // Create each template entries + createFileEntries(user, path, name, url, scriptContent); + if (createLib) { + createLibraryDirectory(user, path); + } + return false; + } + + @Override + protected void deleteUnnecessaryFilesFromDist(File distDir) { + super.deleteUnnecessaryFilesFromDist(distDir); + deleteQuietly(new File(distDir, ".gradle")); + } + + private void createFileEntries(User user, String path, String name, String url, String scriptContent) { + String[] scriptTemplatePaths = { getBuildScriptName(), "src/main/resources/resource1.txt", "src/main/java/TestRunner.groovy" }; + for (String scriptTemplatePath : scriptTemplatePaths) { + try (InputStream inputStream = new ClassPathResource("/script_template/groovy_gradle/" + scriptTemplatePath).getInputStream()) { + String fileContent = IOUtils.toString(inputStream, UTF_8.name()); + if (scriptTemplatePath.endsWith("TestRunner.groovy")) { + fileContent = scriptContent; + } else { + fileContent = fileContent.replace("${userName}", user.getUserName()); + fileContent = fileContent.replace("${name}", name); + fileContent = fileContent.replace("${url}", url); + } + FileEntry fileEntry = new FileEntry(); + fileEntry.setContent(fileContent); + fileEntry.setPath(normalize(PathUtils.join(path, scriptTemplatePath), true)); + fileEntry.setDescription("create groovy gradle project"); + String hostName = getHost(url); + if (isNotEmpty(hostName) + && fileEntry.getFileType().getFileCategory() == SCRIPT) { + fileEntry.getProperties().put("targetHosts", getHost(url)); + } else { + fileEntry.getProperties().put("targetHosts", EMPTY); + } + getFileEntryRepository().save(user, fileEntry, UTF_8.name()); + } catch (IOException e) { + throw processException("Error while saving " + get(scriptTemplatePath).getFileName(), e); + } + } + } + + private void createBaseDirectory(User user, String path) { + FileEntry dirEntry = new FileEntry(); + dirEntry.setPath(path); + // Make it eclipse default folder ignored. + dirEntry.setProperties(buildMap("svn:ignore", ".project\n.classpath\n.settings\ntarget")); + dirEntry.setFileType(DIR); + dirEntry.setDescription("create groovy gradle project"); + getFileEntryRepository().save(user, dirEntry, null); + } +} diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyMavenProjectScriptHandler.java b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyMavenProjectScriptHandler.java index 202e606443..72cd256f6b 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyMavenProjectScriptHandler.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyMavenProjectScriptHandler.java @@ -13,35 +13,14 @@ */ package org.ngrinder.script.handler; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.maven.cli.MavenCli; -import org.ngrinder.common.exception.NGrinderRuntimeException; -import org.ngrinder.common.util.PathUtils; -import org.ngrinder.common.util.PropertiesWrapper; -import org.ngrinder.common.util.UrlUtils; -import org.ngrinder.model.User; -import org.ngrinder.script.model.FileCategory; -import org.ngrinder.script.model.FileEntry; -import org.ngrinder.script.model.FileType; -import org.ngrinder.script.repository.FileEntryRepository; -import org.ngrinder.script.repository.GitHubFileEntryRepository; -import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; -import org.tmatesoft.svn.core.wc.SVNRevision; import java.io.File; -import java.io.IOException; -import java.io.InputStream; import java.util.List; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.maven.wagon.PathUtils.filename; -import static org.ngrinder.common.util.CollectionUtils.buildMap; -import static org.ngrinder.common.util.CollectionUtils.newArrayList; -import static org.ngrinder.common.util.ExceptionUtils.processException; +import static java.lang.System.getenv; +import static org.apache.commons.lang.StringUtils.isNotEmpty; +import static org.ngrinder.common.util.AccessUtils.getSafe; /** * Groovy Maven project {@link ScriptHandler}. @@ -49,257 +28,33 @@ * @since 3.2 */ @Component -public class GroovyMavenProjectScriptHandler extends GroovyScriptHandler implements ProjectHandler { +public class GroovyMavenProjectScriptHandler extends GroovyProjectScriptHandler { - /** - * Constructor. - */ - public GroovyMavenProjectScriptHandler() { - super("groovy_maven", "", "Groovy Maven Project", "groovy"); - } - - private static final String RESOURCES = "src/main/resources/"; - private static final String JAVA = "src/main/java/"; - private static final String GROOVY = "src/main/groovy/"; - private static final String LIB = "lib/"; - - @Override - public boolean canHandle(FileEntry fileEntry) { - String path = fileEntry.getPath(); - if (!FilenameUtils.isExtension(path, "groovy")) { - return false; - } - - //noinspection SimplifiableIfStatement - if (!isGroovyMavenPath(path)) { - return false; - } - - if (isGitHubFileEntry(fileEntry)) { - return StringUtils.equals(fileEntry.getProperties().get("type"), "groovy-maven"); - } else { - if (fileEntry.getCreatedUser() == null) { - return false; - } - return getFileEntryRepository().hasOne(fileEntry.getCreatedUser(), getBasePath(path) + "pom.xml"); - } - } - - @Override - public Integer displayOrder() { - return 400; - } + public static final String MAVEN_HOME_ENV_NAME = "MAVEN_HOME"; - @Override - protected Integer order() { - return 200; - } - - @Override - public List getLibAndResourceEntries(User user, FileEntry scriptEntry, long revision) { - List fileList = newArrayList(); - String basePath = getBasePath(scriptEntry); - FileEntryRepository fileEntryRepository = getFileEntryRepository(); - GitHubFileEntryRepository gitHubFileEntryRepository = getGitHubFileEntryRepository(); - - List resourcesFileEntry; - List javaFileEntry; - List groovyFileEntry; - List libFileEntry; - - if (isGitHubFileEntry(scriptEntry)) { - try { - javaFileEntry = gitHubFileEntryRepository.findAll(basePath + JAVA); - resourcesFileEntry = gitHubFileEntryRepository.findAll(basePath + RESOURCES); - groovyFileEntry = gitHubFileEntryRepository.findAll(basePath + GROOVY); - libFileEntry = gitHubFileEntryRepository.findAll(basePath + LIB); - fileList.add(gitHubFileEntryRepository.findOne(basePath + "pom.xml")); - } catch (IOException e) { - throw new NGrinderRuntimeException(e); - } - } else { - resourcesFileEntry = fileEntryRepository.findAll(user, basePath + RESOURCES, revision, true); - javaFileEntry = fileEntryRepository.findAll(user, basePath + JAVA, revision, true); - groovyFileEntry = fileEntryRepository.findAll(user, basePath + GROOVY, revision, true); - libFileEntry = fileEntryRepository.findAll(user, basePath + LIB, revision, true); - fileList.add(fileEntryRepository.findOne(user, basePath + "pom.xml", SVNRevision.create(revision))); - } - - for (FileEntry eachFileEntry : resourcesFileEntry) { - FileType fileType = eachFileEntry.getFileType(); - if (fileType.isResourceDistributable()) { - fileList.add(eachFileEntry); - } - } - - for (FileEntry eachFileEntry : javaFileEntry) { - FileType fileType = eachFileEntry.getFileType(); - if (fileType.isLibDistributable() && !eachFileEntry.getPath().equals(scriptEntry.getPath())) { - fileList.add(eachFileEntry); - } - } - - for (FileEntry eachFileEntry : groovyFileEntry) { - FileType fileType = eachFileEntry.getFileType(); - if (fileType.isLibDistributable() && !eachFileEntry.getPath().equals(scriptEntry.getPath())) { - fileList.add(eachFileEntry); - } - } - - for (FileEntry eachFileEntry : libFileEntry) { - FileType fileType = eachFileEntry.getFileType(); - if (fileType.isLibDistributable()) { - fileList.add(eachFileEntry); - } - } + private String mavenPath; - return fileList; - } - - @Override - protected String calcDistSubPath(String basePath, FileEntry each) { - String calcDistSubPath = super.calcDistSubPath(basePath, each); - if (calcDistSubPath.startsWith(JAVA)) { - return calcDistSubPath.substring(JAVA.length() - 1); - } else if (calcDistSubPath.startsWith(GROOVY)) { - return calcDistSubPath.substring(GROOVY.length() - 1); - } else if (calcDistSubPath.startsWith(RESOURCES)) { - return calcDistSubPath.substring(RESOURCES.length() - 1); - } - return calcDistSubPath; - } - - @Override - protected void prepareDistMore(Long testId, User user, FileEntry script, File distDir, - PropertiesWrapper properties, ProcessingResultPrintStream processingResult) { - String pomPathInSVN = PathUtils.join(getBasePath(script), "pom.xml"); - MavenCli cli = new MavenCli(); - processingResult.println("\nCopy dependencies by running 'mvn dependency:copy-dependencies" - + " -DoutputDirectory=./lib -DexcludeScope=provided'"); - - System.setProperty(MavenCli.MULTIMODULE_PROJECT_DIRECTORY, distDir.getAbsolutePath()); - - int result = cli.doMain(new String[]{ // goal specification - "dependency:copy-dependencies", // run dependency goal - "-DoutputDirectory=./lib", // to the lib folder - "-DexcludeScope=provided" // but exclude the provided - // library - }, distDir.getAbsolutePath(), processingResult, processingResult); - boolean success = (result == 0); - if (success) { - processingResult.printf("\nDependencies in %s was copied.\n", pomPathInSVN); - LOGGER.info("Dependencies in {} is copied into {}/lib folder", pomPathInSVN, distDir.getAbsolutePath()); - } else { - processingResult.printf("\nDependencies copy in %s is failed.\n", pomPathInSVN); - LOGGER.info("Dependencies copy in {} is failed.", pomPathInSVN); - } - // Then it's not necessary to include pom.xml anymore. - FileUtils.deleteQuietly(new File(distDir, "pom.xml")); - processingResult.setSuccess(result == 0); - } - - @Override - public boolean prepareScriptEnv(User user, String path, String fileName, String name, // LF - String url, boolean createLib, String scriptContent) { - path = PathUtils.join(path, fileName); - // Create Dir entry - createBaseDirectory(user, path); - // Create each template entries - createFileEntries(user, path, name, url, scriptContent); - if (createLib) { - createLibraryDirectory(user, path); - } - return false; - } - - private void createLibraryDirectory(User user, String path) { - FileEntry fileEntry = new FileEntry(); - fileEntry.setPath(path + "/lib"); - fileEntry.setFileType(FileType.DIR); - fileEntry.setDescription("put private libraries here"); - getFileEntryRepository().save(user, fileEntry, null); - } + public GroovyMavenProjectScriptHandler() { + super("groovy_maven", "", "Groovy Maven Project", "groovy", "pom.xml", false); - private void createFileEntries(User user, String path, String name, String url, String scriptContent) { - String[] scriptTemplatePaths = { "pom.xml", "src/main/resources/resource1.txt", "src/main/java/TestRunner.groovy" }; - for (String scriptTemplatePath : scriptTemplatePaths) { - try (InputStream inputStream = new ClassPathResource("/script_template/groovy_maven/" + scriptTemplatePath).getInputStream()) { - String fileContent = IOUtils.toString(inputStream, UTF_8.name()); - if (scriptTemplatePath.endsWith("TestRunner.groovy")) { - fileContent = scriptContent; - } else { - fileContent = fileContent.replace("${userName}", user.getUserName()); - fileContent = fileContent.replace("${name}", name); - fileContent = fileContent.replace("${url}", url); - } - FileEntry fileEntry = new FileEntry(); - fileEntry.setContent(fileContent); - fileEntry.setPath(FilenameUtils.normalize(PathUtils.join(path, scriptTemplatePath), true)); - fileEntry.setDescription("create groovy maven project"); - String hostName = UrlUtils.getHost(url); - if (StringUtils.isNotEmpty(hostName) - && fileEntry.getFileType().getFileCategory() == FileCategory.SCRIPT) { - fileEntry.getProperties().put("targetHosts", UrlUtils.getHost(url)); - } else { - fileEntry.getProperties().put("targetHosts", StringUtils.EMPTY); - } - getFileEntryRepository().save(user, fileEntry, "UTF8"); - } catch (IOException e) { - throw processException("Error while saving " + filename(scriptTemplatePath), e); - } + mavenPath = getSafe(getenv(MAVEN_HOME_ENV_NAME), ""); + if (isNotEmpty(mavenPath)) { + mavenPath += "/bin/"; } } - private void createBaseDirectory(User user, String path) { - FileEntry dirEntry = new FileEntry(); - dirEntry.setPath(path); - // Make it eclipse default folder ignored. - dirEntry.setProperties(buildMap("svn:ignore", ".project\n.classpath\n.settings\ntarget")); - dirEntry.setFileType(FileType.DIR); - dirEntry.setDescription("create groovy maven project"); - getFileEntryRepository().save(user, dirEntry, null); - } - - /* - * (non-Javadoc) - * - * @see - * org.ngrinder.script.handler.ScriptHandler#getBasePath(java.lang.String) - */ @Override - public String getBasePath(String path) { - if (path.contains(JAVA)) { - return path.substring(0, path.lastIndexOf(JAVA)); - } else { - return path.substring(0, path.lastIndexOf(GROOVY)); - } + protected String getCopyDependenciesCommand(File distDir) { + String distDirPath = distDir.getAbsolutePath(); + return mavenPath + "mvn -f " + distDirPath + " dependency:copy-dependencies -DoutputDirectory=./lib " + + "-DexcludeScope=provided -Dmaven.multiModuleProjectDirectory=" + distDirPath; } @Override - public String getScriptExecutePath(String path) { - if (path.contains(JAVA)) { - return path.substring(path.lastIndexOf(JAVA) + JAVA.length()); - } else { - return path.substring(path.lastIndexOf(GROOVY) + GROOVY.length()); - } - } - - @Override - public FileEntry getDefaultQuickTestFilePath(String path) { - FileEntry fileEntry = new FileEntry(); - fileEntry.setPath(path + "/" + JAVA + "TestRunner.groovy"); - return fileEntry; - } - - public String getGroovyMavenPath(String path) { - if (path.contains(JAVA)) { - return path.substring(path.lastIndexOf(JAVA)); - } else { - return path.substring(path.lastIndexOf(GROOVY)); + protected boolean isSuccess(List results) { + if (results.isEmpty()) { + return false; } - } - - public boolean isGroovyMavenPath(String path) { - return path.contains(JAVA) || path.contains(GROOVY); + return results.stream().noneMatch(str -> str.contains("[ERROR]")); } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyProjectScriptHandler.java b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyProjectScriptHandler.java new file mode 100644 index 0000000000..93765404d0 --- /dev/null +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyProjectScriptHandler.java @@ -0,0 +1,264 @@ +/* + * Copyright (c) 2012-present NAVER Corp. + * + * This file is part of The nGrinder software distribution. Refer to + * the file LICENSE which is part of The nGrinder distribution for + * licensing details. The nGrinder distribution is available on the + * Internet at https://naver.github.io/ngrinder + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ngrinder.script.handler; + +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.StringUtils; +import org.ngrinder.common.exception.NGrinderRuntimeException; +import org.ngrinder.common.util.PathUtils; +import org.ngrinder.common.util.PropertiesWrapper; +import org.ngrinder.model.PerfTest; +import org.ngrinder.model.User; +import org.ngrinder.script.model.FileEntry; +import org.ngrinder.script.model.FileType; +import org.ngrinder.script.repository.FileEntryRepository; +import org.ngrinder.script.repository.GitHubFileEntryRepository; +import org.tmatesoft.svn.core.wc.SVNRevision; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +import static org.apache.commons.io.FileUtils.deleteQuietly; +import static org.ngrinder.common.util.CollectionUtils.newArrayList; +import static org.ngrinder.common.util.LoggingUtils.format; +import static org.ngrinder.script.model.FileType.DIR; +import static oshi.util.ExecutingCommand.runNative; + +/** + * Groovy project {@link ScriptHandler}. + * + * @since 3.5.3 + */ +@Getter +@Slf4j +public abstract class GroovyProjectScriptHandler extends GroovyScriptHandler implements ProjectHandler { + + protected static String RESOURCES = "src/main/resources/"; + protected static String JAVA = "src/main/java/"; + protected static String GROOVY = "src/main/groovy/"; + protected static String LIB = "lib/"; + + private final String buildScriptName; + + public GroovyProjectScriptHandler(String key, String extension, String title, + String codeMirrorKey, String buildScriptName, boolean creatable) { + super(key, extension, title, codeMirrorKey, creatable); + this.buildScriptName = buildScriptName; + } + + /** + * Return a command to copy dependencies specified in the build script to dist directory. + * */ + protected abstract String getCopyDependenciesCommand(File distDir); + + /** + * Check if copy dependencies is successful. + * + * @param results Result of executing command created by {@link #getCopyDependenciesCommand} with OSHI. + */ + protected abstract boolean isSuccess(List results); + + @Override + public boolean canHandle(FileEntry fileEntry) { + String path = fileEntry.getPath(); + if (!FilenameUtils.isExtension(path, "groovy")) { + return false; + } + + //noinspection SimplifiableIfStatement + if (!isGroovyProjectScriptPath(path)) { + return false; + } + + if (isGitHubFileEntry(fileEntry)) { + return StringUtils.equals(fileEntry.getProperties().get("type"), getKey()); + } else { + if (fileEntry.getCreatedBy() == null) { + return false; + } + return getFileEntryRepository().hasOne(fileEntry.getCreatedBy(), getBasePath(path) + buildScriptName); + } + } + + @Override + public Integer displayOrder() { + return 400; + } + + @Override + protected Integer order() { + return 200; + } + + @Override + public String getScriptExecutePath(String path) { + if (path.contains(JAVA)) { + return path.substring(path.lastIndexOf(JAVA) + JAVA.length()); + } else { + return path.substring(path.lastIndexOf(GROOVY) + GROOVY.length()); + } + } + + @Override + public FileEntry getDefaultQuickTestFilePath(String path) { + FileEntry fileEntry = new FileEntry(); + fileEntry.setPath(path + "/" + JAVA + "TestRunner.groovy"); + return fileEntry; + } + + @Override + protected String calcDistSubPath(String basePath, FileEntry each) { + String calcDistSubPath = super.calcDistSubPath(basePath, each); + if (calcDistSubPath.startsWith(JAVA)) { + return calcDistSubPath.substring(JAVA.length() - 1); + } else if (calcDistSubPath.startsWith(GROOVY)) { + return calcDistSubPath.substring(GROOVY.length() - 1); + } else if (calcDistSubPath.startsWith(RESOURCES)) { + return calcDistSubPath.substring(RESOURCES.length() - 1); + } + return calcDistSubPath; + } + + /* + * (non-Javadoc) + * + * @see + * org.ngrinder.script.handler.ScriptHandler#getBasePath(java.lang.String) + */ + @Override + public String getBasePath(String path) { + if (path.contains(JAVA)) { + return path.substring(0, path.lastIndexOf(JAVA)); + } else { + return path.substring(0, path.lastIndexOf(GROOVY)); + } + } + + @Override + protected void prepareDistMore(PerfTest perfTest, User user, FileEntry script, File distDir, + PropertiesWrapper properties, ProcessingResultPrintStream processingResult) { + String buildFilePathInSVN = PathUtils.join(getBasePath(script), getBuildScriptName()); + String copyDependenciesCommand = getCopyDependenciesCommand(distDir); + processingResult.println("\nCopy dependencies by running '" + copyDependenciesCommand + "'"); + + boolean success = isSuccess(runNative(copyDependenciesCommand)); + + if (success) { + processingResult.printf("\nDependencies in %s was copied.\n", buildFilePathInSVN); + log.info(format(perfTest, "Dependencies in {} is copied into {}/lib folder", buildFilePathInSVN, distDir.getAbsolutePath())); + } else { + processingResult.printf("\nDependencies copy in %s is failed.\n", buildFilePathInSVN); + log.info(format(perfTest, "Dependencies copy in {} is failed.", buildFilePathInSVN)); + } + + deleteUnnecessaryFilesFromDist(distDir); + processingResult.setSuccess(success); + } + + @Override + public List getLibAndResourceEntries(User user, FileEntry scriptEntry, long revision) { + List fileList = newArrayList(); + String basePath = getBasePath(scriptEntry); + FileEntryRepository fileEntryRepository = getFileEntryRepository(); + GitHubFileEntryRepository gitHubFileEntryRepository = getGitHubFileEntryRepository(); + + List resourcesFileEntry; + List javaFileEntry; + List groovyFileEntry; + List libFileEntry; + + if (isGitHubFileEntry(scriptEntry)) { + try { + javaFileEntry = gitHubFileEntryRepository.findAll(basePath + JAVA); + resourcesFileEntry = gitHubFileEntryRepository.findAll(basePath + RESOURCES); + groovyFileEntry = gitHubFileEntryRepository.findAll(basePath + GROOVY); + libFileEntry = gitHubFileEntryRepository.findAll(basePath + LIB); + fileList.add(gitHubFileEntryRepository.findOne(basePath + buildScriptName)); + } catch (IOException e) { + throw new NGrinderRuntimeException(e); + } + } else { + resourcesFileEntry = fileEntryRepository.findAll(user, basePath + RESOURCES, revision, true); + javaFileEntry = fileEntryRepository.findAll(user, basePath + JAVA, revision, true); + groovyFileEntry = fileEntryRepository.findAll(user, basePath + GROOVY, revision, true); + libFileEntry = fileEntryRepository.findAll(user, basePath + LIB, revision, true); + fileList.add(fileEntryRepository.findOne(user, basePath + buildScriptName, SVNRevision.create(revision))); + } + + for (FileEntry eachFileEntry : resourcesFileEntry) { + FileType fileType = eachFileEntry.getFileType(); + if (fileType.isResourceDistributable()) { + fileList.add(eachFileEntry); + } + } + + for (FileEntry eachFileEntry : javaFileEntry) { + FileType fileType = eachFileEntry.getFileType(); + if (fileType.isLibDistributable() && !eachFileEntry.getPath().equals(scriptEntry.getPath())) { + fileList.add(eachFileEntry); + } + } + + for (FileEntry eachFileEntry : groovyFileEntry) { + FileType fileType = eachFileEntry.getFileType(); + if (fileType.isLibDistributable() && !eachFileEntry.getPath().equals(scriptEntry.getPath())) { + fileList.add(eachFileEntry); + } + } + + for (FileEntry eachFileEntry : libFileEntry) { + FileType fileType = eachFileEntry.getFileType(); + if (fileType.isLibDistributable()) { + fileList.add(eachFileEntry); + } + } + + return fileList; + } + + protected void deleteUnnecessaryFilesFromDist(File distDir) { + deleteQuietly(new File(distDir, getBuildScriptName())); + } + + protected void createLibraryDirectory(User user, String path) { + FileEntry fileEntry = new FileEntry(); + fileEntry.setPath(path + "/lib"); + fileEntry.setFileType(DIR); + fileEntry.setDescription("put private libraries here"); + getFileEntryRepository().save(user, fileEntry, null); + } + + public String getGroovyProjectPath(String path) { + if (path.contains(JAVA)) { + return path.substring(path.lastIndexOf(JAVA)); + } else { + return path.substring(path.lastIndexOf(GROOVY)); + } + } + + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public boolean isGroovyProjectScriptPath(String path) { + return path.contains(JAVA) || path.contains(GROOVY); + } +} diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyScriptHandler.java b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyScriptHandler.java index 515ad654e1..2c360f01de 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyScriptHandler.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/GroovyScriptHandler.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.handler; @@ -39,7 +39,7 @@ public class GroovyScriptHandler extends ScriptHandler { * Constructor. */ public GroovyScriptHandler() { - this("groovy", "groovy", "Groovy", "groovy"); + this("groovy", "groovy", "Groovy", "groovy", true); } /** @@ -49,9 +49,10 @@ public GroovyScriptHandler() { * @param extension extension * @param title title * @param codeMirrorKey code mirror key + * @param creatable creatable */ - public GroovyScriptHandler(String key, String extension, String title, String codeMirrorKey) { - super(key, extension, title, codeMirrorKey); + public GroovyScriptHandler(String key, String extension, String title, String codeMirrorKey, boolean creatable) { + super(key, extension, title, codeMirrorKey, creatable); } @Override diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/JythonScriptHandler.java b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/JythonScriptHandler.java index 8a31cc0cd4..7c293e5ae8 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/JythonScriptHandler.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/JythonScriptHandler.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.handler; @@ -28,7 +28,7 @@ public class JythonScriptHandler extends ScriptHandler { * Constructor. */ public JythonScriptHandler() { - super("jython", "py", "Jython", "python"); + super("jython", "py", "Jython", "python", true); } @Override diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/NullScriptHandler.java b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/NullScriptHandler.java index 188b6a4fca..a08bfd18dd 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/NullScriptHandler.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/NullScriptHandler.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,11 +9,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.handler; import org.ngrinder.common.util.PropertiesWrapper; +import org.ngrinder.model.PerfTest; import org.ngrinder.model.User; import org.ngrinder.script.model.FileEntry; import org.ngrinder.script.model.FileType; @@ -24,6 +25,7 @@ import static org.ngrinder.common.util.CollectionUtils.getValue; import static org.ngrinder.common.util.CollectionUtils.newHashMap; +import static org.ngrinder.script.model.FileType.*; /** * Null {@link ScriptHandler} which implements Null object pattern. @@ -33,13 +35,14 @@ @Component public class NullScriptHandler extends ScriptHandler { - private Map codeMirrorKey = newHashMap(); + private final Map codeMirrorKey = newHashMap(); public NullScriptHandler() { - super("", "", null, null); - codeMirrorKey.put(FileType.PROPERTIES, "properties"); - codeMirrorKey.put(FileType.XML, "xml"); - codeMirrorKey.put(FileType.YAML, "yaml"); + super("", "", null, null, false); + codeMirrorKey.put(PROPERTIES, "properties"); + codeMirrorKey.put(XML, "xml"); + codeMirrorKey.put(YAML, "yaml"); + codeMirrorKey.put(GRADLE, "groovy"); } @Override @@ -48,12 +51,11 @@ public Integer order() { } @Override - public void prepareDist(Long testId, User user, FileEntry script, // - File distDir, PropertiesWrapper properties, ProcessingResultPrintStream processingResult) { + public void prepareDist(PerfTest perfTest, User user, FileEntry script, // + File distDir, PropertiesWrapper properties, ProcessingResultPrintStream processingResult) { } - @SuppressWarnings("SpellCheckingInspection") @Override public boolean isValidatable() { return false; @@ -65,7 +67,7 @@ public boolean isValidatable() { * @param fileType file type * @return appropriate code mirror key. if nothing, return shell */ - @SuppressWarnings({"UnusedDeclaration", "SpellCheckingInspection"}) + @SuppressWarnings("UnusedDeclaration") public String getCodemirrorKey(FileType fileType) { return getValue(codeMirrorKey, fileType, "shell"); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/ScriptHandler.java b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/ScriptHandler.java index ae0e8620d0..1c7d8e00e1 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/ScriptHandler.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/ScriptHandler.java @@ -19,6 +19,7 @@ import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import lombok.Getter; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.ngrinder.common.constant.ControllerConstants; @@ -26,13 +27,12 @@ import org.ngrinder.common.exception.PerfTestPrepareException; import org.ngrinder.common.util.PathUtils; import org.ngrinder.common.util.PropertiesWrapper; +import org.ngrinder.model.PerfTest; import org.ngrinder.model.User; import org.ngrinder.script.model.FileEntry; import org.ngrinder.script.model.FileType; import org.ngrinder.script.repository.FileEntryRepository; import org.ngrinder.script.repository.GitHubFileEntryRepository; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.io.File; @@ -47,6 +47,7 @@ import static org.ngrinder.common.util.CollectionUtils.newArrayList; import static org.ngrinder.common.util.ExceptionUtils.processException; import static org.ngrinder.common.util.FileUtils.copyResourceToFile; +import static org.ngrinder.common.util.LoggingUtils.format; /** * Script per language handler. This is the superclass for all sub @@ -56,12 +57,14 @@ * @since 3.2 */ @Getter +@Slf4j public abstract class ScriptHandler implements ControllerConstants { - protected static final Logger LOGGER = LoggerFactory.getLogger(JythonScriptHandler.class); + private final String codemirrorKey; private final String title; private final String extension; private final String key; + private final boolean creatable; /** * Constructor. @@ -71,11 +74,12 @@ public abstract class ScriptHandler implements ControllerConstants { * @param title title of the handler * @param codeMirrorKey code mirror key */ - public ScriptHandler(String key, String extension, String title, String codeMirrorKey) { + public ScriptHandler(String key, String extension, String title, String codeMirrorKey, boolean creatable) { this.key = key; this.extension = extension; this.title = title; this.codemirrorKey = codeMirrorKey; + this.creatable = creatable; } @Autowired @@ -112,7 +116,7 @@ public boolean canHandle(FileEntry fileEntry) { */ protected abstract Integer order(); - @SuppressWarnings("SpellCheckingInspection") + @SuppressWarnings("unused") @JsonProperty public boolean isValidatable() { return true; @@ -133,17 +137,17 @@ public boolean isProjectHandler() { /** * Prepare the distribution. * - * @param testCaseId id of the test case. This is for the log identification. + * @param perfTest current running test. * @param user user who will distribute the script. * @param scriptEntry script to be distributed. * @param distDir distribution target dir. * @param properties properties set which is used for detailed distribution control. * @param processingResult processing result holder. */ - public void prepareDist(Long testCaseId, - User user, - FileEntry scriptEntry, File distDir, PropertiesWrapper properties, - ProcessingResultPrintStream processingResult) { + public void prepareDist(PerfTest perfTest, + User user, + FileEntry scriptEntry, File distDir, PropertiesWrapper properties, + ProcessingResultPrintStream processingResult) { prepareDefaultFile(distDir, properties); List fileEntries = getLibAndResourceEntries(user, scriptEntry, -1); if (scriptEntry.getRevision() != 0) { @@ -160,7 +164,7 @@ public void prepareDist(Long testCaseId, } File toDir = new File(distDir, calcDistSubPath(basePath, each)); processingResult.printf("%s is being written.\n", each.getPath()); - LOGGER.info("{} is being written in {} for test {}", each.getPath(), toDir, testCaseId); + log.info(format(perfTest, "{} is being written in {}", each.getPath(), toDir)); if (isGitHubFileEntry(each)) { gitHubFileEntryRepository.writeContentTo(each.getPath(), toDir); } else { @@ -172,7 +176,7 @@ public void prepareDist(Long testCaseId, "If you change your branch configuration, please click script refresh button before running test.", ex); } processingResult.setSuccess(true); - prepareDistMore(testCaseId, user, scriptEntry, distDir, properties, processingResult); + prepareDistMore(perfTest, user, scriptEntry, distDir, properties, processingResult); } protected boolean isGitHubFileEntry(FileEntry fileEntry) { @@ -195,8 +199,9 @@ protected boolean isGitHubFileEntry(FileEntry fileEntry) { * @param createLibAndResources true if lib and resources should be created * @return true if process more. */ + @SuppressWarnings("UnusedReturnValue") public boolean prepareScriptEnv(User user, String path, String fileName, String name, String url, - boolean createLibAndResources, String scriptContent) { + boolean createLibAndResources, String scriptContent) { return true; } @@ -204,14 +209,14 @@ public boolean prepareScriptEnv(User user, String path, String fileName, String * Prepare the distribution more. This method is subject to be extended by * the subclass. * - * @param testCaseId test case id. This is for the log identification. + * @param perfTest current running test. * @param user user * @param script script entry to be distributed. * @param distDir distribution directory * @param properties properties * @param processingResult processing result holder */ - protected void prepareDistMore(Long testCaseId, User user, FileEntry script, File distDir, + protected void prepareDistMore(PerfTest perfTest, User user, FileEntry script, File distDir, PropertiesWrapper properties, ProcessingResultPrintStream processingResult) { } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/ScriptHandlerFactory.java b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/ScriptHandlerFactory.java index 99113cf3aa..b99a64e815 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/handler/ScriptHandlerFactory.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/ScriptHandlerFactory.java @@ -15,7 +15,7 @@ /** * ScriptHanderFactory which returns appropriate hander for the given {@link FileEntry}. - * + * * @since 3.2 */ @Component @@ -39,7 +39,7 @@ public void init() { visibleHandlers = newArrayList(); for (ScriptHandler each : this.scriptHandlers) { - if (!(each instanceof NullScriptHandler)) { + if (each.isCreatable()) { visibleHandlers.add(each); } } @@ -49,7 +49,7 @@ public void init() { /** * Get the appropriate {@link ScriptHandler} for the given fileEntry. - * + * * @param fileEntry fileEntry to be handled * @return {@link ScriptHandler}. {@link NullScriptHandler} if none is available. */ @@ -65,7 +65,7 @@ public ScriptHandler getHandler(FileEntry fileEntry) { /** * Get the appropriate {@link ScriptHandler} for the given key. - * + * * @param key ScriptHandler key * @return {@link ScriptHandler}. {@link NullScriptHandler} if none is available. */ diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileCategory.java b/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileCategory.java index 964bec5519..ff33bac9dd 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileCategory.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileCategory.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,22 +9,22 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.model; /** * Category of FileEntity. - * + * * This field is used for identifying the file type. - * + * * @since 3.1 */ public enum FileCategory { SCRIPT(true), DATA(true), LIBRARY(false), ETC(false), PROJECT(true); private final boolean isEditable; - private FileCategory(boolean isEditable) { + FileCategory(boolean isEditable) { this.isEditable = isEditable; } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileEntry.java b/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileEntry.java index 38d60cadd4..bc3a8aa377 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileEntry.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileEntry.java @@ -22,9 +22,9 @@ import lombok.Setter; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.math.NumberUtils; -import org.ngrinder.common.util.PathUtils; import org.ngrinder.model.BaseModel; import org.ngrinder.model.IFileEntry; +import org.ngrinder.model.User; import java.io.IOException; import java.util.HashMap; @@ -136,6 +136,15 @@ public int getValidated() { } } + /** + * For backward compatibility. + * */ + @Override + @JsonSerialize(using = User.UserReferenceSerializer.class) + public User getCreatedUser() { + return getCreatedBy(); + } + private static class UnixPathSerializer extends StdSerializer { @SuppressWarnings("unused") UnixPathSerializer() { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileType.java b/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileType.java index 4fb8455410..1d6b1586d1 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileType.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileType.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.model; @@ -18,19 +18,22 @@ /** * File type of FileEntity. - * + * * @since 3.0 */ public enum FileType { /** Python/Jython. */ PYTHON_SCRIPT("Jython Script", "py", FileCategory.SCRIPT, true, false), - + /** Groovy Script. */ GROOVY_SCRIPT("Groovy Script", "groovy", FileCategory.SCRIPT, true, false), - + /** Groovy Maven project. */ - GROOVY_MAVEN_PROJECT("Groovy maven project", "pom", FileCategory.PROJECT, true, false), - + GROOVY_MAVEN_PROJECT("Groovy maven project", "", FileCategory.PROJECT, true, false), + + /** Groovy Gradle project. */ + GROOVY_GRADLE_PROJECT("Groovy gradle project", "", FileCategory.PROJECT, true, false), + /** Xml. */ XML("xml", "xml", FileCategory.DATA, true, true), /** Text. */ @@ -41,6 +44,8 @@ public enum FileType { JSON("json", "json", FileCategory.DATA, false, true), /** YAML. */ YAML("yaml", "yml", FileCategory.DATA, false, false), + /** GRADLE. */ + GRADLE("Gradle build script", "gradle", FileCategory.DATA, false, false), /** Properties. */ PROPERTIES("properties", "properties", FileCategory.DATA, false, true), /** Classes. */ @@ -57,7 +62,7 @@ public enum FileType { /** Dir. */ DIR("dir", "", FileCategory.ETC, false, false); - private String description; + private final String description; @Getter private final FileCategory fileCategory; private final String extension; @@ -68,7 +73,7 @@ public enum FileType { /** * Constructor. - * + * * @param description description of this file type * @param extension file extension. * @param fileCategory category of FileType. @@ -86,7 +91,7 @@ public enum FileType { /** * Get file type by extension of given name. - * + * * @param name name of file. * @return FileType which matches to extension. UNKNOWN otherwise. */ @@ -96,7 +101,7 @@ public static FileType getFileTypeByName(String name) { /** * Get file type by extension. - * + * * @param extension extension * @return FileType which matches to extension. UNKNOWN otherwise. */ @@ -111,7 +116,7 @@ public static FileType getFileTypeByExtension(String extension) { /** * Get description of file type. - * + * * @return file type description. */ @Override diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/model/GitHubConfigField.java b/ngrinder-controller/src/main/java/org/ngrinder/script/model/GitHubConfigField.java index b37e860d06..545f5f0105 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/model/GitHubConfigField.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/model/GitHubConfigField.java @@ -11,7 +11,7 @@ public enum GitHubConfigField { NAME("name"), OWNER("owner"), REPO("repo"), ACCESS_TOKEN("access-token"), BRANCH("branch"), BASE_URL("base-url"), REVISION("revision"), SCRIPT_ROOT("script-root"); - private String value; + private final String value; public static boolean isSupportedField(String fieldName) { return stream(values()).anyMatch(field -> field.getValue().equals(fieldName)); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/repository/FileEntryRepository.java b/ngrinder-controller/src/main/java/org/ngrinder/script/repository/FileEntryRepository.java index db0dfd2ec8..06d36526c9 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/repository/FileEntryRepository.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/repository/FileEntryRepository.java @@ -26,7 +26,6 @@ import org.ngrinder.script.model.FileCategory; import org.ngrinder.script.model.FileEntry; import org.ngrinder.script.model.FileType; -import org.ngrinder.user.repository.UserRepository; import org.ngrinder.user.service.UserContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,6 +47,7 @@ import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; +import java.time.Instant; import java.util.EmptyStackException; import java.util.List; import java.util.Map.Entry; @@ -132,18 +132,15 @@ public List findAll(User user, final String path, Long revision, bool SVNClientManager svnClientManager = getSVNClientManager(); try { svnClientManager.getLogClient().doList(SVNURL.fromFile(getUserRepoDirectory(user)).appendPath(path, true), - svnRevision, svnRevision, true, recursive, new ISVNDirEntryHandler() { - @Override - public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException { - + svnRevision, svnRevision, true, recursive, dirEntry -> { FileEntry script = new FileEntry(); // Exclude base path "/" if (StringUtils.isBlank(dirEntry.getRelativePath())) { return; } script.setPath(FilenameUtils.normalize(path + "/" + dirEntry.getRelativePath(), true)); - script.setCreatedDate(dirEntry.getDate()); - script.setLastModifiedDate(dirEntry.getDate()); + script.setCreatedAt(dirEntry.getDate().toInstant()); + script.setLastModifiedAt(dirEntry.getDate().toInstant()); script.setDescription(dirEntry.getCommitMessage()); script.setRevision(dirEntry.getRevision()); if (dirEntry.getKind() == SVNNodeKind.DIR) { @@ -153,8 +150,7 @@ public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException { script.setFileSize(dirEntry.getSize()); } fileEntries.add(script); - } - }); + }); } catch (Exception e) { LOG.debug("findAll() to the not existing folder {}", path); } finally { @@ -175,16 +171,15 @@ public List findAll(final User user) { SVNClientManager svnClientManager = getSVNClientManager(); try { svnClientManager.getLogClient().doList(SVNURL.fromFile(getUserRepoDirectory(user)), SVNRevision.HEAD, - SVNRevision.HEAD, false, true, new ISVNDirEntryHandler() { - @Override - public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException { + SVNRevision.HEAD, false, true, dirEntry -> { FileEntry script = new FileEntry(); String relativePath = dirEntry.getRelativePath(); if (StringUtils.isBlank(relativePath)) { return; } - script.setCreatedDate(dirEntry.getDate()); - script.setLastModifiedDate(dirEntry.getDate()); + Instant lastModifiedAt = dirEntry.getDate().toInstant(); + script.setCreatedAt(lastModifiedAt); + script.setLastModifiedAt(lastModifiedAt); script.setPath(relativePath); script.setDescription(dirEntry.getCommitMessage()); long reversion = dirEntry.getRevision(); @@ -192,8 +187,7 @@ public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException { script.setFileType(dirEntry.getKind() == SVNNodeKind.DIR ? FileType.DIR : null); script.setFileSize(dirEntry.getSize()); scripts.add(script); - } - }); + }); } catch (Exception e) { LOG.error("Error while fetching files from SVN for {}", user.getUserId()); LOG.debug("Error details :", e); @@ -216,8 +210,9 @@ public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException { public FileEntry findOne(User user, String path, SVNRevision revision) { final FileEntry script = new FileEntry(); SVNClientManager svnClientManager = null; - ByteArrayOutputStream outputStream = null; - try { + + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + svnClientManager = getSVNClientManager(); SVNURL userRepoUrl = SVNURL.fromFile(getUserRepoDirectory(user)); @@ -229,7 +224,6 @@ public FileEntry findOne(User user, String path, SVNRevision revision) { if (nodeKind == SVNNodeKind.NONE) { return null; } - outputStream = new ByteArrayOutputStream(); SVNProperties fileProperty = new SVNProperties(); // Get File. repo.getFile(path, revision.getNumber(), fileProperty, outputStream); @@ -248,20 +242,17 @@ public FileEntry findOne(User user, String path, SVNRevision revision) { String autoDetectedEncoding = EncodingUtils.detectEncoding(byteArray, "UTF-8"); script.setContent((new String(byteArray, autoDetectedEncoding)).replaceAll(""","\"")); script.setEncoding(autoDetectedEncoding); - script.setContentBytes(byteArray); - } else { - script.setContentBytes(byteArray); } + script.setContentBytes(byteArray); script.setDescription(info.getCommitMessage()); script.setRevision(revisionNumber); script.setLastRevision(lastRevisionNumber); - script.setCreatedUser(user); + script.setCreatedBy(user); } catch (Exception e) { LOG.error("Error while fetching a file from SVN {}", user.getUserId() + "_" + path, e); return null; } finally { closeSVNClientManagerQuietly(svnClientManager); - IOUtils.closeQuietly(outputStream); } return script; } @@ -283,11 +274,13 @@ private void addPropertyValue(ISVNEditor editor, FileEntry fileEntry) throws SVN * @param encoding file encoding with which fileEntry is saved. It is meaningful * only FileEntry is editable. */ + @SuppressWarnings("JavadocReference") public void save(User user, FileEntry fileEntry, String encoding) { SVNClientManager svnClientManager = null; ISVNEditor editor = null; String checksum = null; InputStream bais = null; + try { svnClientManager = getSVNClientManager(); SVNRepository repo = svnClientManager.createRepository(SVNURL.fromFile(getUserRepoDirectory(user)), true); @@ -332,9 +325,10 @@ public void save(User user, FileEntry fileEntry, String encoding) { // Calc diff final SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator(); + if (fileEntry.getContentBytes() == null && fileEntry.getFileType().isEditable()) { bais = new ByteArrayInputStream(checkNotNull(fileEntry.getContent()).getBytes( - encoding == null ? "UTF-8" : encoding)); + encoding == null ? "UTF-8" : encoding)); } else { bais = new ByteArrayInputStream(fileEntry.getContentBytes()); } @@ -398,10 +392,7 @@ private void closeSVNEditorQuietly(ISVNEditor editor) { while (true) { editor.closeDir(); } - } catch (EmptyStackException e) { - // FALL THROUGH - noOp(); - } catch (SVNException e) { + } catch (EmptyStackException | SVNException e) { // FALL THROUGH noOp(); } finally { @@ -504,7 +495,7 @@ public boolean hasOne(User user, String path) { */ public void writeContentTo(User user, String path, File toPathDir) { SVNClientManager svnClientManager = null; - FileOutputStream fileOutputStream = null; + try { svnClientManager = getSVNClientManager(); @@ -519,16 +510,17 @@ public void writeContentTo(User user, String path, File toPathDir) { toPathDir.mkdirs(); File destFile = new File(toPathDir, FilenameUtils.getName(path)); // Prepare parent folders - fileOutputStream = new FileOutputStream(destFile); - SVNProperties fileProperty = new SVNProperties(); - // Get file. - repo.getFile(path, -1L, fileProperty, fileOutputStream); + try (FileOutputStream fileOutputStream = new FileOutputStream(destFile)) { + SVNProperties fileProperty = new SVNProperties(); + // Get file. + repo.getFile(path, -1L, fileProperty, fileOutputStream); + } + } catch (Exception e) { LOG.error("Error while fetching files from SVN", e); throw processException("Error while fetching files from SVN", e); } finally { closeSVNClientManagerQuietly(svnClientManager); - IOUtils.closeQuietly(fileOutputStream); } } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/service/FileEntryService.java b/ngrinder-controller/src/main/java/org/ngrinder/script/service/FileEntryService.java index 0b6ee9f52d..816d04a9a8 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/service/FileEntryService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/service/FileEntryService.java @@ -48,7 +48,7 @@ import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.unmodifiableList; import static org.apache.commons.compress.utils.CharsetNames.UTF_8; -import static org.ngrinder.common.constant.CacheConstants.CACHE_FILE_ENTRIES; +import static org.ngrinder.common.constant.CacheConstants.DIST_CACHE_FILE_ENTRIES; import static org.ngrinder.common.util.CollectionUtils.buildMap; import static org.ngrinder.common.util.CollectionUtils.newHashMap; import static org.ngrinder.common.util.ExceptionUtils.processException; @@ -97,7 +97,7 @@ public void init() { } }); svnClientManager = fileEntityRepository.getSVNClientManager(); - fileEntryCache = cacheManager.getCache(CACHE_FILE_ENTRIES); + fileEntryCache = cacheManager.getCache(DIST_CACHE_FILE_ENTRIES); } /** @@ -147,6 +147,7 @@ public boolean existGitHubConfig(User user) { return getOne(user, ".gitconfig.yml", -1L) != null; } + @SuppressWarnings("UnusedReturnValue") private SVNURL createUserRepo(User user, File newUserDirectory) throws SVNException { return svnClientManager.getAdminClient().doCreateRepository(newUserDirectory, user.getUserId(), true, true); } @@ -162,7 +163,7 @@ private File getUserRepoDirectory(User user) { * @param user user * @return cached {@link FileEntry} list */ - @Cacheable(value = CACHE_FILE_ENTRIES, key = "#user.userId") + @Cacheable(value = DIST_CACHE_FILE_ENTRIES, key = "#user.userId") public List getAll(User user) { prepare(user); List allFileEntries; @@ -279,7 +280,7 @@ String getPathFromUrl(String urlString) { try { URL url = new URL(urlString); String urlPath = "/".equals(url.getPath()) ? "" : url.getPath(); - return (url.getHost() + urlPath).replaceAll("[;\\&\\?\\%\\$\\-\\#]", "_"); + return (url.getHost() + urlPath).replaceAll("[;&?%$\\-#]", "_"); } catch (MalformedURLException e) { throw processException("Error while translating " + urlString, e); } @@ -337,13 +338,12 @@ public FileEntry prepareNewEntryForQuickTest(User user, String url, ScriptHandle String path = getPathFromUrl(url); String host = UrlUtils.getHost(url); FileEntry quickTestFile = scriptHandler.getDefaultQuickTestFilePath(path); - String nullOptions = null; if (scriptHandler instanceof ProjectHandler) { String[] pathPart = dividePathAndFile(path); - prepareNewEntry(user, pathPart[0], pathPart[1], host, url, scriptHandler, false, nullOptions); + prepareNewEntry(user, pathPart[0], pathPart[1], host, url, scriptHandler, false, null); } else { FileEntry fileEntry = prepareNewEntry(user, path, quickTestFile.getFileName(), host, url, scriptHandler, - false, nullOptions); + false, null); fileEntry.setDescription("Quick test for " + url); save(user, fileEntry); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/service/GitHubFileEntryService.java b/ngrinder-controller/src/main/java/org/ngrinder/script/service/GitHubFileEntryService.java index 0858b1b534..01c4758b99 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/service/GitHubFileEntryService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/service/GitHubFileEntryService.java @@ -14,6 +14,7 @@ import org.ngrinder.model.Status; import org.ngrinder.model.User; import org.ngrinder.perftest.service.PerfTestService; +import org.ngrinder.script.handler.GroovyGradleProjectScriptHandler; import org.ngrinder.script.handler.GroovyMavenProjectScriptHandler; import org.ngrinder.script.model.FileEntry; import org.ngrinder.script.model.GitHubConfig; @@ -42,8 +43,8 @@ import static org.apache.commons.io.FilenameUtils.getName; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotEmpty; -import static org.ngrinder.common.constant.CacheConstants.CACHE_GITHUB_IS_MAVEN_GROOVY; -import static org.ngrinder.common.constant.CacheConstants.CACHE_GITHUB_SCRIPTS; +import static org.ngrinder.common.constant.CacheConstants.LOCAL_CACHE_GITHUB_GROOVY_PROJECT_SCRIPT_TYPE; +import static org.ngrinder.common.constant.CacheConstants.LOCAL_CACHE_GITHUB_SCRIPTS; import static org.ngrinder.common.constant.ControllerConstants.PROP_CONTROLLER_GITHUB_BASE_URL; import static org.ngrinder.common.util.AopUtils.proxy; import static org.ngrinder.common.util.CollectionUtils.buildMap; @@ -77,24 +78,29 @@ public class GitHubFileEntryService { private final GroovyMavenProjectScriptHandler groovyMavenProjectScriptHandler; + private final GroovyGradleProjectScriptHandler groovyGradleProjectScriptHandler; + private static final RateLimitHandlerEx rateLimitHandlerEx = new RateLimitHandlerEx(); public GitHubFileEntryService(FileEntryService fileEntryService, ObjectMapper objectMapper, Config config, @Lazy PerfTestService perfTestService, - GroovyMavenProjectScriptHandler groovyMavenProjectScriptHandler) { + GroovyMavenProjectScriptHandler groovyMavenProjectScriptHandler, + GroovyGradleProjectScriptHandler groovyGradleProjectScriptHandler) { this.fileEntryService = fileEntryService; this.objectMapper = objectMapper; this.config = config; this.perfTestService = perfTestService; this.groovyMavenProjectScriptHandler = groovyMavenProjectScriptHandler; + this.groovyGradleProjectScriptHandler = groovyGradleProjectScriptHandler; } public FileEntry getOne(GHRepository ghRepository, GitHubConfig gitHubConfig, String scriptPath) { String fullPath = getCheckoutDirPath(ghRepository, gitHubConfig, scriptPath); - if (proxy(this).isGroovyMavenProject(ghRepository, scriptPath, gitHubConfig.getBranch())) { - fullPath += groovyMavenProjectScriptHandler.getGroovyMavenPath(scriptPath); + String activeBranch = gitHubConfig.getBranch(); + if (isGroovyProjectScript(ghRepository, scriptPath, activeBranch)) { + fullPath += groovyMavenProjectScriptHandler.getGroovyProjectPath(scriptPath); FileEntry fileEntry = createGitHubScriptFileEntry(fullPath); - fileEntry.getProperties().put("type", "groovy-maven"); + fileEntry.getProperties().put("type", proxy(this).getGroovyProjectType(ghRepository, scriptPath, activeBranch)); fileEntry.getProperties().put("scriptPath", scriptPath); return fileEntry; } else { @@ -124,7 +130,7 @@ public void checkoutGitHubScript(PerfTest perfTest, GHRepository ghRepository, G File checkoutDir = new File(checkoutDirPath); SVNURL checkoutUrl = createCheckoutUrl(ghRepository, scriptPath, gitHubConfig.getBranch(), defaultBranch); - cleanUpGitHubStorage(svnClientManager.getStatusClient(), checkoutDir, checkoutUrl); + cleanUpGitHubStorage(svnClientManager.getStatusClient(), checkoutDir); perfTestService.markProgressAndStatus(perfTest, Status.CHECKOUT_SCRIPT, "Getting script from github."); if (!isSvnWorkingCopyDir(checkoutDir)) { @@ -148,7 +154,7 @@ public void checkoutGitHubScript(PerfTest perfTest, GHRepository ghRepository, G } } - private void cleanUpGitHubStorage(SVNStatusClient svnStatusClient, File checkoutDir, SVNURL checkoutUrl) { + private void cleanUpGitHubStorage(SVNStatusClient svnStatusClient, File checkoutDir) { try { SVNStatus svnStatus = svnStatusClient.doStatus(checkoutDir, true); if (!svnStatus.getRemoteRevision().equals(UNDEFINED)) { @@ -185,18 +191,31 @@ private boolean isSvnWorkingCopyDir(File directory) { return new File(directory.getPath() + "/.svn").exists(); } - @Cacheable(value = CACHE_GITHUB_IS_MAVEN_GROOVY, key = "#ghRepository.svnUrl + #scriptPath + #activeBranch") - public boolean isGroovyMavenProject(GHRepository ghRepository, String scriptPath, String activeBranch) { - if (!groovyMavenProjectScriptHandler.isGroovyMavenPath(scriptPath)) { + public boolean isGroovyProjectScript(GHRepository ghRepository, String scriptPath, String activeBranch) { + if (!groovyMavenProjectScriptHandler.isGroovyProjectScriptPath(scriptPath)) { return false; } + return proxy(this).getGroovyProjectType(ghRepository, scriptPath, activeBranch) != null; + } + @Cacheable(value = LOCAL_CACHE_GITHUB_GROOVY_PROJECT_SCRIPT_TYPE, key = "#ghRepository.svnUrl + #scriptPath + #activeBranch") + public String getGroovyProjectType(GHRepository ghRepository, String scriptPath, String activeBranch) { try { List ghContents = ghRepository.getDirectoryContent(groovyMavenProjectScriptHandler.getBasePath(scriptPath), activeBranch); - return ghContents.stream().anyMatch(ghContent -> ghContent.getName().equals("pom.xml")); - } catch (IOException e) { - return false; + for (GHContent ghContent : ghContents) { + String fileName = ghContent.getName(); + if (StringUtils.equals(fileName, groovyMavenProjectScriptHandler.getBuildScriptName())) { + return groovyMavenProjectScriptHandler.getKey(); + } + + if (StringUtils.equals(fileName, groovyGradleProjectScriptHandler.getBuildScriptName())) { + return groovyGradleProjectScriptHandler.getKey(); + } + } + } catch (IOException ignored) { + noOp(); } + return null; } private FileEntry createGitHubScriptFileEntry(String fullPath) { @@ -230,7 +249,7 @@ private String getCheckoutDirPath(GHRepository ghRepository, GitHubConfig gitHub try { String checkoutScriptPath; URI uri = new URI(getGitHubBaseUrl(gitHubConfig)); - if (proxy(this).isGroovyMavenProject(ghRepository, scriptPath, gitHubConfig.getBranch())) { + if (isGroovyProjectScript(ghRepository, scriptPath, gitHubConfig.getBranch())) { checkoutScriptPath = groovyMavenProjectScriptHandler.getBasePath(scriptPath); } else { checkoutScriptPath = getFullPath(scriptPath); @@ -331,7 +350,7 @@ private Map parseGitHubConfigurationErrorMessage(String errorMes * * @since 3.5.0 */ - @Cacheable(value = CACHE_GITHUB_SCRIPTS, key = "#user.userId") + @Cacheable(value = LOCAL_CACHE_GITHUB_SCRIPTS, key = "#user.userId") public Map> getScripts(User user) throws FileNotFoundException { Map> scriptMap = new HashMap<>(); getAllGitHubConfig(user).forEach(gitHubConfig -> { @@ -370,7 +389,7 @@ private SVNURL createCheckoutUrl(GHRepository ghRepository, String checkoutBaseUrl = ghRepository.getSvnUrl(); checkoutBaseUrl += isDefaultBranch ? "/trunk" : "/branches/" + activeBranch; SVNURL checkoutUrl; - if (proxy(this).isGroovyMavenProject(ghRepository, scriptPath, activeBranch)) { + if (isGroovyProjectScript(ghRepository, scriptPath, activeBranch)) { checkoutUrl = parseURIEncoded(checkoutBaseUrl + "/" + groovyMavenProjectScriptHandler.getBasePath(scriptPath)); } else { checkoutUrl = parseURIEncoded(checkoutBaseUrl + "/" + getFullPath(scriptPath)); @@ -424,13 +443,13 @@ private String getGitHubBaseUrl(GitHubConfig gitHubConfig) { return (!configuredGitHubBaseUrl.isEmpty()) ? configuredGitHubBaseUrl : config.getControllerProperties().getProperty(PROP_CONTROLLER_GITHUB_BASE_URL); } - @CacheEvict(value = CACHE_GITHUB_SCRIPTS, key = "#user.userId") + @CacheEvict(value = LOCAL_CACHE_GITHUB_SCRIPTS, key = "#user.userId") public void evictGitHubScriptCache(User user) { noOp(); } - @CacheEvict(value = CACHE_GITHUB_IS_MAVEN_GROOVY, key = "#ghRepository.svnUrl + #scriptPath + #activeBranch") - public void evictGitHubMavenGroovyCache(GHRepository ghRepository, String scriptPath, String activeBranch) { + @CacheEvict(value = LOCAL_CACHE_GITHUB_GROOVY_PROJECT_SCRIPT_TYPE, key = "#ghRepository.svnUrl + #scriptPath + #activeBranch") + public void evictGitHubGroovyProjectScriptTypeCache(GHRepository ghRepository, String scriptPath, String activeBranch) { noOp(); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/script/service/ScriptValidationService.java b/ngrinder-controller/src/main/java/org/ngrinder/script/service/ScriptValidationService.java index 5236e4f575..99b5d35a1b 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/script/service/ScriptValidationService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/script/service/ScriptValidationService.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.service; @@ -24,6 +24,7 @@ import org.ngrinder.common.util.Preconditions; import org.ngrinder.infra.config.Config; import org.ngrinder.model.IFileEntry; +import org.ngrinder.model.PerfTest; import org.ngrinder.model.User; import org.ngrinder.script.handler.ProcessingResultPrintStream; import org.ngrinder.script.handler.ScriptHandler; @@ -37,6 +38,7 @@ import java.io.File; import java.util.List; +import static java.nio.charset.Charset.defaultCharset; import static org.ngrinder.common.constant.ControllerConstants.PROP_CONTROLLER_VALIDATION_SYNTAX_CHECK; import static org.ngrinder.common.constant.ControllerConstants.PROP_CONTROLLER_VALIDATION_TIMEOUT; import static org.ngrinder.common.util.ExceptionUtils.processException; @@ -65,7 +67,7 @@ public class ScriptValidationService extends AbstractScriptValidationService { /* * (non-Javadoc) - * + * * @see * org.ngrinder.script.service.IScriptValidationService#validate(org * .ngrinder.model.User, org.ngrinder.model.IFileEntry, boolean, @@ -96,7 +98,11 @@ public String validate(User user, IFileEntry scriptIEntry, boolean useScriptInSV Preconditions.checkTrue(scriptDirectory.mkdirs(), "Script directory {} creation is failed."); ProcessingResultPrintStream processingResult = new ProcessingResultPrintStream(new ByteArrayOutputStream()); - handler.prepareDist(0L, user, scriptEntry, scriptDirectory, config.getControllerProperties(), processingResult); + + PerfTest dummyTest = new PerfTest(); + dummyTest.setId(0L); + + handler.prepareDist(dummyTest, user, scriptEntry, scriptDirectory, config.getControllerProperties(), processingResult); if (!processingResult.isSuccess()) { return new String(processingResult.getLogByteArray()); } @@ -110,7 +116,7 @@ public String validate(User user, IFileEntry scriptIEntry, boolean useScriptInSV } File doValidate = localScriptTestDriveService.doValidate(scriptDirectory, scriptFile, new Condition(), config.isSecurityEnabled(), config.getSecurityLevel(), hostString, getTimeout()); - List readLines = FileUtils.readLines(doValidate); + List readLines = FileUtils.readLines(doValidate, defaultCharset()); StringBuilder output = new StringBuilder(); File homeDirectory = config.getHome().getDirectory(); String absolutePath = homeDirectory.getAbsolutePath(); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/security/DefaultLoginPlugin.java b/ngrinder-controller/src/main/java/org/ngrinder/security/DefaultLoginPlugin.java index 9ac9ab1415..cfda0f5b95 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/security/DefaultLoginPlugin.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/security/DefaultLoginPlugin.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.security; @@ -51,7 +51,6 @@ public User loadUser(String userId) { return user; } - @SuppressWarnings("deprecation") @Override public boolean validateUser(String userId, String password, String encPass, Object encoder, Object salt) { if (StringUtils.isEmpty(password) || !((ShaPasswordEncoder) encoder).matches(String.valueOf(salt), password, encPass)) { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/security/NGrinderAuthenticationPreAuthProvider.java b/ngrinder-controller/src/main/java/org/ngrinder/security/NGrinderAuthenticationPreAuthProvider.java index 14ec0c753c..df189be574 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/security/NGrinderAuthenticationPreAuthProvider.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/security/NGrinderAuthenticationPreAuthProvider.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,11 +9,10 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.security; -import java.util.Date; import java.util.HashMap; import org.ngrinder.model.Role; @@ -27,19 +26,21 @@ import lombok.Setter; +import static java.time.Instant.now; + /** * nGrinder {@link PreAuthenticatedAuthenticationProvider}. - * + * * Some SSO system like SiteMinder doesn't need nGrinder login page. If the user info is resolved by plugins * implementing {@link javax.servlet.Filter} which stores the {@link Authentication} by following code, - * + * * * SecurityContextHolder.getContext().setAuthentication(authenticate); * - * + * * {@link NGrinderAuthenticationPreAuthProvider} will take this Authentication Object and handles user language and * timezone settings and user save - * + * * @since 3.0 */ public class NGrinderAuthenticationPreAuthProvider extends PreAuthenticatedAuthenticationProvider { @@ -51,10 +52,10 @@ public class NGrinderAuthenticationPreAuthProvider extends PreAuthenticatedAuthe /** * Authenticate the given PreAuthenticatedAuthenticationToken. - * + * * If the principal contained in the authentication object is null, the request will be ignored to allow other * providers to authenticate it. - * + * * @param authentication * authentication * @return authorized {@link Authentication} @@ -83,7 +84,7 @@ public Authentication authenticate(Authentication authentication) { /** * Add new user into local db. - * + * * @param securedUser * user */ @@ -91,7 +92,7 @@ public Authentication authenticate(Authentication authentication) { public void addNewUserIntoLocal(SecuredUser securedUser) { User user = securedUser.getUser(); user.setAuthProviderClass(securedUser.getUserInfoProviderClass()); - user.setCreatedDate(new Date()); + user.setCreatedAt(now()); User findOneByUserId = userService.getOne(user.getUserId()); if (findOneByUserId != null) { user = findOneByUserId.merge(user); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/security/NGrinderAuthenticationProvider.java b/ngrinder-controller/src/main/java/org/ngrinder/security/NGrinderAuthenticationProvider.java index 2c0f3f9325..f56c32dfe0 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/security/NGrinderAuthenticationProvider.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/security/NGrinderAuthenticationProvider.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.security; @@ -31,24 +31,22 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.ShaPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; -import java.util.Date; - +import static java.time.Instant.now; import static java.util.Arrays.asList; /** * nGrinder UserDetailsAuthenticationProvider. - * + * * This class validates the user provided ID / Password from login page. Internally it uses the plugins implementing * {@link OnLoginRunnable}. If you want to extend user authentification, please create the plugin implementing * {@link OnLoginRunnable} interface. - * + * * @since 3.0 */ @SuppressWarnings("UnusedDeclaration") @@ -57,34 +55,31 @@ public class NGrinderAuthenticationProvider extends AbstractUserDetailsAuthentic protected static final Logger LOG = LoggerFactory.getLogger(NGrinderAuthenticationProvider.class); + private final DefaultLoginPlugin defaultLoginPlugin; + private final DefaultLdapLoginPlugin defaultLdapLoginPlugin; + private final UserService userService; + + @Getter(AccessLevel.PROTECTED) + private final ShaPasswordEncoder passwordEncoder; + @Getter @Setter private PluginManager pluginManager; - private DefaultLoginPlugin defaultLoginPlugin; - - private DefaultLdapLoginPlugin defaultLdapLoginPlugin; - - @Getter(AccessLevel.PROTECTED) - private ShaPasswordEncoder passwordEncoder; - @Getter(AccessLevel.PROTECTED) @Setter - private UserDetailsService userDetailsService; - - private UserService userService; + private NGrinderUserDetailsService nGrinderUserDetailsService; public NGrinderAuthenticationProvider(PluginManager pluginManager, DefaultLoginPlugin defaultLoginPlugin, DefaultLdapLoginPlugin defaultLdapLoginPlugin, - @Lazy ShaPasswordEncoder passwordEncoder, UserDetailsService userDetailsService, UserService userService) { + @Lazy ShaPasswordEncoder passwordEncoder, NGrinderUserDetailsService nGrinderUserDetailsService, UserService userService) { this.pluginManager = pluginManager; this.defaultLoginPlugin = defaultLoginPlugin; this.defaultLdapLoginPlugin = defaultLdapLoginPlugin; this.passwordEncoder = passwordEncoder; - this.userDetailsService = userDetailsService; + this.nGrinderUserDetailsService = nGrinderUserDetailsService; this.userService = userService; } - @SuppressWarnings("deprecation") @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) { @@ -123,21 +118,21 @@ protected void additionalAuthenticationChecks(UserDetails userDetails, addNewUserIntoLocal(user); LOG.info("{} is saved by password {}", user.getUser().getUserId(), user.getUser().getPassword()); } else { - // update user information - userService.saveWithoutPasswordEncoding(user.getUser()); + // update user information without followers + userService.saveWithoutFollowers(user.getUser()); } } /** * Add new user into local db. - * + * * @param securedUser user */ @Transactional public void addNewUserIntoLocal(SecuredUser securedUser) { User user = securedUser.getUser(); user.setAuthProviderClass(securedUser.getUserInfoProviderClass()); - user.setCreatedDate(new Date()); + user.setCreatedAt(now()); User newUser = userService.getOne(user.getUserId()); if (newUser != null) { user = newUser.merge(user); @@ -150,8 +145,8 @@ public void addNewUserIntoLocal(SecuredUser securedUser) { } @Override - protected void doAfterPropertiesSet() throws Exception { - Assert.notNull(this.userDetailsService, "A UserDetailsService must be set"); + protected void doAfterPropertiesSet() { + Assert.notNull(this.nGrinderUserDetailsService, "A UserDetailsService must be set"); } @Override @@ -159,7 +154,7 @@ protected final UserDetails retrieveUser(String username, UsernamePasswordAuthen UserDetails loadedUser; try { - loadedUser = this.getUserDetailsService().loadUserByUsername(username); + loadedUser = this.nGrinderUserDetailsService.loadUserByUsername(username); } catch (UsernameNotFoundException notFound) { throw notFound; } catch (Exception repositoryProblem) { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/security/PluggablePreAuthFilter.java b/ngrinder-controller/src/main/java/org/ngrinder/security/PluggablePreAuthFilter.java index 7a8ced2c25..25c3122286 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/security/PluggablePreAuthFilter.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/security/PluggablePreAuthFilter.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.security; @@ -30,7 +30,7 @@ @Component public class PluggablePreAuthFilter implements Filter { - private CompositeFilter compositeFilter = new CompositeFilter(); + private final CompositeFilter compositeFilter = new CompositeFilter(); /** * load the servlet filter plugins. @@ -42,7 +42,7 @@ public void loadPlugins(PluginManager pluginManager) { /* * (non-Javadoc) - * + * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @@ -54,7 +54,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha /* * (non-Javadoc) - * + * * @see javax.servlet.Filter#destroy() */ @Override diff --git a/ngrinder-controller/src/main/java/org/ngrinder/security/SecuredUser.java b/ngrinder-controller/src/main/java/org/ngrinder/security/SecuredUser.java index 8f206263a6..c7ba3289f1 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/security/SecuredUser.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/security/SecuredUser.java @@ -52,7 +52,7 @@ public class SecuredUser implements UserDetails { * @param userInfoProviderClass class name who provides the user info */ public SecuredUser(User user, String userInfoProviderClass) { - this.setUser(user); + this.user = user; this.userInfoProviderClass = userInfoProviderClass; } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/security/SvnHttpBasicEntryPoint.java b/ngrinder-controller/src/main/java/org/ngrinder/security/SvnHttpBasicEntryPoint.java index 088bea2853..c8a2c62560 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/security/SvnHttpBasicEntryPoint.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/security/SvnHttpBasicEntryPoint.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,13 +9,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.security; import java.io.IOException; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -26,7 +25,7 @@ /** * Dynamic Realm returnable HttpBasic {@link AuthenticationEntryPoint}. - * + * * @since 3.2 */ @Component("svnHttpBasicEntryPoint") @@ -34,7 +33,7 @@ public class SvnHttpBasicEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, // LB - AuthenticationException authException) throws IOException, ServletException { + AuthenticationException authException) throws IOException { // Get the first part of url path and use it as a realm. String pathInfo = request.getPathInfo(); String[] split = StringUtils.split(pathInfo, '/'); diff --git a/ngrinder-controller/src/main/java/org/ngrinder/security/UserSwitchPermissionVoter.java b/ngrinder-controller/src/main/java/org/ngrinder/security/UserSwitchPermissionVoter.java index d2e7e7348f..d7330d328c 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/security/UserSwitchPermissionVoter.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/security/UserSwitchPermissionVoter.java @@ -18,9 +18,11 @@ import java.util.Collection; import java.util.List; +import lombok.AllArgsConstructor; import org.apache.commons.lang.StringUtils; import org.ngrinder.model.Role; import org.ngrinder.model.User; +import org.ngrinder.user.service.UserService; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.core.Authentication; @@ -33,8 +35,11 @@ * @since 3.2 */ @Component("userSwitchPermissionVoter") +@AllArgsConstructor public class UserSwitchPermissionVoter implements AccessDecisionVoter { + private final UserService userService; + @Override public boolean supports(ConfigAttribute attribute) { return true; @@ -54,8 +59,8 @@ public int vote(Authentication authentication, FilterInvocation filter, Collecti return ACCESS_DENIED; } SecuredUser secureUser = cast(authentication.getPrincipal()); - User user = secureUser.getUser(); - if (user.getRole() == Role.ADMIN) { + User loginUser = secureUser.getUser(); + if (loginUser.getRole() == Role.ADMIN) { return ACCESS_GRANTED; } @@ -63,6 +68,7 @@ public int vote(Authentication authentication, FilterInvocation filter, Collecti if (secureUser.getUsername().equals(realm)) { return ACCESS_GRANTED; } else { + User user = userService.getOneWithEagerFetch(loginUser.getUserId()); List owners = user.getOwners(); for (User each : owners) { if (realm.equals(each.getUserId())) { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/starter/InstallationChecker.java b/ngrinder-controller/src/main/java/org/ngrinder/starter/InstallationChecker.java new file mode 100644 index 0000000000..5d15e2b6b9 --- /dev/null +++ b/ngrinder-controller/src/main/java/org/ngrinder/starter/InstallationChecker.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2012-present NAVER Corp. + * + * This file is part of The nGrinder software distribution. Refer to + * the file LICENSE which is part of The nGrinder distribution for + * licensing details. The nGrinder distribution is available on the + * Internet at https://naver.github.io/ngrinder + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ngrinder.starter; + +import java.util.List; + +import static java.lang.System.*; +import static org.ngrinder.script.handler.GroovyGradleProjectScriptHandler.GRADLE_HOME_ENV_NAME; +import static org.ngrinder.script.handler.GroovyMavenProjectScriptHandler.MAVEN_HOME_ENV_NAME; +import static oshi.util.ExecutingCommand.runNative; + +/** + * + * Check If specific program is installed. + * + * @since 3.5.3 + * + * */ +public enum InstallationChecker { + + MAVEN(MAVEN_HOME_ENV_NAME, "mvn -version", + "Maven isn't installed, You can't run Maven groovy scripts. Please install Maven and set MAVEN_HOME. "), + GRADLE(GRADLE_HOME_ENV_NAME, "gradle -version", + "Gradle isn't installed, You can't run Gradle groovy scripts. Please install Gradle and set GRADLE_HOME."); + + private static final String CONSOLE_COLOR_YELLOW = "\033[0;33m"; + private static final String CONSOLE_COLOR_RESET = "\033[0m"; + + private final String homePath; + private final String installationCheckingCommand; + private final String warningMessage; + + InstallationChecker(String homeEnvName, String installationCheckingCommand, String warningMessage) { + this.warningMessage = warningMessage; + this.installationCheckingCommand = installationCheckingCommand; + + homePath = getenv(homeEnvName) == null ? "" : getenv(homeEnvName) + "/bin/"; + } + + public static void checkAll() { + for (InstallationChecker installationChecker : InstallationChecker.values()) { + if (!installationChecker.isInstalled()) { + installationChecker.printWarningMessage(); + } + } + } + + private boolean isInstalled() { + List result = runNative(homePath + installationCheckingCommand); + return !result.isEmpty(); + } + + private void printWarningMessage() { + out.print(CONSOLE_COLOR_YELLOW); + out.println("####################################################################################################################"); + out.println("# #"); + out.println("# WARNING: " + warningMessage + " #"); + out.println("# #"); + out.println("####################################################################################################################"); + out.print(CONSOLE_COLOR_RESET); + } + +} diff --git a/ngrinder-controller/src/main/java/org/ngrinder/starter/PortRangeValidator.java b/ngrinder-controller/src/main/java/org/ngrinder/starter/PortRangeValidator.java index c75d9c333d..c29628f3e7 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/starter/PortRangeValidator.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/starter/PortRangeValidator.java @@ -4,6 +4,8 @@ import com.beust.jcommander.ParameterException; public class PortRangeValidator implements IValueValidator { + + @SuppressWarnings("ConstantConditions") @Override public void validate(String name, Integer value) throws ParameterException { if (value > Character.MAX_VALUE && value < 0) { @@ -12,4 +14,4 @@ public void validate(String name, Integer value) throws ParameterException { } } -} \ No newline at end of file +} diff --git a/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserApiController.java b/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserApiController.java index 89c81e478d..34f3ecbc9d 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserApiController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserApiController.java @@ -31,6 +31,7 @@ import static org.springframework.data.domain.Sort.Direction.ASC; import static org.springframework.data.domain.Sort.by; +@SuppressWarnings({"JavaDoc", "SpringElInspection"}) @Slf4j @RestController @RequestMapping("/user/api") @@ -66,7 +67,7 @@ public List switchOptions(User user, @RequestParam(defaultValue = "") fina @GetMapping("/profile") public Map getOne(User user) { checkNotEmpty(user.getUserId(), "UserID should not be NULL!"); - User one = userService.getOneWithFollowers(user.getUserId()); + User one = userService.getOneWithEagerFetch(user.getUserId()); Map viewConfig = new HashMap<>(); viewConfig.put("allowPasswordChange", !config.isDemo()); @@ -88,8 +89,9 @@ public Map getOne(User user) { * @param user current user * @return app */ + @SuppressWarnings("unused") @GetMapping("/new") - @PreAuthorize("hasAnyRole('A') or #user.userId == #userId") + @PreAuthorize("hasAnyRole('A')") public Map openForm(User user) { User one = User.createNew(); @@ -117,7 +119,7 @@ public Map openForm(User user) { @GetMapping("/{userId}/detail") @PreAuthorize("hasAnyRole('A')") public Map getOneDetail(@PathVariable final String userId) { - User one = userService.getOneWithFollowers(userId); + User one = userService.getOneWithEagerFetch(userId); Map viewConfig = new HashMap<>(); viewConfig.put("allowPasswordChange", true); @@ -137,7 +139,7 @@ public Map getOneDetail(@PathVariable final String userId) { @GetMapping({"/list", "/list/"}) @PreAuthorize("hasAnyRole('A')") public Page getAll(@RequestParam(required = false) Role role, - @PageableDefault(page = 0, size = 10) Pageable pageable, + @PageableDefault Pageable pageable, @RequestParam(required = false) String keywords) { pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), defaultIfNull(pageable.getSort(), DEFAULT_SORT)); Pageable defaultPageable = PageRequest.of(0, pageable.getPageSize(), defaultIfNull(pageable.getSort(), DEFAULT_SORT)); @@ -280,7 +282,6 @@ public User update(User user, @PathVariable("userId") String userId, User update * Delete the user by the given userId. * * @param userId user id - * @return json message */ @DeleteMapping("/{userId}") @PreAuthorize("hasAnyRole('A')") diff --git a/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserController.java b/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserController.java index d9fc4296e7..6d0067b631 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserController.java @@ -32,6 +32,7 @@ * * @since 3.0 */ +@SuppressWarnings({"unused", "SpringMVCViewInspection"}) @Controller @RequestMapping("/user") @GlobalControllerModel @@ -56,6 +57,7 @@ public String userList(User user) { * * @return app */ + @SuppressWarnings({"SpringElInspection"}) @GetMapping("/new") @PreAuthorize("hasAnyRole('A') or #user.userId == #userId") public String openForm(User user) { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserSignUpApiController.java b/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserSignUpApiController.java index 0aecd59f85..018797d2a2 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserSignUpApiController.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/user/controller/UserSignUpApiController.java @@ -71,7 +71,6 @@ public Map signUpInfo() { * Save a user. * * @param newUser user to be added. - * @return success */ @PostMapping("/save") public void save(@RequestBody User newUser) { diff --git a/ngrinder-controller/src/main/java/org/ngrinder/user/repository/UserRepository.java b/ngrinder-controller/src/main/java/org/ngrinder/user/repository/UserRepository.java index 59535dabdd..aba7dce85c 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/user/repository/UserRepository.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/user/repository/UserRepository.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.user.repository; @@ -30,6 +30,7 @@ * * @since 3.0 */ +@SuppressWarnings("NullableProblems") @Repository public interface UserRepository extends JpaRepository, JpaSpecificationExecutor { /** @@ -38,7 +39,7 @@ public interface UserRepository extends JpaRepository, JpaSpecificat * @param spec spec * @return found {@link User} list */ - public List findAll(Specification spec); + List findAll(Specification spec); /** @@ -48,7 +49,7 @@ public interface UserRepository extends JpaRepository, JpaSpecificat * @param sort sort * @return found {@link User} list */ - public List findAllByRole(Role role, Sort sort); + List findAllByRole(Role role, Sort sort); /** * Find all {@link User}s for the given role. @@ -57,7 +58,7 @@ public interface UserRepository extends JpaRepository, JpaSpecificat * @param pageable pageable * @return found {@link User} list */ - public Page findAllByRole(Role role, Pageable pageable); + Page findAllByRole(Role role, Pageable pageable); /** @@ -66,7 +67,7 @@ public interface UserRepository extends JpaRepository, JpaSpecificat * @param userId user id * @return found {@link User}. null if not found. */ - public User findOneByUserId(String userId); + User findOneByUserId(String userId); /** @@ -76,6 +77,6 @@ public interface UserRepository extends JpaRepository, JpaSpecificat * @param pageable pageable * @return user list */ - public Page findAll(Specification spec, Pageable pageable); + Page findAll(Specification spec, Pageable pageable); } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/user/repository/UserSpecification.java b/ngrinder-controller/src/main/java/org/ngrinder/user/repository/UserSpecification.java index 3a76a1be2f..83856fec1a 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/user/repository/UserSpecification.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/user/repository/UserSpecification.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,15 +9,10 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.user.repository; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; - import org.ngrinder.model.User; import org.springframework.data.jpa.domain.Specification; @@ -35,13 +30,10 @@ private UserSpecification() { * @return created spec */ public static Specification nameLike(final String query) { - return new Specification() { - @Override - public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) { - String pattern = ("%" + query + "%").toLowerCase(); - return cb.or(cb.like(cb.lower(root.get("userName").as(String.class)), pattern), - cb.like(cb.lower(root.get("userId").as(String.class)), pattern)); - } + return (Specification) (root, criteriaQuery, cb) -> { + String pattern = ("%" + query + "%").toLowerCase(); + return cb.or(cb.like(cb.lower(root.get("userName").as(String.class)), pattern), + cb.like(cb.lower(root.get("userId").as(String.class)), pattern)); }; } @@ -51,12 +43,9 @@ public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, Cr * @return created spec */ public static Specification emailLike(final String query) { - return new Specification() { - @Override - public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) { - String pattern = ("%" + query + "%").toLowerCase(); - return cb.like(cb.lower(root.get("email").as(String.class)), pattern); - } + return (Specification) (root, criteriaQuery, cb) -> { + String pattern = ("%" + query + "%").toLowerCase(); + return cb.like(cb.lower(root.get("email").as(String.class)), pattern); }; } @@ -67,12 +56,7 @@ public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, Cr * @return {@link Specification} */ public static Specification idEqual(final Long id) { - return new Specification() { - @Override - public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { - return cb.equal(root.get("id"), id); - } - }; + return (Specification) (root, query, cb) -> cb.equal(root.get("id"), id); } } diff --git a/ngrinder-controller/src/main/java/org/ngrinder/user/service/UserService.java b/ngrinder-controller/src/main/java/org/ngrinder/user/service/UserService.java index 949fb2d19e..302f12cfca 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/user/service/UserService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/user/service/UserService.java @@ -39,12 +39,14 @@ import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; +import java.time.Instant; import java.util.ArrayList; -import java.util.Date; import java.util.List; +import static java.time.Instant.now; +import static org.apache.commons.lang.StringUtils.isBlank; import static org.hibernate.Hibernate.initialize; -import static org.ngrinder.common.constant.CacheConstants.CACHE_USERS; +import static org.ngrinder.common.constant.CacheConstants.DIST_CACHE_USERS; import static org.ngrinder.common.constant.CacheConstants.CACHE_USER_ENTITY; import static org.springframework.data.domain.Sort.Direction.*; import static org.springframework.data.domain.Sort.by; @@ -80,7 +82,7 @@ public UserService(UserRepository userRepository, PerfTestService perfTestServic @PostConstruct public void init() { - userCache = cacheManager.getCache(CACHE_USERS); + userCache = cacheManager.getCache(DIST_CACHE_USERS); userModelCache = cacheManager.getCache(CACHE_USER_ENTITY); } @@ -91,30 +93,28 @@ public void init() { * @return user */ @Transactional - @Cacheable(value = CACHE_USERS, key = "#userId") + @Cacheable(value = DIST_CACHE_USERS, key = "#userId") @Override public User getOne(String userId) { - User user = userRepository.findOneByUserId(userId); - if (user != null) { - initialize(user.getFollowers()); - } - return user; + return userRepository.findOneByUserId(userId); } /** - * Get user by user id with followers. + * Get user by user id with eager fetch. * * @param userId user id * @return user */ @Transactional - public User getOneWithFollowers(String userId) { - User one = userRepository.findOneByUserId(userId); - one.getFollowers().size(); - return one; + public User getOneWithEagerFetch(String userId) { + User user = userRepository.findOneByUserId(userId); + if (user != null) { + initialize(user.getOwners()); + initialize(user.getFollowers()); + } + return user; } - /** * Encoding given user's password. * @@ -127,7 +127,6 @@ public void encodePassword(User user) { } } - /** * Save user. * @@ -135,7 +134,7 @@ public void encodePassword(User user) { * @return User */ @Transactional - @CachePut(value = CACHE_USERS, key = "#user.userId") + @CachePut(value = DIST_CACHE_USERS, key = "#user.userId") @Override public User save(User user) { encodePassword(user); @@ -149,12 +148,27 @@ public User save(User user) { * @return User */ @Transactional - @CachePut(value = CACHE_USERS, key = "#user.userId") + @CachePut(value = DIST_CACHE_USERS, key = "#user.userId") @Override public User saveWithoutPasswordEncoding(User user) { final List followers = getFollowers(user.getFollowersStr()); user.setFollowers(followers); - if (user.getPassword() != null && StringUtils.isBlank(user.getPassword())) { + + User savedUser = saveWithoutFollowers(user); + + // Then expires new followers so that new followers info can be loaded. + for (User eachFollower : followers) { + userCache.evict(eachFollower.getUserId()); + userModelCache.evict(eachFollower.getId()); + } + prepareUserEnv(savedUser); + return savedUser; + } + + @Transactional + @CachePut(value = DIST_CACHE_USERS, key = "#user.userId") + public User saveWithoutFollowers(User user) { + if (user.getPassword() != null && isBlank(user.getPassword())) { user.setPassword(null); } final User existing = userRepository.findOneByUserId(user.getUserId()); @@ -169,14 +183,7 @@ public User saveWithoutPasswordEncoding(User user) { } user = existing.merge(user); } - User createdUser = userRepository.save(user); - // Then expires new followers so that new followers info can be loaded. - for (User eachFollower : followers) { - userCache.evict(eachFollower.getUserId()); - userModelCache.evict(eachFollower.getId()); - } - prepareUserEnv(createdUser); - return createdUser; + return userRepository.save(user); } private void prepareUserEnv(User user) { @@ -203,7 +210,7 @@ private List getFollowers(String followersStr) { */ @SuppressWarnings("SpringElInspection") @Transactional - @CacheEvict(value = CACHE_USERS, key = "#userId") + @CacheEvict(value = DIST_CACHE_USERS, key = "#userId") public void delete(String userId) { User user = getOne(userId); List deletePerfTests = perfTestService.deleteAll(user); @@ -275,16 +282,16 @@ public Page getPagedAll(String keyword, Pageable pageable) { * @return User */ @Transactional - @CachePut(value = CACHE_USERS, key = "#user.userId") + @CachePut(value = DIST_CACHE_USERS, key = "#user.userId") @Override public User createUser(User user) { encodePassword(user); - Date createdDate = new Date(); - user.setCreatedDate(createdDate); - user.setLastModifiedDate(createdDate); - User createdUser = getOne(ControllerConstants.NGRINDER_INITIAL_ADMIN_USERID); - user.setCreatedUser(createdUser); - user.setLastModifiedUser(createdUser); + Instant createdAt = now(); + user.setCreatedAt(createdAt); + user.setLastModifiedAt(createdAt); + User createdBy = getOne(ControllerConstants.NGRINDER_INITIAL_ADMIN_USERID); + user.setCreatedBy(createdBy); + user.setLastModifiedBy(createdBy); return saveWithoutPasswordEncoding(user); } diff --git a/ngrinder-controller/src/main/java/org/springframework/security/crypto/password/ShaPasswordEncoder.java b/ngrinder-controller/src/main/java/org/springframework/security/crypto/password/ShaPasswordEncoder.java index d870c6f734..20c124ee68 100644 --- a/ngrinder-controller/src/main/java/org/springframework/security/crypto/password/ShaPasswordEncoder.java +++ b/ngrinder-controller/src/main/java/org/springframework/security/crypto/password/ShaPasswordEncoder.java @@ -8,11 +8,10 @@ * * @since 3.5.0 */ -@SuppressWarnings("deprecation") public class ShaPasswordEncoder { private static final String PREFIX = "{"; private static final String SUFFIX = "}"; - private Digester digester; + private final Digester digester; /** * @param algorithm encryption algorithm diff --git a/ngrinder-controller/src/main/resources/application.yml b/ngrinder-controller/src/main/resources/application.yml index de3cbe0f6c..af6601cf10 100644 --- a/ngrinder-controller/src/main/resources/application.yml +++ b/ngrinder-controller/src/main/resources/application.yml @@ -1,5 +1,5 @@ ngrinder: - version: 3.5.2 + version: 3.5.3 server: default-encoding: UTF-8 @@ -33,3 +33,7 @@ spring: multipart: max-file-size: 100MB max-request-size: 100MB + h2: + console: + enabled: false + path: /h2-console diff --git a/ngrinder-controller/src/main/resources/ngrinder_datachange_logfile/db.changelog.xml b/ngrinder-controller/src/main/resources/ngrinder_datachange_logfile/db.changelog.xml index d92d335696..919829ade2 100644 --- a/ngrinder-controller/src/main/resources/ngrinder_datachange_logfile/db.changelog.xml +++ b/ngrinder-controller/src/main/resources/ngrinder_datachange_logfile/db.changelog.xml @@ -40,4 +40,5 @@ + diff --git a/ngrinder-controller/src/main/resources/ngrinder_datachange_logfile/db.changelog_schema_31.xml b/ngrinder-controller/src/main/resources/ngrinder_datachange_logfile/db.changelog_schema_31.xml new file mode 100644 index 0000000000..4ab70f1cbd --- /dev/null +++ b/ngrinder-controller/src/main/resources/ngrinder_datachange_logfile/db.changelog_schema_31.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + alter table PERF_TEST rename index created_user_index to created_by_index; + alter table PERF_TEST rename index last_modified_user_index to last_modified_by_index; + alter table NUSER rename index created_user_index to created_by_index; + alter table NUSER rename index last_modified_user_index to last_modified_by_index; + alter table TAG rename index created_user_index to created_by_index; + alter table TAG rename index last_modified_user_index to last_modified_by_index; + + + + + + alter index created_user_index rename to created_by_index_NUSER; + alter index last_modified_user_index_NUSER rename to last_modified_by_index_NUSER; + alter index created_user_index_PERF_TEST rename to created_by_index_PERF_TEST; + alter index last_modified_user_index_PERF_TEST rename to last_modified_by_index_PERF_TEST; + alter index created_user_index_TAG rename to created_by_index_TAG; + alter index last_modified_user_index_TAG rename to last_modified_by_index_TAG; + + + diff --git a/ngrinder-controller/src/main/resources/ngrinder_home_template/init.gradle b/ngrinder-controller/src/main/resources/ngrinder_home_template/init.gradle new file mode 100644 index 0000000000..589b6c074e --- /dev/null +++ b/ngrinder-controller/src/main/resources/ngrinder_home_template/init.gradle @@ -0,0 +1,8 @@ +allprojects { + apply plugin: "java" + + task __copyDependencies(type: Copy) { + from configurations.default + into project.hasProperty("outputDirectory") ? outputDirectory : "lib" + } +} diff --git a/ngrinder-controller/src/main/resources/script_template/groovy_gradle/build.gradle b/ngrinder-controller/src/main/resources/script_template/groovy_gradle/build.gradle new file mode 100644 index 0000000000..5e7222f5de --- /dev/null +++ b/ngrinder-controller/src/main/resources/script_template/groovy_gradle/build.gradle @@ -0,0 +1,24 @@ +apply plugin: "java" + +group = "ngrinder" +version = "0.0.1" + +sourceCompatibility = "1.8" +targetCompatibility = "1.8" + +compileJava.options.encoding = "UTF-8" +compileTestJava.options.encoding = "UTF-8" + +repositories { + mavenCentral() + jcenter() +} + +ext { + ngrinder_version = "3.5.3" +} + +dependencies { + compileOnly (group: "org.ngrinder", name: "ngrinder-groovy", version: ngrinder_version) + // implementation (group: "commons-io", name: "commons-io", version: "2.0.1") +} diff --git a/ngrinder-controller/src/main/resources/script_template/groovy_maven/src/main/java/TestRunner.groovy b/ngrinder-controller/src/main/resources/script_template/groovy_gradle/src/main/java/TestRunner.groovy similarity index 100% rename from ngrinder-controller/src/main/resources/script_template/groovy_maven/src/main/java/TestRunner.groovy rename to ngrinder-controller/src/main/resources/script_template/groovy_gradle/src/main/java/TestRunner.groovy diff --git a/ngrinder-controller/src/main/resources/script_template/groovy_maven/src/main/resources/resource1.txt b/ngrinder-controller/src/main/resources/script_template/groovy_gradle/src/main/resources/resource1.txt similarity index 100% rename from ngrinder-controller/src/main/resources/script_template/groovy_maven/src/main/resources/resource1.txt rename to ngrinder-controller/src/main/resources/script_template/groovy_gradle/src/main/resources/resource1.txt diff --git a/ngrinder-controller/src/main/resources/script_template/groovy_maven/pom.xml b/ngrinder-controller/src/main/resources/script_template/groovy_maven/pom.xml deleted file mode 100644 index 746c74842f..0000000000 --- a/ngrinder-controller/src/main/resources/script_template/groovy_maven/pom.xml +++ /dev/null @@ -1,68 +0,0 @@ - - 4.0.0 - ngrinder - ${name} - 0.0.1 - - - 3.5.2 - 1.8 - 1.8 - UTF-8 - - - - - ngrinder.maven.repo - https://github.com/naver/ngrinder/raw/ngrinder.maven.repo/releases - - - - - org.ngrinder - ngrinder-groovy - ${ngrinder.version} - provided - - - - - - - - - - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.9 - - - - org.eclipse.jdt.groovy.core.groovyNature - - - org.eclipse.m2e.core.maven2Nature - - - - - - - diff --git a/ngrinder-controller/src/test/java/org/ngrinder/agent/controller/AgentManagerApiControllerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/agent/controller/AgentManagerApiControllerTest.java index 174b5bb805..efbfa6166c 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/agent/controller/AgentManagerApiControllerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/agent/controller/AgentManagerApiControllerTest.java @@ -34,10 +34,10 @@ import java.io.IOException; import java.util.Map; +import static java.nio.charset.Charset.defaultCharset; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.spy; public class AgentManagerApiControllerTest extends AbstractNGrinderTransactionalTest { @@ -86,7 +86,7 @@ public void testGetAgentList() { File tmpDownFile; try { tmpDownFile = File.createTempFile("ngrinder", "zip", directory); - FileUtils.writeStringToFile(tmpDownFile, "test data"); + FileUtils.writeStringToFile(tmpDownFile, "test data", defaultCharset()); tmpDownFile.deleteOnExit(); } catch (IOException e) { e.printStackTrace(); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/agent/repository/AgentRepositoryTest.java b/ngrinder-controller/src/test/java/org/ngrinder/agent/repository/AgentRepositoryTest.java index da7fc85df0..5a7c1fc93b 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/agent/repository/AgentRepositoryTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/agent/repository/AgentRepositoryTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.agent.repository; @@ -19,9 +19,9 @@ import org.ngrinder.model.AgentInfo; import org.springframework.beans.factory.annotation.Autowired; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; public class AgentRepositoryTest extends AbstractNGrinderTransactionalTest { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/agent/service/AgentCountMapTest.java b/ngrinder-controller/src/test/java/org/ngrinder/agent/service/AgentCountMapTest.java index 5e66e4cdfd..110cd9f56e 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/agent/service/AgentCountMapTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/agent/service/AgentCountMapTest.java @@ -32,8 +32,8 @@ import static java.util.Arrays.asList; import static net.grinder.message.console.AgentControllerState.READY; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.ngrinder.common.util.NoOp.noOp; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/agent/service/AgentServiceTest.java b/ngrinder-controller/src/test/java/org/ngrinder/agent/service/AgentServiceTest.java index a552834f20..fe0b68fbc2 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/agent/service/AgentServiceTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/agent/service/AgentServiceTest.java @@ -11,10 +11,10 @@ import java.util.Set; import static java.util.stream.Collectors.toList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import static org.ngrinder.common.constant.CacheConstants.CACHE_RECENTLY_USED_AGENTS; +import static org.ngrinder.common.constant.CacheConstants.DIST_MAP_NAME_RECENTLY_USED_AGENTS; import static org.ngrinder.common.util.CollectionUtils.newHashSet; public class AgentServiceTest extends AbstractNGrinderTransactionalTest { @@ -39,7 +39,7 @@ public class AgentServiceTest extends AbstractNGrinderTransactionalTest { @Test public void selectAgentsTest() { Set recentlyUsedAgents = getRecentlyUsedAgents(); - hazelcastService.put(CACHE_RECENTLY_USED_AGENTS, TEST_USER_ID, recentlyUsedAgents); + hazelcastService.put(DIST_MAP_NAME_RECENTLY_USED_AGENTS, TEST_USER_ID, recentlyUsedAgents); User testUser = new User(); testUser.setUserId(TEST_USER_ID); @@ -65,7 +65,7 @@ public void selectAgentsTest() { recentlyUsedAgents.add(createAgentInfo("test-agent-11", "test-region_owned_test-user")); recentlyUsedAgents.add(createAgentInfo("test-agent-14", "test-region_owned_test-user")); - hazelcastService.put(CACHE_RECENTLY_USED_AGENTS, TEST_USER_ID, recentlyUsedAgents); + hazelcastService.put(DIST_MAP_NAME_RECENTLY_USED_AGENTS, TEST_USER_ID, recentlyUsedAgents); // Add owned agents for another test. allFreeAgents.add(createAgentInfo("test-agent-8", "test-region_owned_test-user")); @@ -85,7 +85,7 @@ public void selectAgentsTest() { assertTrue(selectedAgents.contains(createAgentInfo("test-agent-11", "test-region_owned_test-user"))); assertTrue(selectedAgents.contains(createAgentInfo("test-agent-14", "test-region_owned_test-user"))); - hazelcastService.delete(CACHE_RECENTLY_USED_AGENTS, TEST_USER_ID); + hazelcastService.delete(DIST_MAP_NAME_RECENTLY_USED_AGENTS, TEST_USER_ID); } private Set getRecentlyUsedAgents() { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/agent/service/MockAgentService.java b/ngrinder-controller/src/test/java/org/ngrinder/agent/service/MockAgentService.java index 485151756a..10cc0372e7 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/agent/service/MockAgentService.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/agent/service/MockAgentService.java @@ -18,7 +18,7 @@ import java.util.Set; -import static org.ngrinder.common.constant.CacheConstants.CACHE_RECENTLY_USED_AGENTS; +import static org.ngrinder.common.constant.CacheConstants.DIST_MAP_NAME_RECENTLY_USED_AGENTS; @Profile("unit-test") @Service @@ -44,7 +44,7 @@ public synchronized void runAgent(User user, final SingleConsole singleConsole, final Set allFreeAgents = getAllAttachedFreeApprovedAgentsForUser(user.getUserId()); final Set necessaryAgents = selectAgent(user, allFreeAgents, agentCount); - hazelcastService.put(CACHE_RECENTLY_USED_AGENTS, user.getUserId(), necessaryAgents); + hazelcastService.put(DIST_MAP_NAME_RECENTLY_USED_AGENTS, user.getUserId(), necessaryAgents); LOGGER.info("{} agents are starting for user {}", agentCount, user.getUserId()); for (AgentInfo agentInfo : necessaryAgents) { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/common/model/HomeTest.java b/ngrinder-controller/src/test/java/org/ngrinder/common/model/HomeTest.java index cf09bb3fa9..bb75b47288 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/common/model/HomeTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/common/model/HomeTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.model; @@ -21,7 +21,7 @@ import java.io.File; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class HomeTest extends AbstractNGrinderTransactionalTest { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/common/service/ModelAspectTest.java b/ngrinder-controller/src/test/java/org/ngrinder/common/service/ModelAspectTest.java index d2290af575..548562754c 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/common/service/ModelAspectTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/common/service/ModelAspectTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.service; @@ -21,10 +21,10 @@ import org.ngrinder.model.BaseModel; import org.springframework.beans.factory.annotation.Autowired; -import java.util.Date; +import java.time.Instant; import static org.hamcrest.Matchers.is; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import static org.springframework.test.util.ReflectionTestUtils.setField; @@ -44,7 +44,7 @@ public void testModelAspect() { BaseModel baseModel = mock(BaseModel.class); when(joinPoint.getArgs()).thenReturn(new Object[] { baseModel }); modelAspect.beforeSave(joinPoint); - verify(baseModel, times(1)).setCreatedDate(any(Date.class)); + verify(baseModel, times(1)).setCreatedAt(any(Instant.class)); } @Test @@ -58,6 +58,6 @@ public void testModelAspectOnServletContext() { when(joinPoint.getArgs()).thenReturn(new Object[] { baseModel }); setField(modelAspect, "springContext", springContext); modelAspect.beforeSave(joinPoint); - verify(baseModel, times(1)).setLastModifiedDate(any(Date.class)); + verify(baseModel, times(1)).setLastModifiedAt(any(Instant.class)); } } diff --git a/ngrinder-controller/src/test/java/org/ngrinder/common/util/EncodingUtilsTest.java b/ngrinder-controller/src/test/java/org/ngrinder/common/util/EncodingUtilsTest.java index bf3042f992..6683d094fe 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/common/util/EncodingUtilsTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/common/util/EncodingUtilsTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,12 +9,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.*; import java.io.IOException; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/common/util/FileDownloadUtilsTest.java b/ngrinder-controller/src/test/java/org/ngrinder/common/util/FileDownloadUtilsTest.java index db0ea4e7bc..9776e19172 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/common/util/FileDownloadUtilsTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/common/util/FileDownloadUtilsTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,12 +9,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.io.IOException; @@ -37,14 +37,14 @@ public void testDownloadFileHttpServletResponseString() throws IOException { assertThat(lengthHeader, is(String.valueOf(downFile.length()))); } - + @Test public void testDownloadNotExistFile() throws IOException { File downFile = null; HttpServletResponse resp = new MockHttpServletResponse(); boolean result = FileDownloadUtils.downloadFile(resp, downFile); assertThat(result, is(false)); - + downFile = new File("Not-existed-file"); result = FileDownloadUtils.downloadFile(resp, downFile); assertThat(result, is(false)); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/common/util/JsonUtilsTest.java b/ngrinder-controller/src/test/java/org/ngrinder/common/util/JsonUtilsTest.java index 0261b345d4..e23e1b3cd1 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/common/util/JsonUtilsTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/common/util/JsonUtilsTest.java @@ -5,8 +5,9 @@ import java.util.HashMap; import java.util.Map; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNull; public class JsonUtilsTest { private static class NumberModel { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/common/util/LoggingUtilsTest.java b/ngrinder-controller/src/test/java/org/ngrinder/common/util/LoggingUtilsTest.java new file mode 100644 index 0000000000..9b3c4d39df --- /dev/null +++ b/ngrinder-controller/src/test/java/org/ngrinder/common/util/LoggingUtilsTest.java @@ -0,0 +1,57 @@ +package org.ngrinder.common.util; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.ngrinder.model.PerfTest; +import org.ngrinder.model.User; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.ngrinder.common.util.LoggingUtils.format; + +/* + * Copyright (c) 2012-present NAVER Corp. + * + * This file is part of The nGrinder software distribution. Refer to + * the file LICENSE which is part of The nGrinder distribution for + * licensing details. The nGrinder distribution is available on the + * Internet at https://naver.github.io/ngrinder + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class LoggingUtilsTest { + + private static PerfTest perfTest; + + @BeforeClass + public static void init() { + User user = new User(); + user.setUserId("format test user"); + + perfTest = new PerfTest(); + perfTest.setId(12345678L); + perfTest.setCreatedBy(user); + } + + @Test + public void formatTest() { + assertThat(format(perfTest, "Test is started."), is("[12345678][format test user] Test is started.")); + assertThat(format(perfTest, "{} test is {} started at {}.", "Beautiful", 777, 113.44544), + is("[12345678][format test user] Beautiful test is 777 started at 113.44544.")); + + assertThat(format(null, "Test is started."), is("Test is started.")); + + perfTest.setCreatedBy(null); + assertThat(format(perfTest, "Test is started."), is("Test is started.")); + } +} diff --git a/ngrinder-controller/src/test/java/org/ngrinder/common/util/UnitUtilTest.java b/ngrinder-controller/src/test/java/org/ngrinder/common/util/UnitUtilTest.java index fc2fc3e1ee..645ee37fd6 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/common/util/UnitUtilTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/common/util/UnitUtilTest.java @@ -1,7 +1,7 @@ package org.ngrinder.common.util; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import net.grinder.util.UnitUtils; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/home/controller/HomeControllerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/home/controller/HomeControllerTest.java index 6d8d2d9982..8897dd6e29 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/home/controller/HomeControllerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/home/controller/HomeControllerTest.java @@ -26,9 +26,9 @@ import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.i18n.CookieLocaleResolver; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; import java.util.Map; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/home/service/HomeServiceTest.java b/ngrinder-controller/src/test/java/org/ngrinder/home/service/HomeServiceTest.java index 05606c6f14..9145722a31 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/home/service/HomeServiceTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/home/service/HomeServiceTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.home.service; @@ -21,8 +21,8 @@ import java.io.IOException; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; public class HomeServiceTest extends AbstractNGrinderTransactionalTest { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/home/service/HomeServiceTestWithAtom.java b/ngrinder-controller/src/test/java/org/ngrinder/home/service/HomeServiceTestWithAtom.java index 3a6c69d08e..b04962de22 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/home/service/HomeServiceTestWithAtom.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/home/service/HomeServiceTestWithAtom.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.home.service; @@ -18,8 +18,8 @@ import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; public class HomeServiceTestWithAtom { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/infra/config/ConfigTest.java b/ngrinder-controller/src/test/java/org/ngrinder/infra/config/ConfigTest.java index 6e0f78b089..90dc240ea9 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/infra/config/ConfigTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/infra/config/ConfigTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.config; @@ -24,8 +24,8 @@ import java.io.File; import java.util.Properties; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/infra/init/ClassPathInitTest.java b/ngrinder-controller/src/test/java/org/ngrinder/infra/init/ClassPathInitTest.java index a4888c0122..68762b2c48 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/infra/init/ClassPathInitTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/infra/init/ClassPathInitTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,13 +9,13 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.init; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; import java.io.File; import java.util.Collection; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/infra/init/DBInitTest.java b/ngrinder-controller/src/test/java/org/ngrinder/infra/init/DBInitTest.java index 4dbca5c9e2..56e9944d81 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/infra/init/DBInitTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/infra/init/DBInitTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.init; @@ -24,8 +24,8 @@ import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; public class DBInitTest extends org.ngrinder.AbstractNGrinderTransactionalTest { @Autowired diff --git a/ngrinder-controller/src/test/java/org/ngrinder/infra/spring/RemainedPathResolverTest.java b/ngrinder-controller/src/test/java/org/ngrinder/infra/spring/RemainedPathResolverTest.java index 01f15c258c..0a8bdb7ba9 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/infra/spring/RemainedPathResolverTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/infra/spring/RemainedPathResolverTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.spring; @@ -20,8 +20,8 @@ import javax.servlet.http.HttpServletRequest; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/infra/spring/UserHandlerMethodArgumentResolverTest.java b/ngrinder-controller/src/test/java/org/ngrinder/infra/spring/UserHandlerMethodArgumentResolverTest.java index 2f9f0918d5..0391668fce 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/infra/spring/UserHandlerMethodArgumentResolverTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/infra/spring/UserHandlerMethodArgumentResolverTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,12 +9,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra.spring; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.ngrinder.common.util.TypeConvertUtils.cast; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/operation/AnnouncementControllerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/operation/AnnouncementControllerTest.java index a073cb5ef9..dceb537d2d 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/operation/AnnouncementControllerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/operation/AnnouncementControllerTest.java @@ -13,8 +13,8 @@ */ package org.ngrinder.operation; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; import org.junit.Test; import org.ngrinder.AbstractNGrinderTransactionalTest; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/operation/ScriptConsoleControllerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/operation/ScriptConsoleControllerTest.java index 489c432275..4d03a2ecc5 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/operation/ScriptConsoleControllerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/operation/ScriptConsoleControllerTest.java @@ -13,8 +13,8 @@ */ package org.ngrinder.operation; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; import static org.ngrinder.common.util.CollectionUtils.buildMap; import org.junit.Test; @@ -33,7 +33,7 @@ public void runScriptTest() { Map param = buildMap("script", ""); result = scriptController.run(param); - assertThat((String) result.get("result"), isEmptyString()); + assertThat((String) result.get("result"), is(emptyString())); param.put("script", "print \'hello\'"); result = scriptController.run(param); assertThat(result.get("result"), notNullValue()); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/operation/SystemConfigControllerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/operation/SystemConfigControllerTest.java index 3b418a12a5..c882b26c59 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/operation/SystemConfigControllerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/operation/SystemConfigControllerTest.java @@ -13,9 +13,9 @@ */ package org.ngrinder.operation; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; import org.junit.Test; import org.ngrinder.AbstractNGrinderTransactionalTest; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/MockPerfTestApiController.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/MockPerfTestApiController.java index b25cbc09a1..5a7191aee4 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/MockPerfTestApiController.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/MockPerfTestApiController.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.controller; @@ -26,7 +26,6 @@ import org.ngrinder.user.service.UserContext; import org.ngrinder.user.service.UserService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.MessageSource; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import org.springframework.test.util.ReflectionTestUtils; @@ -48,8 +47,12 @@ public class MockPerfTestApiController extends PerfTestApiController { @Autowired private Config config; - public MockPerfTestApiController(PerfTestService perfTestService, TagService tagService, AgentManager agentManager, RegionService regionService, AgentService agentService, FileEntryService fileEntryService, UserService userService, HazelcastService hazelcastService, ScriptHandlerFactory scriptHandlerFactory, UserContext userContext, Config config, MessageSource messageSource) { - super(perfTestService, tagService, agentManager, regionService, agentService, fileEntryService, userService, hazelcastService, scriptHandlerFactory, userContext, config, messageSource); + public MockPerfTestApiController(PerfTestService perfTestService, TagService tagService, AgentManager agentManager, + RegionService regionService, AgentService agentService, FileEntryService fileEntryService, + UserService userService, HazelcastService hazelcastService, ScriptHandlerFactory scriptHandlerFactory, + UserContext userContext, Config config) { + super(perfTestService, tagService, agentManager, regionService, agentService, fileEntryService, + userService, hazelcastService, scriptHandlerFactory, userContext, config); } @PostConstruct diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/PerfTestControllerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/PerfTestControllerTest.java index b90933321e..530a7fdb92 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/PerfTestControllerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/PerfTestControllerTest.java @@ -13,6 +13,8 @@ */ package org.ngrinder.perftest.controller; +import static java.time.Instant.now; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.ngrinder.common.constant.WebConstants.PARAM_TEST; @@ -42,7 +44,6 @@ import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -87,7 +88,7 @@ public void testInvalidPerfTest() { @Test public void testGetPerfTestDetail() { - PerfTest createPerfTest = createPerfTest("hello", Status.READY, new Date()); + PerfTest createPerfTest = createPerfTest("hello", Status.READY, now()); Map response = perfTestApiController.getOneDetail(getTestUser(), createPerfTest.getId()); assertNotNull(response.get(PARAM_TEST)); } @@ -104,11 +105,11 @@ public void testGetResourcesOnScriptFolder() throws IOException { @Test public void testDeleteTests() { String testName = "test1"; - PerfTest test = createPerfTest(testName, Status.READY, new Date()); + PerfTest test = createPerfTest(testName, Status.READY, now()); perfTestApiController.delete(getTestUser(), String.valueOf(test.getId())); - PerfTest test1 = createPerfTest(testName, Status.READY, new Date()); - PerfTest test2 = createPerfTest(testName, Status.READY, new Date()); + PerfTest test1 = createPerfTest(testName, Status.READY, now()); + PerfTest test2 = createPerfTest(testName, Status.READY, now()); Function, PerfTest> perfTestOf = map -> (PerfTest) map.get(PARAM_TEST); @@ -160,7 +161,7 @@ public void testSavePerfTestCloneAndLeaveCommentAndStop() { public void testSavePerfTestExist() { String testName = "test1"; String newName = "new test1"; - PerfTest test = createPerfTest(testName, Status.READY, new Date()); + PerfTest test = createPerfTest(testName, Status.READY, now()); test.setTestName(newName); PerfTest newTest = new PerfTest(); @@ -205,7 +206,7 @@ public void testSavePerfTestExist() { @Test public void testGetTestList() { - createPerfTest("new test1", Status.READY, new Date()); + createPerfTest("new test1", Status.READY, now()); Map response = perfTestApiController.getAllList(getTestUser(), null, null, null, PageRequest.of(0, 10)); assertThat(((List) response.get("tests")).size(), is(1)); } @@ -213,7 +214,7 @@ public void testGetTestList() { @Test public void testGetTestListByAdmin() { String testName = "new test1"; - createPerfTest(testName, Status.READY, new Date()); + createPerfTest(testName, Status.READY, now()); User testAdmin = new User(); testAdmin.setUserId("testAdmin"); testAdmin.setPassword("testAdmin"); @@ -229,7 +230,7 @@ public void testGetTestListByAdmin() { @Test public void testGetTestListByOtherUser() { String testName = "new test1"; - PerfTest test = createPerfTest(testName, Status.READY, new Date()); + PerfTest test = createPerfTest(testName, Status.READY, now()); User otherTestUser = new User(); otherTestUser.setUserId("testUser"); @@ -253,7 +254,7 @@ public void testGetTestListByOtherUser() { @Test public void testGetTestListByKeyWord() { String strangeName = "DJJHG^%R&*^%^565(^%&^%(^%(^"; - createPerfTest(strangeName, Status.READY, new Date()); + createPerfTest(strangeName, Status.READY, now()); Sort sort = Sort.by(Sort.Direction.ASC, "testName"); Pageable pageable = PageRequest.of(0, 10, sort); @@ -267,7 +268,7 @@ public void testGetTestListByKeyWord() { @Test public void testGetReportData() { String testName = "test1"; - PerfTest test = createPerfTest(testName, Status.FINISHED, new Date()); + PerfTest test = createPerfTest(testName, Status.FINISHED, now()); controller.getReport(test.getId()); perfTestApiController.getPerfGraph(test.getId(), "TPS,mean_time(ms)", true, 0); @@ -278,7 +279,7 @@ public void testGetReportData() { @Test public void testGetMonitorData() { String testName = "test1"; - PerfTest test = createPerfTest(testName, Status.FINISHED, new Date()); + PerfTest test = createPerfTest(testName, Status.FINISHED, now()); perfTestApiController.getMonitorGraph(test.getId(), "127.0.0.1", 0); long testId = 123456L; @@ -288,7 +289,7 @@ public void testGetMonitorData() { @Test public void testDownloadReportData() { String testName = "test1"; - PerfTest test = createPerfTest(testName, Status.FINISHED, new Date()); + PerfTest test = createPerfTest(testName, Status.FINISHED, now()); HttpServletResponse resp = new MockHttpServletResponse(); try { controller.downloadCSV(getTestUser(), test.getId(), resp); @@ -304,7 +305,7 @@ public void testDownloadReportData() { public void testRefreshTestRunning() { String testName = "test1"; // it is not a running test, can not test get statistic data. - PerfTest test = createPerfTest(testName, Status.TESTING, new Date()); + PerfTest test = createPerfTest(testName, Status.TESTING, now()); test.setPort(11011); try { perfTestApiController.refreshTestRunning(getTestUser(), test.getId()); @@ -316,9 +317,9 @@ public void testRefreshTestRunning() { @Test public void testUpdateStatus() { String testName = "test1"; - PerfTest test = createPerfTest(testName, Status.TESTING, new Date()); + PerfTest test = createPerfTest(testName, Status.TESTING, now()); String testName2 = "test1"; - PerfTest test2 = createPerfTest(testName2, Status.START_AGENTS, new Date()); + PerfTest test2 = createPerfTest(testName2, Status.START_AGENTS, now()); String ids = test.getId() + "," + test2.getId(); Map response = perfTestApiController.getStatuses(getTestUser(), ids); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/PerfTestControllerWithRepoTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/PerfTestControllerWithRepoTest.java index 314ed40044..97eaf60690 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/PerfTestControllerWithRepoTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/controller/PerfTestControllerWithRepoTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.controller; @@ -29,11 +29,11 @@ import java.util.Map; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * {@link PerfTestController} test with repository supports. - * + * * @since 3.0 */ public class PerfTestControllerWithRepoTest extends AbstractAgentReadyTest { @@ -46,7 +46,7 @@ public class PerfTestControllerWithRepoTest extends AbstractAgentReadyTest { /** * Locate dumped user1 repo into tempdir. - * + * * @throws IOException */ @Before diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/model/PerfTestTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/model/PerfTestTest.java index fe44d68dc7..60f11152e6 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/model/PerfTestTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/model/PerfTestTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.model; @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class PerfTestTest { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/repository/PerfTestRepositoryTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/repository/PerfTestRepositoryTest.java index 0afc8cfb83..60f74f22bd 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/repository/PerfTestRepositoryTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/repository/PerfTestRepositoryTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.repository; @@ -27,7 +27,7 @@ import java.util.TreeSet; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; import static org.ngrinder.perftest.repository.PerfTestSpecification.idEqual; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/AbstractPerfTestTransactionalTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/AbstractPerfTestTransactionalTest.java index a77935f14d..4d9e2acc49 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/AbstractPerfTestTransactionalTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/AbstractPerfTestTransactionalTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; @@ -23,9 +23,12 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import java.time.Instant; import java.util.Date; import java.util.List; +import static org.ngrinder.common.util.ObjectUtils.defaultIfNull; + /** * In addition {@link org.ngrinder.AbstractNGrinderTransactionalTest}, this class provides basic function to * create {@link org.ngrinder.model.PerfTest} and run the test. @@ -61,7 +64,7 @@ public void clearAllPerfTest() { tagRepository.flush(); } - public PerfTest newPerfTest(String testName, Status status, Date scheduledTime) { + public PerfTest newPerfTest(String testName, Status status, Instant scheduledTime) { PerfTest test = new PerfTest(); test.setTestName(testName); test.setThreshold("D"); @@ -78,14 +81,14 @@ public PerfTest newPerfTest(String testName, Status status, Date scheduledTime) test.setRampUpInitSleepTime(0); test.setRampUpIncrementInterval(1000); test.setStatus(status); - test.setCreatedUser(getTestUser()); + test.setCreatedBy(getTestUser()); test.setRegion(config.getRegion()); test.setSamplingInterval(1); test.setScm("svn"); return test; } - public PerfTest createPerfTest(String testName, Status status, Date scheduledTime) { + public PerfTest createPerfTest(String testName, Status status, Instant scheduledTime) { PerfTest perftest = newPerfTest(testName, status, scheduledTime); return createPerfTest(perftest); } diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ClusteredPerfTestServiceTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ClusteredPerfTestServiceTest.java index ac02c56eba..2d76aef51c 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ClusteredPerfTestServiceTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ClusteredPerfTestServiceTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,12 +9,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ConsoleEntryTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ConsoleEntryTest.java index 832dd2f86f..349d716323 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ConsoleEntryTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ConsoleEntryTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,13 +9,13 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Test; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ConsoleManagerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ConsoleManagerTest.java index 18ec1c8559..68a922ea51 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ConsoleManagerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/ConsoleManagerTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; @@ -28,7 +28,7 @@ import java.util.List; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; import static org.ngrinder.common.util.NoOp.noOp; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/MockPerfTestRunnable.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/MockPerfTestRunnable.java index 5b2e706eb3..24ea81aae8 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/MockPerfTestRunnable.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/MockPerfTestRunnable.java @@ -49,7 +49,7 @@ public MockPerfTestRunnable(PerfTestService perfTestService, AgentManager agentM void startAgentsOn(PerfTest perfTest, GrinderProperties grinderProperties, SingleConsole singleConsole) { getPerfTestService().markStatusAndProgress(perfTest, START_AGENTS, perfTest.getAgentCount() + " agents are starting."); - getAgentService().runAgent(perfTest.getLastModifiedUser(), singleConsole, grinderProperties, + getAgentService().runAgent(perfTest, singleConsole, grinderProperties, perfTest.getAgentCount()); getPerfTestService().markStatusAndProgress(perfTest, START_AGENTS_FINISHED, perfTest.getAgentCount() + " agents are started."); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/NumberFormatTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/NumberFormatTest.java index a6e22b8a3f..7a753c02a1 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/NumberFormatTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/NumberFormatTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,12 +9,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.util.HashMap; import java.util.Map; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestCancellationTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestCancellationTest.java index ca5936e815..d2eaa09379 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestCancellationTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestCancellationTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; @@ -33,9 +33,10 @@ import java.io.IOException; import java.util.List; +import static java.nio.charset.Charset.defaultCharset; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; public class PerfTestCancellationTest extends AbstractAgentReadyTest implements ControllerConstants { @@ -69,7 +70,7 @@ public void before() throws IOException { FileEntry fileEntry = new FileEntry(); fileEntry.setPath("test1.py"); - String worldString = IOUtils.toString(new ClassPathResource("world.py").getInputStream()); + String worldString = IOUtils.toString(new ClassPathResource("world.py").getInputStream(), defaultCharset()); if (fileEntry.getFileType().isEditable()) { fileEntry.setContent(worldString); } else { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestProcessAndThreadPolicyServiceTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestProcessAndThreadPolicyServiceTest.java index 70123a2730..b478662b41 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestProcessAndThreadPolicyServiceTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestProcessAndThreadPolicyServiceTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,12 +9,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Test; import org.ngrinder.AbstractNGrinderTransactionalTest; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestRunnableTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestRunnableTest.java index 602c9a4bc6..69dd88746c 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestRunnableTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestRunnableTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; @@ -41,9 +41,10 @@ import java.util.ArrayList; import java.util.List; +import static java.nio.charset.Charset.defaultCharset; import static net.grinder.message.console.AgentControllerState.READY; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.ngrinder.common.util.TypeConvertUtils.cast; public class PerfTestRunnableTest extends AbstractAgentReadyTest implements ControllerConstants { @@ -196,7 +197,7 @@ private void prepareUserRepo() throws IOException { FileEntry fileEntry = new FileEntry(); fileEntry.setPath("/hello/world.py"); - String worldString = IOUtils.toString(new ClassPathResource("world.py").getInputStream()); + String worldString = IOUtils.toString(new ClassPathResource("world.py").getInputStream(), defaultCharset()); fileEntry.setContent(worldString); fileEntry.setFileType(FileType.PYTHON_SCRIPT); fileEntityRepository.save(getTestUser(), fileEntry, "UTF-8"); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestServiceTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestServiceTest.java index 0c697efff6..e22e100b3c 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestServiceTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/PerfTestServiceTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; @@ -35,12 +35,14 @@ import java.io.File; import java.io.IOException; +import java.time.Instant; import java.util.*; import java.util.function.Predicate; +import static java.time.Instant.now; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; @@ -63,8 +65,8 @@ public void clearPerfTest() { @Test public void testGetTestListAll() { - createPerfTest("new Test1", Status.TESTING, new Date()); - createPerfTest("new Test2", Status.FINISHED, new Date()); + createPerfTest("new Test1", Status.TESTING, now()); + createPerfTest("new Test2", Status.FINISHED, now()); PerfTest candidate = testService.getNextRunnablePerfTestPerfTestCandidate(); assertThat(candidate, nullValue()); @@ -85,12 +87,12 @@ public void testGetTestListAll() { assertThat(list.size(), is(1)); for (PerfTest test : list) { - long systemTimeMills = System.currentTimeMillis(); - test.setStartTime(new Date(systemTimeMills)); + Instant now = now(); + test.setStartTime(now); PerfTest testTemp = testService.getOne(getTestUser(), test.getId()); assertThat(testTemp.getId(), is(test.getId())); - assertThat(testTemp.getStartTime().getTime(), is(systemTimeMills)); + assertThat(testTemp.getStartTime(), is(now)); testService.markAbnormalTermination(testTemp, StopReason.CANCEL_BY_USER); testService.markProgress(testTemp, "this test will be TESTING again"); @@ -107,18 +109,18 @@ public void testGetTestListAll() { } - createPerfTest("new Test2", Status.getProcessingOrTestingTestStatus()[0], new Date()); + createPerfTest("new Test2", Status.getProcessingOrTestingTestStatus()[0], now()); list = testService.getCurrentlyRunningTest(); assertThat(list.size(), is(2)); - PerfTest finishedTest = createPerfTest("new Test3", Status.ABNORMAL_TESTING, new Date()); + PerfTest finishedTest = createPerfTest("new Test3", Status.ABNORMAL_TESTING, now()); finishedTest.setPort(0); // need port number for finishing list = testService.getAllAbnormalTesting(); assertThat(list.size(), is(1)); testService.updatePerfTestAfterTestFinish(finishedTest); - createPerfTest("new Test3", Status.START_AGENTS, new Date()); + createPerfTest("new Test3", Status.START_AGENTS, now()); List errorList = testService.getAll(getTestUser(), new Status[]{Status.START_AGENTS}); assertThat(errorList.size(), is(1)); @@ -130,7 +132,7 @@ public void testTestScriptAll() { int maxConcurrent = testService.getMaximumConcurrentTestCount(); assertThat(maxConcurrent, is(10)); - PerfTest testScript = createPerfTest("new TestScript", Status.READY, new Date()); + PerfTest testScript = createPerfTest("new TestScript", Status.READY, now()); testService.addCommentOn(getTestUser(), testScript.getId(), "this is TestScript method", ""); PerfTest testing = testService.markProgressAndStatus(testScript, Status.TESTING, "It is testing from ready"); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/TagServiceTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/TagServiceTest.java index 84ecb9280c..ae5f7e7ac9 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/TagServiceTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/TagServiceTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service; @@ -22,14 +22,14 @@ import org.ngrinder.perftest.repository.TagRepository; import org.springframework.beans.factory.annotation.Autowired; -import java.util.Date; import java.util.List; import java.util.Set; +import static java.time.Instant.now; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.ngrinder.perftest.repository.TagSpecification.hasPerfTest; public class TagServiceTest extends AbstractPerfTestTransactionalTest { @@ -61,8 +61,8 @@ public void beforeTag() { @Test public void testTagService() { Tag entity = new Tag("HELLO"); - entity.setLastModifiedUser(getTestUser()); - entity.setCreatedUser(getTestUser()); + entity.setLastModifiedBy(getTestUser()); + entity.setCreatedBy(getTestUser()); tagRepository.save(entity); Set addTags = tagService.addTags(getTestUser(), new String[]{"HELLO", "WORLD"}); assertThat(addTags.size(), is(2)); @@ -82,7 +82,7 @@ public void testTagService() { @Test public void testTagging() { - PerfTest newPerfTest = newPerfTest("hello", Status.SAVED, new Date()); + PerfTest newPerfTest = newPerfTest("hello", Status.SAVED, now()); newPerfTest.setTagString("HELLO,world"); createPerfTest(newPerfTest); newPerfTest.setTagString("HELLO,WORLD"); @@ -98,7 +98,7 @@ public void testTagging() { public void testGetAllTagStrings() { String[] tags = new String[]{"aaaa", "AAA", "a123", "bbbb", "a12312", "a999", "a777"}; tagService.addTags(getTestUser(), tags); - PerfTest newPerfTest = newPerfTest("hello", Status.SAVED, new Date()); + PerfTest newPerfTest = newPerfTest("hello", Status.SAVED, now()); newPerfTest.setTagString(String.join(",", tags)); perfTestService.save(getTestUser(), newPerfTest); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/monitor/MonitorClientServiceTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/monitor/MonitorClientServiceTest.java index 2e6adfb800..33b1e73361 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/monitor/MonitorClientServiceTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/monitor/MonitorClientServiceTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service.monitor; @@ -26,7 +26,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** diff --git a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/monitor/MonitorInfoStoreTest.java b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/monitor/MonitorInfoStoreTest.java index 2e41bd42a6..b2d153fe84 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/monitor/MonitorInfoStoreTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/perftest/service/monitor/MonitorInfoStoreTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.perftest.service.monitor; @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class MonitorInfoStoreTest extends AbstractAgentReadyTest { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/script/controller/FileEntryApiControllerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/script/controller/FileEntryApiControllerTest.java index 7f3879a40d..b103aa7922 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/script/controller/FileEntryApiControllerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/script/controller/FileEntryApiControllerTest.java @@ -38,7 +38,7 @@ import java.util.Map; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class FileEntryApiControllerTest extends AbstractNGrinderTransactionalTest { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/script/controller/MyHttpServletRequestWrapperTest.java b/ngrinder-controller/src/test/java/org/ngrinder/script/controller/MyHttpServletRequestWrapperTest.java index 366b72bd0a..cc252b705c 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/script/controller/MyHttpServletRequestWrapperTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/script/controller/MyHttpServletRequestWrapperTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,12 +9,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.controller; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/script/controller/SvnDavControllerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/script/controller/SvnDavControllerTest.java index a3caf1f7ed..cc312df918 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/script/controller/SvnDavControllerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/script/controller/SvnDavControllerTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.controller; @@ -34,7 +34,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class SvnDavControllerTest extends AbstractNGrinderTransactionalTest { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/script/handler/GroovyHandlerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/script/handler/GroovyHandlerTest.java index 24672ad0bc..58d5932c33 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/script/handler/GroovyHandlerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/script/handler/GroovyHandlerTest.java @@ -1,8 +1,8 @@ package org.ngrinder.script.handler; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import org.junit.Test; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/script/handler/GroovyMavenProjectScriptHandlerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/script/handler/GroovyMavenProjectScriptHandlerTest.java index f1f3f61de5..b04860d634 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/script/handler/GroovyMavenProjectScriptHandlerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/script/handler/GroovyMavenProjectScriptHandlerTest.java @@ -24,7 +24,7 @@ public void testHandlerMatching() { FileEntry entry = new FileEntry(); entry.setPath("/hello/world/src/main/java/wow/Global.groovy"); - entry.setCreatedUser(user); + entry.setCreatedBy(user); assertThat(handler.canHandle(entry)).isTrue(); entry.setPath("/hello/world/src/main/wow/Global.groovy"); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/script/handler/JythonHandlerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/script/handler/JythonHandlerTest.java index 3240d2b545..ec2b03ceb8 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/script/handler/JythonHandlerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/script/handler/JythonHandlerTest.java @@ -2,7 +2,7 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Test; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/script/handler/ScriptHandlerFactoryTest.java b/ngrinder-controller/src/test/java/org/ngrinder/script/handler/ScriptHandlerFactoryTest.java index 8eaf045ece..6bad47d701 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/script/handler/ScriptHandlerFactoryTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/script/handler/ScriptHandlerFactoryTest.java @@ -15,7 +15,7 @@ public class ScriptHandlerFactoryTest extends AbstractNGrinderTransactionalTest public void testFactoryCreation() { FileEntry fileEntry = new FileEntry(); fileEntry.setPath("/hello/world.groovy"); - fileEntry.setCreatedUser(getTestUser()); + fileEntry.setCreatedBy(getTestUser()); assertThat(factory.getHandler(fileEntry)).isInstanceOf(GroovyScriptHandler.class); fileEntry.setPath("/hello/world.py"); assertThat(factory.getHandler(fileEntry)).isInstanceOf(JythonScriptHandler.class); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/script/repository/FileEntryRepositoryTest.java b/ngrinder-controller/src/test/java/org/ngrinder/script/repository/FileEntryRepositoryTest.java index 4221c6a607..4db0a7e632 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/script/repository/FileEntryRepositoryTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/script/repository/FileEntryRepositoryTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.repository; @@ -33,7 +33,7 @@ import java.util.List; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class FileEntryRepositoryTest extends AbstractNGrinderTransactionalTest { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/script/service/FileEntryServiceTest.java b/ngrinder-controller/src/test/java/org/ngrinder/script/service/FileEntryServiceTest.java index 9753425dab..3dcb7522a0 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/script/service/FileEntryServiceTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/script/service/FileEntryServiceTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,13 +9,13 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.service; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Test; import org.ngrinder.common.exception.NGrinderRuntimeException; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/script/service/ScriptValidationServiceTest.java b/ngrinder-controller/src/test/java/org/ngrinder/script/service/ScriptValidationServiceTest.java index 26c9b4f9db..67ebecd822 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/script/service/ScriptValidationServiceTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/script/service/ScriptValidationServiceTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.script.service; @@ -33,9 +33,11 @@ import java.io.File; import java.io.IOException; +import java.nio.charset.Charset; +import static java.nio.charset.Charset.defaultCharset; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.ngrinder.common.constants.GrinderConstants.GRINDER_SECURITY_LEVEL_NORMAL; public class ScriptValidationServiceTest extends AbstractNGrinderTransactionalTest { @@ -88,7 +90,7 @@ public void testValidation() throws IOException { @Test(timeout = 30000) public void testInfiniteScriptValidation() throws IOException { - String script = IOUtils.toString(new ClassPathResource("/validation/script_loop.py").getInputStream()); + String script = IOUtils.toString(new ClassPathResource("/validation/script_loop.py").getInputStream(), defaultCharset()); FileEntry fileEntry = new FileEntry(); fileEntry.setPath("/script.py"); fileEntry.setContent(script); @@ -97,7 +99,7 @@ public void testInfiniteScriptValidation() throws IOException { @Test public void testNormalScriptValidation() throws IOException { - String script = IOUtils.toString(new ClassPathResource("/validation/script_1time.py").getInputStream()); + String script = IOUtils.toString(new ClassPathResource("/validation/script_1time.py").getInputStream(), defaultCharset()); FileEntry fileEntry = new FileEntry(); fileEntry.setPath("/script2.py"); fileEntry.setContent(script); @@ -108,7 +110,7 @@ public void testNormalScriptValidation() throws IOException { @Test public void testScriptValidationWithSvnScript() throws IOException { - String script = IOUtils.toString(new ClassPathResource("/validation/script_1time.py").getInputStream()); + String script = IOUtils.toString(new ClassPathResource("/validation/script_1time.py").getInputStream(), defaultCharset()); FileEntry fileEntry = new FileEntry(); fileEntry.setPath("/script2.py"); fileEntry.setContent(script); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/security/NGrinderAuthenticationProviderTest.java b/ngrinder-controller/src/test/java/org/ngrinder/security/NGrinderAuthenticationProviderTest.java index 740f204238..96bd2ec6ac 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/security/NGrinderAuthenticationProviderTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/security/NGrinderAuthenticationProviderTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.security; @@ -24,8 +24,8 @@ import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.core.userdetails.UserDetails; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public class NGrinderAuthenticationProviderTest extends AbstractNGrinderTransactionalTest { diff --git a/ngrinder-controller/src/test/java/org/ngrinder/security/NGrinderPluginUserDetailsServiceTest.java b/ngrinder-controller/src/test/java/org/ngrinder/security/NGrinderPluginUserDetailsServiceTest.java index c1e8fee864..efb8f4cc0c 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/security/NGrinderPluginUserDetailsServiceTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/security/NGrinderPluginUserDetailsServiceTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,14 +9,14 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.security; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; diff --git a/ngrinder-controller/src/test/java/org/ngrinder/security/NgrinderUsernamePasswordAuthenticationFilterTest.java b/ngrinder-controller/src/test/java/org/ngrinder/security/NgrinderUsernamePasswordAuthenticationFilterTest.java index 9275b8dc13..209420e965 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/security/NgrinderUsernamePasswordAuthenticationFilterTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/security/NgrinderUsernamePasswordAuthenticationFilterTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.security; @@ -24,8 +24,8 @@ import javax.servlet.http.HttpServletResponse; import java.util.Optional; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -41,8 +41,6 @@ protected org.springframework.security.core.Authentication getAuthentication( when(auth.getPrincipal()).thenReturn(new SecuredUser(getTestUser(), null)); return auth; }; - - }; @Autowired diff --git a/ngrinder-controller/src/test/java/org/ngrinder/user/controller/UserControllerTest.java b/ngrinder-controller/src/test/java/org/ngrinder/user/controller/UserControllerTest.java index 5a5b08c93b..8204b73d5e 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/user/controller/UserControllerTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/user/controller/UserControllerTest.java @@ -13,9 +13,10 @@ */ package org.ngrinder.user.controller; +import static java.time.Instant.now; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.ngrinder.common.constant.WebConstants.JSON_SUCCESS; @@ -29,7 +30,6 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; -import java.util.Date; import java.util.List; import java.util.Map; @@ -119,8 +119,8 @@ private void saveTestUser(String userId, String userName) { newUser.setUserId(userId); newUser.setUserName(userName); newUser.setEmail("junoyoon@gmail.com"); - newUser.setCreatedUser(getTestUser()); - newUser.setCreatedDate(new Date()); + newUser.setCreatedBy(getTestUser()); + newUser.setCreatedAt(now()); newUser.setRole(Role.USER); userApiController.save(getAdminUser(), newUser); } diff --git a/ngrinder-controller/src/test/java/org/ngrinder/user/model/UserTest.java b/ngrinder-controller/src/test/java/org/ngrinder/user/model/UserTest.java index 66498dd549..51d297ab1c 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/user/model/UserTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/user/model/UserTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.user.model; @@ -26,12 +26,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; +import java.time.Instant; import java.util.ArrayList; -import java.util.Date; import java.util.List; +import static java.time.Instant.now; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; public class UserTest extends AbstractNGrinderTransactionalTest { @@ -44,7 +45,7 @@ public class UserTest extends AbstractNGrinderTransactionalTest { @Autowired private TagRepository tagRepository; - + @Before public void before() { List findAll = perfTestRepository.findAll(); @@ -59,17 +60,18 @@ public void before() { userRepository.deleteAll(); userRepository.flush(); } - + @Test public void testShareUser() { List sharedUsers = new ArrayList<>(); List shareUsers = new ArrayList<>(); + Instant now = now(); User user = new User(); user.setUserName("MyName1"); user.setEmail("junoyoon@gmail.com"); - user.setCreatedUser(getUser("user")); - user.setCreatedDate(new Date()); + user.setCreatedBy(getUser("user")); + user.setCreatedAt(now); user.setUserId("hello"); user.setRole(Role.USER); user = userRepository.save(user); @@ -77,26 +79,26 @@ public void testShareUser() { user2.setUserId("hello2"); user2.setUserName("MyName2"); user2.setEmail("junoyoon2@paran.com"); - user2.setCreatedUser(getUser("user")); - user2.setCreatedDate(new Date()); + user2.setCreatedBy(getUser("user")); + user2.setCreatedAt(now); user2.setRole(Role.USER); userRepository.save(user2); - + User user3 = new User(); user3.setUserId("hello3"); user3.setUserName("MyName3"); user3.setEmail("junoyoon3@paran.com"); - user3.setCreatedUser(getUser("user")); - user3.setCreatedDate(new Date()); + user3.setCreatedBy(getUser("user")); + user3.setCreatedAt(now); user3.setRole(Role.USER); userRepository.save(user3); - + User user4 = new User(); user4.setUserId("hello4"); user4.setUserName("MyName4"); user4.setEmail("junoyoon4@paran.com"); - user4.setCreatedUser(getUser("user")); - user4.setCreatedDate(new Date()); + user4.setCreatedBy(getUser("user")); + user4.setCreatedAt(now); user4.setRole(Role.USER); sharedUsers.add(user3); sharedUsers.add(user2); @@ -110,15 +112,16 @@ public void testShareUser() { List sh = sharedUser.getFollowers(); LOG.debug("sharedUser.getFollowers:{}", sh); } - + @Test public void testUser() { + Instant now = now(); User user = new User(); user.setUserName("MyName1"); user.setEmail("junoyoon@gmail.com"); - user.setCreatedUser(getUser("user")); - user.setCreatedDate(new Date()); + user.setCreatedBy(getUser("user")); + user.setCreatedAt(now); user.setUserId("hello"); user.setRole(Role.USER); user = userRepository.save(user); @@ -126,8 +129,8 @@ public void testUser() { user2.setUserId("hello2"); user2.setUserName("MyName2"); user2.setEmail("junoyoon@paran.com"); - user2.setCreatedUser(getUser("user")); - user2.setCreatedDate(new Date()); + user2.setCreatedBy(getUser("user")); + user2.setCreatedAt(now); user2.setRole(Role.USER); userRepository.save(user2); diff --git a/ngrinder-controller/src/test/java/org/ngrinder/user/service/UserServiceTest.java b/ngrinder-controller/src/test/java/org/ngrinder/user/service/UserServiceTest.java index 4a20ff37d1..4231e01b40 100644 --- a/ngrinder-controller/src/test/java/org/ngrinder/user/service/UserServiceTest.java +++ b/ngrinder-controller/src/test/java/org/ngrinder/user/service/UserServiceTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.user.service; @@ -27,8 +27,8 @@ import java.io.File; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; public class UserServiceTest extends AbstractNGrinderTransactionalTest { diff --git a/ngrinder-core/build.gradle b/ngrinder-core/build.gradle index 68b7cc5bda..24b0bd8044 100644 --- a/ngrinder-core/build.gradle +++ b/ngrinder-core/build.gradle @@ -18,8 +18,8 @@ dependencies { compile (group: "ch.qos.logback", name: "logback-classic", version:"1.0.0") compile (group: "org.slf4j", name: "slf4j-api", version: slf4j_version) compile (group: "org.slf4j", name: "jcl-over-slf4j", version: slf4j_version) - compile (group: 'org.hibernate', name: 'hibernate-core', version: hibernate_version) - compile (group: 'org.jboss.spec.javax.transaction', name: 'jboss-transaction-api_1.2_spec', version: '1.0.1.Final') + compile (group: "org.hibernate", name: "hibernate-core", version: hibernate_version) + compile (group: "org.jboss.spec.javax.transaction", name: "jboss-transaction-api_1.2_spec", version: "1.0.1.Final") compileOnly (group: "org.projectlombok", name: "lombok", version: "1.18.8") annotationProcessor (group: "org.projectlombok", name: "lombok", version: "1.18.8") diff --git a/ngrinder-core/src/main/java/net/grinder/AgentController.java b/ngrinder-core/src/main/java/net/grinder/AgentController.java index 6aa9610247..97d40f6ec0 100644 --- a/ngrinder-core/src/main/java/net/grinder/AgentController.java +++ b/ngrinder-core/src/main/java/net/grinder/AgentController.java @@ -13,8 +13,6 @@ */ package net.grinder; -import net.grinder.AgentDaemon.AgentShutDownListener; -import net.grinder.common.GrinderException; import net.grinder.common.GrinderProperties; import net.grinder.communication.*; import net.grinder.engine.agent.Agent; @@ -41,9 +39,9 @@ import org.slf4j.LoggerFactory; import java.io.File; -import java.io.FilenameFilter; import java.net.ServerSocket; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Timer; import java.util.TimerTask; @@ -61,34 +59,26 @@ public class AgentController implements Agent, AgentConstants { private static final Logger LOGGER = LoggerFactory.getLogger("agent controller"); + private static final SystemDataModel emptySystemDataModel = new SystemDataModel(); - private final AgentConfig agentConfig; - - private Timer m_timer; @SuppressWarnings("FieldCanBeLocal") private final Condition m_eventSynchronization = new Condition(); + private final AgentConfig agentConfig; private final AgentControllerIdentityImplementation m_agentIdentity; private final AgentControllerServerListener m_agentControllerServerListener; - private FanOutStreamSender m_fanOutStreamSender; - private final AgentControllerConnectorFactory m_connectorFactory = new AgentControllerConnectorFactory( - ConnectionType.AGENT); + private final AgentControllerConnectorFactory m_connectorFactory = new AgentControllerConnectorFactory(ConnectionType.AGENT); private final Condition m_eventSyncCondition; - private volatile AgentControllerState m_state = AgentControllerState.STARTED; + private final SystemDataCollector agentSystemDataCollector; + private final String version; - private SystemDataCollector agentSystemDataCollector = new SystemDataCollector(); + private volatile AgentControllerState m_state = AgentControllerState.STARTED; private int m_connectionPort = 0; - - private static SystemDataModel emptySystemDataModel = new SystemDataModel(); - - private AgentUpdateHandler agentUpdateHandler; - private int retryCount = 0; - - private String version; - + private Timer m_timer; + private FanOutStreamSender m_fanOutStreamSender; + private AgentUpdateHandler agentUpdateHandler; private ConnectionAgentCommunicationProxy communicationProxy = ConnectionAgentCommunicationProxy.EMPTY; - private ServerSocket connectionAgentSocket; /** @@ -96,7 +86,7 @@ public class AgentController implements Agent, AgentConstants { * * @param eventSyncCondition event sync condition to wait until agent start to run. */ - public AgentController(Condition eventSyncCondition, AgentConfig agentConfig) throws GrinderException { + public AgentController(Condition eventSyncCondition, AgentConfig agentConfig) { this.m_eventSyncCondition = eventSyncCondition; this.agentConfig = agentConfig; @@ -112,11 +102,9 @@ public AgentController(Condition eventSyncCondition, AgentConfig agentConfig) th /** * Run the agent controller. - * - * @throws GrinderException occurs when the test execution is failed. */ @SuppressWarnings("ConstantConditions") - public void run() throws GrinderException { + public void run() { synchronized (m_eventSyncCondition) { m_eventSyncCondition.notifyAll(); } @@ -187,12 +175,10 @@ public void run() throws GrinderException { if (agentConfig.isConnectionMode()) { final int localConnectionPort = NetworkUtils.getFreePort(); grinderProperties.setInt(GrinderProperties.CONSOLE_PORT, localConnectionPort); - communicationProxy = new ConnectionAgentCommunicationProxy(localConnectionPort, agentConfig.getConnectionAgentPort(), LOGGER, new ConnectionAgentCommunicationProxy.CommunicationMessageSender() { - @Override - public void send() { - conCom.sendMessage(new ConnectionAgentCommunicationMessage(m_connectionPort, m_agentIdentity.getIp(), agentConfig.getConnectionAgentPort())); - } - }); + communicationProxy = new ConnectionAgentCommunicationProxy(localConnectionPort, + agentConfig.getConnectionAgentPort(), + LOGGER, + () -> conCom.sendMessage(new ConnectionAgentCommunicationMessage(m_connectionPort, m_agentIdentity.getIp(), agentConfig.getConnectionAgentPort()))); releaseConnectionAgentSocket(); communicationProxy.start(); } @@ -200,17 +186,14 @@ public void send() { agentDaemon.run(grinderProperties); agentDaemon.resetListeners(); - agentDaemon.addListener(new AgentShutDownListener() { - @Override - public void shutdownAgent() { - LOGGER.info("Send log for {}", testId); - sendLog(conCom, testId); - m_state = AgentControllerState.READY; - m_connectionPort = 0; - communicationProxy.shutdown(); - communicationProxy = ConnectionAgentCommunicationProxy.EMPTY; - occupyConnectionAgentSocket(); - } + agentDaemon.addListener(() -> { + LOGGER.info("Send log for {}", testId); + sendLog(conCom, testId); + m_state = AgentControllerState.READY; + m_connectionPort = 0; + communicationProxy.shutdown(); + communicationProxy = ConnectionAgentCommunicationProxy.EMPTY; + occupyConnectionAgentSocket(); }); } // Ignore any pending start messages. @@ -301,12 +284,7 @@ private void sendLog(ConsoleCommunication consoleCommunication, String testId) { if (!logFolder.exists()) { return; } - File[] logFiles = logFolder.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return (name.endsWith(".log")); - } - }); + File[] logFiles = logFolder.listFiles((dir, name) -> (name.endsWith(".log"))); if (logFiles == null || ArrayUtils.isEmpty(logFiles)) { LOGGER.error("No log exists under {}", logFolder.getAbsolutePath()); @@ -318,7 +296,7 @@ public boolean accept(File dir, String name) { logFiles = new File[]{logFiles[0]}; } final byte[] compressedLog = LogCompressUtils.compress(logFiles, - Charset.defaultCharset(), Charset.forName("UTF-8") + Charset.defaultCharset(), StandardCharsets.UTF_8 ); consoleCommunication.sendMessage(new LogReportGrinderMessage(testId, compressedLog, new AgentAddress(m_agentIdentity))); // Delete logs to clean up @@ -342,7 +320,7 @@ private void sendCurrentState(ConsoleCommunication consoleCommunication) { if (consoleCommunication != null) { try { consoleCommunication.sendCurrentState(); - } catch (CommunicationException e) { + } catch (RuntimeException e) { LOGGER.error("Error while sending current state : {}.", e.getMessage()); LOGGER.debug("The error detail is ", e); } @@ -422,7 +400,7 @@ public ConsoleCommunication(Connector connector) throws CommunicationException { public void run() { try { sendCurrentState(); - } catch (CommunicationException e) { + } catch (RuntimeException e) { cancel(); LOGGER.error("Error while sending current state:" + e.getMessage()); LOGGER.debug("The error detail is", e); @@ -443,7 +421,7 @@ public void sendMessage(Message message) { } } - public void sendCurrentState() throws CommunicationException { + public void sendCurrentState() { sendMessage(new AgentControllerProcessReportMessage(m_state, getSystemDataModel(), m_connectionPort, version)); } diff --git a/ngrinder-core/src/main/java/net/grinder/AgentControllerDaemon.java b/ngrinder-core/src/main/java/net/grinder/AgentControllerDaemon.java index 0b984e17ff..b175492e41 100644 --- a/ngrinder-core/src/main/java/net/grinder/AgentControllerDaemon.java +++ b/ngrinder-core/src/main/java/net/grinder/AgentControllerDaemon.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder; @@ -17,7 +17,6 @@ import net.grinder.engine.agent.Agent; import net.grinder.util.ListenerHelper; import net.grinder.util.ListenerSupport; -import net.grinder.util.ListenerSupport.Informer; import net.grinder.util.thread.Condition; import org.ngrinder.common.util.ThreadUtils; import org.ngrinder.infra.AgentConfig; @@ -33,17 +32,17 @@ */ public class AgentControllerDaemon implements Agent { + public static final Logger LOGGER = LoggerFactory.getLogger("agent controller daemon"); private static final int LOG_FREQUENCY = 5; - private final AgentController agentController; - private Thread thread; - private final ListenerSupport m_listeners = ListenerHelper.create(); - private boolean forceShutdown = false; + // event synchronization for @SuppressWarnings("FieldCanBeLocal") - private Condition m_eventSyncCondition = new Condition(); - - public static final Logger LOGGER = LoggerFactory.getLogger("agent controller daemon"); + private final Condition m_eventSyncCondition = new Condition(); + private final AgentController agentController; + private final ListenerSupport m_listeners = ListenerHelper.create(); + private Thread thread; + private boolean forceShutdown = false; /** * Constructor. @@ -53,7 +52,7 @@ public class AgentControllerDaemon implements Agent { public AgentControllerDaemon(AgentConfig agentConfig) { try { agentController = new AgentController(m_eventSyncCondition, agentConfig); - } catch (GrinderException e) { + } catch (RuntimeException e) { throw processException("Exception occurred while initiating the agent controller daemon", e); } } @@ -62,30 +61,24 @@ public AgentControllerDaemon(AgentConfig agentConfig) { private long count = 0; public void run() { - thread = new Thread(new Runnable() { - public void run() { - do { - try { - if (count++ % LOG_FREQUENCY == 0) { - LOGGER.info("The agent controller daemon is started."); - } - getAgentController().run(); - getListeners().apply(new Informer() { - public void inform(AgentControllerShutDownListener listener) { - listener.shutdownAgentController(); - } - }); - } catch (Exception e) { - LOGGER.info("Agent controller daemon is crashed. {}", e.getMessage()); - LOGGER.debug("The error detail is ", e); - } - if (isForceShutdown()) { - setForceShutdown(false); - break; + thread = new Thread(() -> { + do { + try { + if (count++ % LOG_FREQUENCY == 0) { + LOGGER.info("The agent controller daemon is started."); } - ThreadUtils.sleep(GrinderConstants.AGENT_CONTROLLER_RETRY_INTERVAL); - } while (true); - } + getAgentController().run(); + getListeners().apply(AgentControllerShutDownListener::shutdownAgentController); + } catch (Exception e) { + LOGGER.info("Agent controller daemon is crashed. {}", e.getMessage()); + LOGGER.debug("The error detail is ", e); + } + if (isForceShutdown()) { + setForceShutdown(false); + break; + } + ThreadUtils.sleep(GrinderConstants.AGENT_CONTROLLER_RETRY_INTERVAL); + } while (true); }, "Agent Controller Thread"); thread.start(); } @@ -99,7 +92,7 @@ public interface AgentControllerShutDownListener { /** * Method which will be called when agent controller. */ - public void shutdownAgentController(); + void shutdownAgentController(); } public ListenerSupport getListeners() { diff --git a/ngrinder-core/src/main/java/net/grinder/AgentControllerServer.java b/ngrinder-core/src/main/java/net/grinder/AgentControllerServer.java index 0db4d0f182..1b9e6b1b0d 100644 --- a/ngrinder-core/src/main/java/net/grinder/AgentControllerServer.java +++ b/ngrinder-core/src/main/java/net/grinder/AgentControllerServer.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder; @@ -35,19 +35,21 @@ /** * Agent Controller which controls agent behavior. This class is subject to synchronized. So if you * want to daemon, please refer {@link AgentControllerServerDaemon} - * + * * @author JunHo Yoon * @since 3.0 */ public class AgentControllerServer { - private DefaultPicoContainer m_container; - private Timer m_timer; - private boolean m_shutdown = false; + + private final DefaultPicoContainer m_container; + private final Timer m_timer; private final Condition m_eventSyncCondition; + private boolean m_shutdown = false; + /** * Constructor. - * + * * @param resources message resource * @param logger logger * @param properties {@link ConsoleProperties} @@ -97,7 +99,7 @@ public void run() { /** * Shut down the console. - * + * */ public void shutdown() { m_shutdown = true; @@ -116,7 +118,7 @@ public void shutdown() { /** * Get internal component. - * + * * @param componentType component type class * @param component type * @return component diff --git a/ngrinder-core/src/main/java/net/grinder/AgentControllerServerDaemon.java b/ngrinder-core/src/main/java/net/grinder/AgentControllerServerDaemon.java index 7b0b0c31c6..956a1f6f9e 100644 --- a/ngrinder-core/src/main/java/net/grinder/AgentControllerServerDaemon.java +++ b/ngrinder-core/src/main/java/net/grinder/AgentControllerServerDaemon.java @@ -46,17 +46,18 @@ * @author JunHo Yoon */ public class AgentControllerServerDaemon { - private final ConsoleProperties consoleProperties; - private Thread thread; - private AgentControllerServer agentControllerServer; - public static final Resources RESOURCES = new ResourcesImplementation( - "net.grinder.console.common.resources.Console"); - private final Condition m_eventSyncCondition = new Condition(); + public static final Resources RESOURCES = new ResourcesImplementation("net.grinder.console.common.resources.Console"); public static final Logger LOGGER = LoggerFactory.getLogger(RESOURCES.getString("shortTitle")); + private static final long AGENT_CONTROLLER_SERVER_SHUTDOWN_WAITING_TIMEOUT = 10000; private static final long AGENT_CONTROLLER_SERVER_EVENT_EXPIRATION_TIMEOUT = 10000; + private final ConsoleProperties consoleProperties; + private final AgentControllerServer agentControllerServer; + private final Condition m_eventSyncCondition = new Condition(); + + private Thread thread; /** * Agent controller daemon constructor with default * {@link ConsoleProperties}. diff --git a/ngrinder-core/src/main/java/net/grinder/AgentDaemon.java b/ngrinder-core/src/main/java/net/grinder/AgentDaemon.java index 66c47edfc0..74c148a2c9 100644 --- a/ngrinder-core/src/main/java/net/grinder/AgentDaemon.java +++ b/ngrinder-core/src/main/java/net/grinder/AgentDaemon.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder; @@ -19,7 +19,6 @@ import net.grinder.engine.agent.Agent; import net.grinder.engine.agent.AgentImplementationEx; import net.grinder.util.ListenerSupport; -import net.grinder.util.ListenerSupport.Informer; import org.apache.commons.lang.StringUtils; import org.ngrinder.common.util.ThreadUtils; import org.ngrinder.infra.AgentConfig; @@ -36,9 +35,9 @@ */ public class AgentDaemon implements Agent { private volatile AgentImplementationEx agent; - private Thread thread = new Thread(); + private Thread thread; private GrinderProperties properties; - private final ListenerSupport m_listeners = new ListenerSupport(); + private final ListenerSupport m_listeners = new ListenerSupport<>(); private boolean forceShutdown = false; public static final Logger LOGGER = LoggerFactory.getLogger("agent daemon"); private final AgentConfig m_agentConfig; @@ -133,11 +132,9 @@ public void run() { } catch (Exception e) { LOGGER.error("While running an agent thread, an error occurred", e); } - getListeners().apply(new Informer() { - public void inform(AgentShutDownListener listener) { - listener.shutdownAgent(); - } - }); + + getListeners().apply(AgentShutDownListener::shutdownAgent); + if (isForceShutdown()) { setForceShutdown(false); } @@ -153,7 +150,7 @@ public interface AgentShutDownListener { /** * AgentShutdown listening method. */ - public void shutdownAgent(); + void shutdownAgent(); } public ListenerSupport getListeners() { @@ -164,17 +161,12 @@ public ListenerSupport getListeners() { * Reset all shutdown listener. */ public void resetListeners() { - final ListenerSupport backup = new ListenerSupport(); - getListeners().apply(new Informer() { - public void inform(AgentShutDownListener listener) { - backup.add(listener); - } - }); + final ListenerSupport backup = new ListenerSupport<>(); - backup.apply(new Informer() { - public void inform(AgentShutDownListener listener) { - getListeners().remove(listener); - } + getListeners().apply(backup::add); + + backup.apply(listener -> { + getListeners().remove(listener); }); } @@ -207,6 +199,7 @@ private boolean isForceShutdown() { return forceShutdown; } + @SuppressWarnings("SameParameterValue") private void setForceShutdown(boolean force) { this.forceShutdown = force; } diff --git a/ngrinder-core/src/main/java/net/grinder/AgentUpdateHandler.java b/ngrinder-core/src/main/java/net/grinder/AgentUpdateHandler.java index 8e063520e5..3ae4c7613e 100644 --- a/ngrinder-core/src/main/java/net/grinder/AgentUpdateHandler.java +++ b/ngrinder-core/src/main/java/net/grinder/AgentUpdateHandler.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder; @@ -42,10 +42,11 @@ public class AgentUpdateHandler implements Closeable { private static final Logger LOGGER = LoggerFactory.getLogger(AgentUpdateHandler.class); private final AgentConfig agentConfig; - private File download; + private final File download; + private final FileOutputStream agentOutputStream; + @SuppressWarnings("FieldCanBeLocal") private int offset = 0; - private FileOutputStream agentOutputStream; /** * Agent Update handler. diff --git a/ngrinder-core/src/main/java/net/grinder/SingleConsole.java b/ngrinder-core/src/main/java/net/grinder/SingleConsole.java index d9d4401293..77f3b702db 100644 --- a/ngrinder-core/src/main/java/net/grinder/SingleConsole.java +++ b/ngrinder-core/src/main/java/net/grinder/SingleConsole.java @@ -41,7 +41,6 @@ import net.grinder.messages.console.AgentAddress; import net.grinder.statistics.*; import net.grinder.util.*; -import net.grinder.util.ListenerSupport.Informer; import net.grinder.util.thread.Condition; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.IOUtils; @@ -57,8 +56,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -70,6 +67,7 @@ import static java.util.Arrays.stream; +import static java.util.Collections.synchronizedMap; import static org.ngrinder.common.util.CollectionUtils.*; import static org.ngrinder.common.util.ExceptionUtils.processException; import static org.ngrinder.common.util.Preconditions.checkNotNull; @@ -97,7 +95,7 @@ public class SingleConsole extends AbstractSingleConsole implements Listener, Sa private ProcessReports[] processReports; // It contains cached distribution files digest from each agents. - private CopyOnWriteArrayList> agentCachedDistFilesDigestList = new CopyOnWriteArrayList<>(); + private final CopyOnWriteArrayList> agentCachedDistFilesDigestList = new CopyOnWriteArrayList<>(); private boolean cancel = false; // for displaying tps graph in test running page @@ -121,7 +119,7 @@ public class SingleConsole extends AbstractSingleConsole implements Listener, Sa private boolean headerAdded = false; private GrinderProperties properties; - private Map fileWriterMap = newHashMap(); + private final Map fileWriterMap = newHashMap(); /** * the count of current sampling. */ @@ -143,11 +141,9 @@ public class SingleConsole extends AbstractSingleConsole implements Listener, Sa private int currentNotFinishedProcessCount = 0; private static final int TOO_LOW_TPS_TIME = 60000; - private static final int TOO_MANY_ERROR_TIME = 10000; - private Map intervalStatisticMapPerTest = Collections - .synchronizedMap(new LinkedHashMap()); - private Map accumulatedStatisticMapPerTest = Collections - .synchronizedMap(new LinkedHashMap()); + + private final Map intervalStatisticMapPerTest = synchronizedMap(new LinkedHashMap<>()); + private final Map accumulatedStatisticMapPerTest = synchronizedMap(new LinkedHashMap<>()); /** * cvs file Separator value. */ @@ -210,11 +206,7 @@ public void start() { return; // the console is not a valid console.(NullSingleConsole) } synchronized (eventSyncCondition) { - consoleFoundationThread = new Thread(new Runnable() { - public void run() { - getConsoleFoundation().run(); - } - }, "console on port " + getConsolePort()); + consoleFoundationThread = new Thread(() -> getConsoleFoundation().run(), "console on port " + getConsolePort()); consoleFoundationThread.setDaemon(true); consoleFoundationThread.start(); eventSyncCondition.waitNoInterrruptException(5000); @@ -271,11 +263,7 @@ public List getAllAttachedAgents() { getConsoleFoundation().getComponent(ProcessControl.class), "m_agentNumberMap"), "m_agentNumberMap on ProcessControlImplementation is not available in this grinder version"); - agentIdentity.forEach(new AllocateLowestNumber.IteratorCallback() { - public void objectAndNumber(Object object, int number) { - agentIdentities.add((AgentIdentity) object); - } - }); + agentIdentity.forEach((object, number) -> agentIdentities.add((AgentIdentity) object)); return agentIdentities; } @@ -379,7 +367,6 @@ public void sendDistFilesDigestToAgents(Set distFilesDigest) { .sendToAddressedAgents( new AgentAddress(processReport.getAgentProcessReport().getAgentIdentity()), new RefreshCacheMessage(distFilesDigest)))); - LOGGER.info("Send digest of distribution files to agent for refresh agent's cache directory."); } /** @@ -416,22 +403,17 @@ public void distributeFiles(ListenerSupport listener, final FileDistribution fileDistribution = getConsoleComponent(FileDistribution.class); final AgentCacheState agentCacheState = fileDistribution.getAgentCacheState(); final Condition cacheStateCondition = new Condition(); - agentCacheState.addListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent ignored) { - synchronized (cacheStateCondition) { - cacheStateCondition.notifyAll(); - } + agentCacheState.addListener(ignored -> { + synchronized (cacheStateCondition) { + cacheStateCondition.notifyAll(); } }); final MutableBoolean safeDist = new MutableBoolean(safe); ConsoleProperties consoleComponent = getConsoleComponent(ConsoleProperties.class); final File file = consoleComponent.getDistributionDirectory().getFile(); if (listener != null) { - listener.apply(new Informer() { - @Override - public void inform(FileDistributionListener listener) { - safeDist.setValue(listener.start(file, safe)); - } + listener.apply(fileDistributionListener -> { + safeDist.setValue(fileDistributionListener.start(file, safe)); }); } final FileDistributionHandler distributionHandler = fileDistribution.getHandler(); @@ -445,11 +427,8 @@ public void inform(FileDistributionListener listener) { break; } if (listener != null) { - listener.apply(new Informer() { - @Override - public void inform(FileDistributionListener listener) { - listener.distributed(result.getFileName()); - } + listener.apply(fileDistributionListener -> { + fileDistributionListener.distributed(result.getFileName()); }); } @@ -542,10 +521,8 @@ public boolean isAllTestFinished() { // However sometimes runningThread is over 0 but all process is // marked as // FINISHED.. It can be treated as finished status as well. - } else if (this.currentNotFinishedProcessCount == 0) { - return true; } - return false; + return this.currentNotFinishedProcessCount == 0; } } @@ -653,11 +630,8 @@ public void update(final StatisticsSet intervalStatistics, final StatisticsSet c // Adjust sampling delay.. run write data multiple times... when it // takes longer than 1 sec. - samplingLifeCycleListener.apply(new Informer() { - @Override - public void inform(SamplingLifeCycleListener listener) { - listener.onSampling(getReportPath(), intervalStatistics, cumulativeStatistics); - } + samplingLifeCycleListener.apply(listener -> { + listener.onSampling(getReportPath(), intervalStatistics, cumulativeStatistics); }); for (long index = 0, repeatCounts = gap + 1; index < repeatCounts; index++) { final boolean lastCall = (samplingCount == 1 && index == 0) || (samplingCount != 1 && index == gap); @@ -665,11 +639,8 @@ public void inform(SamplingLifeCycleListener listener) { if (interval >= (MIN_SAMPLING_INTERVAL_TO_ACTIVATE_TPS_PER_TEST)) { writeIntervalSummaryDataPerTest(intervalStatisticMapPerTest, lastCall); } - samplingLifeCycleFollowupListener.apply(new Informer() { - @Override - public void inform(SamplingLifeCycleFollowUpListener listener) { - listener.onSampling(getReportPath(), intervalStatistics, cumulativeStatistics, lastCall); - } + samplingLifeCycleFollowupListener.apply(listener -> { + listener.onSampling(getReportPath(), intervalStatistics, cumulativeStatistics, lastCall); }); } @@ -803,10 +774,8 @@ private void checkTooLowTps(double tps) { } else if (new Date().getTime() - momentWhenTpsBeganToHaveVerySmall >= TOO_LOW_TPS_TIME) { LOGGER.warn("Stop the test because its tps is less than 0.001 for more than {} minitue.", TOO_LOW_TPS_TIME / 60000); - getListeners().apply(new Informer() { - public void inform(ConsoleShutdownListener listener) { - listener.readyToStop(StopReason.TOO_LOW_TPS); - } + getListeners().apply(listener -> { + listener.readyToStop(StopReason.TOO_LOW_TPS); }); momentWhenTpsBeganToHaveVerySmall = 0; @@ -839,8 +808,8 @@ public static boolean isInterestingStatistics(String key) { protected void updateStatistics(StatisticsSet intervalStatistics, StatisticsSet accumulatedStatistics) { Map result = newHashMap(); result.put("testTime", getCurrentRunningTime() / 1000); - List> cumulativeStatistics = new ArrayList>(); - List> lastSampleStatistics = new ArrayList>(); + List> cumulativeStatistics = new ArrayList<>(); + List> lastSampleStatistics = new ArrayList<>(); for (Test test : accumulatedStatisticMapPerTest.keySet()) { Map accumulatedStatisticMap = newHashMap(); Map intervalStatisticsMap = newHashMap(); @@ -893,6 +862,7 @@ protected void updateStatistics(StatisticsSet intervalStatistics, StatisticsSet * * @see net.grinder.ISingleConsole2#getCurrentExecutionCount() */ + @SuppressWarnings("WrapperTypeMayBePrimitive") @Override public long getCurrentExecutionCount() { Map totalStatistics = (Map) getStatisticsData().get("totalStatistics"); @@ -1034,10 +1004,8 @@ public void update(ProcessReports[] processReports) { private void checkExecutionErrors(ProcessReports[] processReports) { if (samplingCount == 0 && ArrayUtils.isNotEmpty(this.processReports) && ArrayUtils.isEmpty(processReports)) { - getListeners().apply(new Informer() { - public void inform(ConsoleShutdownListener listener) { - listener.readyToStop(StopReason.SCRIPT_ERROR); - } + getListeners().apply(listener -> { + listener.readyToStop(StopReason.SCRIPT_ERROR); }); } } @@ -1120,7 +1088,7 @@ public Map getStatisticsData() { } protected Map getNullStatisticsData() { - Map result = new HashMap(1); + Map result = new HashMap<>(1); result.put("test_time", getCurrentRunningTime() / 1000); return result; } @@ -1176,12 +1144,9 @@ public void resetTests() { @Override public void newTests(Set newTests, ModelTestIndex modelTestIndex) { for (final Test each : newTests) { - SingleConsole.this.sampleModel.addSampleListener(each, new SampleListener() { - @Override - public void update(StatisticsSet intervalStatistics, StatisticsSet cumulativeStatistics) { - intervalStatisticMapPerTest.put(each, intervalStatistics.snapshot()); - accumulatedStatisticMapPerTest.put(each, cumulativeStatistics.snapshot()); - } + SingleConsole.this.sampleModel.addSampleListener(each, (intervalStatistics, cumulativeStatistics) -> { + intervalStatisticMapPerTest.put(each, intervalStatistics.snapshot()); + accumulatedStatisticMapPerTest.put(each, cumulativeStatistics.snapshot()); }); } } @@ -1192,7 +1157,6 @@ public void newSample() { }); informTestSamplingStart(); this.sampleModel.start(); - LOGGER.info("Sampling is started"); } /** @@ -1204,52 +1168,39 @@ public void unregisterSampling() { this.sampleModel.reset(); this.sampleModel.stop(); } - LOGGER.info("Sampling is stopped"); informTestSamplingEnd(); } private void informTestSamplingStart() { - samplingLifeCycleListener.apply(new Informer() { - @Override - public void inform(SamplingLifeCycleListener listener) { - try { - listener.onSamplingStarted(); - } catch (Exception e) { - LOGGER.error("Error occurred while running sampling start listener", e); - } + samplingLifeCycleListener.apply(listener -> { + try { + listener.onSamplingStarted(); + } catch (Exception e) { + LOGGER.error("Error occurred while running sampling start listener", e); } }); - samplingLifeCycleFollowupListener.apply(new Informer() { - @Override - public void inform(SamplingLifeCycleFollowUpListener listener) { - try { - listener.onSamplingStarted(); - } catch (Exception e) { - LOGGER.error("Error occurred while running sampling start listener", e); - } + samplingLifeCycleFollowupListener.apply(listener -> { + try { + listener.onSamplingStarted(); + } catch (Exception e) { + LOGGER.error("Error occurred while running sampling start listener", e); } }); } private void informTestSamplingEnd() { - samplingLifeCycleListener.apply(new Informer() { - @Override - public void inform(SamplingLifeCycleListener listener) { - try { - listener.onSamplingEnded(); - } catch (Exception e) { - LOGGER.error("Error occurred while running sampling end listener", e); - } + samplingLifeCycleListener.apply(listener -> { + try { + listener.onSamplingEnded(); + } catch (Exception e) { + LOGGER.error("Error occurred while running sampling end listener", e); } }); - samplingLifeCycleFollowupListener.apply(new Informer() { - @Override - public void inform(SamplingLifeCycleFollowUpListener listener) { - try { - listener.onSamplingEnded(); - } catch (Exception e) { - LOGGER.error("Error occurred while running sampling end listener", e); - } + samplingLifeCycleFollowupListener.apply(listener -> { + try { + listener.onSamplingEnded(); + } catch (Exception e) { + LOGGER.error("Error occurred while running sampling end listener", e); } }); } diff --git a/ngrinder-core/src/main/java/net/grinder/StopReason.java b/ngrinder-core/src/main/java/net/grinder/StopReason.java index 87a43f3381..a2e048b010 100644 --- a/ngrinder-core/src/main/java/net/grinder/StopReason.java +++ b/ngrinder-core/src/main/java/net/grinder/StopReason.java @@ -26,7 +26,7 @@ public enum StopReason { TOO_MANY_ERRORS("Too many errors"), /** Error while test preparation. */ ERROR_WHILE_PREPARE("Test preparation error"), - /** Error while first execution. */ + /** Error while first execution or no recording. */ SCRIPT_ERROR("Script error"), /** Error by too much overall traffic on the given region. */ TOO_MUCH_TRAFFIC_ON_REGION("Too much traffic error"), diff --git a/ngrinder-core/src/main/java/net/grinder/communication/AcceptorResolver.java b/ngrinder-core/src/main/java/net/grinder/communication/AcceptorResolver.java index 782b44fdfb..af788a376a 100644 --- a/ngrinder-core/src/main/java/net/grinder/communication/AcceptorResolver.java +++ b/ngrinder-core/src/main/java/net/grinder/communication/AcceptorResolver.java @@ -21,7 +21,7 @@ import java.util.concurrent.ConcurrentHashMap; public class AcceptorResolver { - public final Map sockets = new ConcurrentHashMap(); + public final Map sockets = new ConcurrentHashMap<>(); public void addSocketListener(Acceptor acceptor) throws Acceptor.ShutdownException { final ResourcePool socketSet = acceptor.getSocketSet(ConnectionType.AGENT); diff --git a/ngrinder-core/src/main/java/net/grinder/console/ConsoleFoundationEx.java b/ngrinder-core/src/main/java/net/grinder/console/ConsoleFoundationEx.java index 2f88e9641d..318215fb7f 100644 --- a/ngrinder-core/src/main/java/net/grinder/console/ConsoleFoundationEx.java +++ b/ngrinder-core/src/main/java/net/grinder/console/ConsoleFoundationEx.java @@ -20,7 +20,6 @@ // OF THE POSSIBILITY OF SUCH DAMAGE. package net.grinder.console; -import net.grinder.common.GrinderException; import net.grinder.communication.MessageDispatchRegistry; import net.grinder.communication.MessageDispatchRegistry.AbstractHandler; import net.grinder.console.common.ErrorQueue; @@ -74,11 +73,10 @@ public class ConsoleFoundationEx { * @param logger Logger. * @param properties The properties. * @param eventSyncCondition event synchronization condition. - * @exception GrinderException occurs If an error occurs. */ public ConsoleFoundationEx(Resources resources, Logger logger, ConsoleProperties properties, ConsoleCommunicationSetting consoleCommunicationSetting, - Condition eventSyncCondition) throws GrinderException { + Condition eventSyncCondition) { m_eventSyncCondition = eventSyncCondition; m_container = new DefaultPicoContainer(new Caching()); m_container.addComponent(logger); @@ -96,7 +94,6 @@ public ConsoleFoundationEx(Resources resources, Logger logger, ConsoleProperties m_timer = new Timer(true); m_container.addComponent(m_timer); - //noinspection RedundantArrayCreation m_container.addComponent(FileDistributionImplementation.class, FileDistributionImplementation.class, new ComponentParameter(DistributionControlImplementation.class), new ComponentParameter(ProcessControlImplementation.class), @@ -120,7 +117,7 @@ public ConsoleFoundationEx(Resources resources, Logger logger, ConsoleProperties /** * Get the component of the given type. - * + * * @param component type * @param componentType component type class * @return component @@ -131,7 +128,7 @@ public T getComponent(Class componentType) { /** * Shut down the console. - * + * */ public void shutdown() { m_shutdown = true; diff --git a/ngrinder-core/src/main/java/net/grinder/console/communication/AgentDownloadRequestListener.java b/ngrinder-core/src/main/java/net/grinder/console/communication/AgentDownloadRequestListener.java index 94cf0d0376..1ebd6173b8 100644 --- a/ngrinder-core/src/main/java/net/grinder/console/communication/AgentDownloadRequestListener.java +++ b/ngrinder-core/src/main/java/net/grinder/console/communication/AgentDownloadRequestListener.java @@ -21,5 +21,5 @@ * @since 3.3 */ public interface AgentDownloadRequestListener { - public AgentUpdateGrinderMessage onAgentDownloadRequested(String version, int offset); + AgentUpdateGrinderMessage onAgentDownloadRequested(String version, int offset); } diff --git a/ngrinder-core/src/main/java/net/grinder/console/communication/AgentProcessControl.java b/ngrinder-core/src/main/java/net/grinder/console/communication/AgentProcessControl.java index 6eb53a4f3e..d8c78f44d9 100644 --- a/ngrinder-core/src/main/java/net/grinder/console/communication/AgentProcessControl.java +++ b/ngrinder-core/src/main/java/net/grinder/console/communication/AgentProcessControl.java @@ -45,7 +45,7 @@ public interface AgentProcessControl { * @param properties Properties that override the agent's local properties. * */ - public void startAgent(Set agents, GrinderProperties properties); + void startAgent(Set agents, GrinderProperties properties); /** * Stop agent. @@ -53,14 +53,14 @@ public interface AgentProcessControl { * @param agentIdentity agent to be stopped * */ - public void stopAgent(AgentIdentity agentIdentity); + void stopAgent(AgentIdentity agentIdentity); /** * Get the number of agents. * * @return available agent's count */ - public int getNumberOfLiveAgents(); + int getNumberOfLiveAgents(); /** * Get the agents for given state and count. @@ -69,14 +69,14 @@ public interface AgentProcessControl { * @param count the count of agent to be get * @return agent list */ - public Set getAgents(AgentControllerState state, int count); + Set getAgents(AgentControllerState state, int count); /** * Get all available agents. * * @return agent list */ - public Set getAllAgents(); + Set getAllAgents(); /** * Get agent version for given {@link AgentIdentity}. diff --git a/ngrinder-core/src/main/java/net/grinder/console/communication/AgentProcessControlImplementation.java b/ngrinder-core/src/main/java/net/grinder/console/communication/AgentProcessControlImplementation.java index 18ff49c1a3..6eb0a66a74 100644 --- a/ngrinder-core/src/main/java/net/grinder/console/communication/AgentProcessControlImplementation.java +++ b/ngrinder-core/src/main/java/net/grinder/console/communication/AgentProcessControlImplementation.java @@ -26,7 +26,6 @@ import net.grinder.messages.agent.StopGrinderMessage; import net.grinder.messages.console.AgentAddress; import net.grinder.util.ListenerSupport; -import net.grinder.util.ListenerSupport.Informer; import org.ngrinder.monitor.controller.model.SystemDataModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,11 +43,10 @@ * * @author JunHo Yoon */ -@SuppressWarnings("SynchronizeOnNonFinalField") public class AgentProcessControlImplementation implements AgentProcessControl { private final ConsoleCommunication m_consoleCommunication; - private Map m_agentMap = new ConcurrentHashMap<>(); + private final Map m_agentMap = new ConcurrentHashMap<>(); private final ListenerSupport m_agentStatusUpdateListeners = new ListenerSupport<>(); private final ListenerSupport m_logListeners = new ListenerSupport<>(); private final ListenerSupport m_agentDownloadRequestListeners = new ListenerSupport<>(); @@ -113,24 +111,18 @@ public void handle(AgentControllerProcessReportMessage message) { messageDispatchRegistry.set(LogReportGrinderMessage.class, new AbstractHandler() { public void handle(final LogReportGrinderMessage message) { - m_logListeners.apply(new Informer() { - @Override - public void inform(LogArrivedListener listener) { - listener.logArrived(message.getTestId(), message.getAddress(), message.getLogs()); - } + m_logListeners.apply(listener -> { + listener.logArrived(message.getTestId(), message.getAddress(), message.getLogs()); }); } }); messageDispatchRegistry.set(AgentDownloadGrinderMessage.class, new AbstractHandler() { public void handle(final AgentDownloadGrinderMessage message) { - m_agentDownloadRequestListeners.apply(new Informer() { - @Override - public void inform(AgentDownloadRequestListener listener) { - AgentUpdateGrinderMessage agentUpdateGrinderMessage = listener.onAgentDownloadRequested(message.getVersion(), message.getNext()); - if (agentUpdateGrinderMessage != null) { - m_consoleCommunication.sendToAddressedAgents(message.getAddress(), agentUpdateGrinderMessage); - } + m_agentDownloadRequestListeners.apply(listener -> { + AgentUpdateGrinderMessage agentUpdateGrinderMessage = listener.onAgentDownloadRequested(message.getVersion(), message.getNext()); + if (agentUpdateGrinderMessage != null) { + m_consoleCommunication.sendToAddressedAgents(message.getAddress(), agentUpdateGrinderMessage); } }); } @@ -138,22 +130,16 @@ public void inform(AgentDownloadRequestListener listener) { messageDispatchRegistry.set(ConnectionAgentMessage.class, new AbstractHandler() { public void handle(final ConnectionAgentMessage message) { - m_connectionAgentListener.apply(new Informer() { - @Override - public void inform(ConnectionAgentListener listener) { - listener.onConnectionAgentMessage(message.getIp(), message.getName(), message.getPort()); - } + m_connectionAgentListener.apply(listener -> { + listener.onConnectionAgentMessage(message.getIp(), message.getName(), message.getPort()); }); } }); messageDispatchRegistry.set(ConnectionAgentCommunicationMessage.class, new AbstractHandler() { public void handle(final ConnectionAgentCommunicationMessage message) { - m_connectionAgentCommunicationListener.apply(new Informer() { - @Override - public void inform(ConnectionAgentCommunicationListener listener) { - listener.onConnectionAgentCommunication(message.getUsingPort(), message.getIp(), message.getPort()); - } + m_connectionAgentCommunicationListener.apply(listener -> { + listener.onConnectionAgentCommunication(message.getUsingPort(), message.getIp(), message.getPort()); }); } }); @@ -192,10 +178,8 @@ private void update() { m_newData = false; - m_agentStatusUpdateListeners.apply(new ListenerSupport.Informer() { - public void inform(AgentStatusUpdateListener agentStatusUpdateListener) { - agentStatusUpdateListener.update(unmodifiableMap(m_agentMap)); - } + m_agentStatusUpdateListeners.apply(agentStatusUpdateListener -> { + agentStatusUpdateListener.update(unmodifiableMap(m_agentMap)); }); } @@ -255,7 +239,7 @@ private interface Purgable { boolean shouldPurge(); } - private abstract class AbstractTimedReference implements Purgable { + private static abstract class AbstractTimedReference implements Purgable { private int m_purgeDelayCount; @Override @@ -276,7 +260,7 @@ public void initPurgeDelayCount() { } } - private final class AgentReference extends AbstractTimedReference { + private static final class AgentReference extends AbstractTimedReference { private final AgentControllerProcessReportMessage m_agentProcessReportMessage; /** @@ -294,7 +278,7 @@ private final class AgentReference extends AbstractTimedReference { * * @author JunHo Yoon */ - public final class AgentStatus implements Purgable { + public static final class AgentStatus implements Purgable { private volatile AgentReference m_agentReference; /** diff --git a/ngrinder-core/src/main/java/net/grinder/console/communication/ConsoleCommunicationImplementationEx.java b/ngrinder-core/src/main/java/net/grinder/console/communication/ConsoleCommunicationImplementationEx.java index 5715ef1d19..94d8c01a24 100644 --- a/ngrinder-core/src/main/java/net/grinder/console/communication/ConsoleCommunicationImplementationEx.java +++ b/ngrinder-core/src/main/java/net/grinder/console/communication/ConsoleCommunicationImplementationEx.java @@ -76,7 +76,7 @@ public final class ConsoleCommunicationImplementationEx implements ConsoleCommun @SuppressWarnings("UnusedDeclaration") public ConsoleCommunicationImplementationEx(Resources resources, ConsoleProperties properties, ErrorHandler errorHandler, TimeAuthority timeAuthority, - ConsoleCommunicationSetting consoleCommunicationSetting) throws DisplayMessageConsoleException { + ConsoleCommunicationSetting consoleCommunicationSetting) { m_resources = resources; m_properties = properties; m_errorHandler = errorHandler; diff --git a/ngrinder-core/src/main/java/net/grinder/console/communication/LogArrivedListener.java b/ngrinder-core/src/main/java/net/grinder/console/communication/LogArrivedListener.java index b5edd880f3..8ea1b3e563 100644 --- a/ngrinder-core/src/main/java/net/grinder/console/communication/LogArrivedListener.java +++ b/ngrinder-core/src/main/java/net/grinder/console/communication/LogArrivedListener.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.console.communication; @@ -19,7 +19,7 @@ /** * AgentStatusUpdateListener which is invoked when log is arrived from agent controller. - * + * * @author JunHo Yoon * @since 3.0 */ @@ -30,5 +30,5 @@ public interface LogArrivedListener extends EventListener { * @param agentAddress agent address * @param logs compressed log byte array */ - public void logArrived(String testId, AgentAddress agentAddress, byte[] logs); + void logArrived(String testId, AgentAddress agentAddress, byte[] logs); } diff --git a/ngrinder-core/src/main/java/net/grinder/console/model/ConsoleCommunicationSetting.java b/ngrinder-core/src/main/java/net/grinder/console/model/ConsoleCommunicationSetting.java index 106b78aef4..40697a7750 100644 --- a/ngrinder-core/src/main/java/net/grinder/console/model/ConsoleCommunicationSetting.java +++ b/ngrinder-core/src/main/java/net/grinder/console/model/ConsoleCommunicationSetting.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.console.model; @@ -31,8 +31,6 @@ public class ConsoleCommunicationSetting { /** * How long before we consider a client connection that presents no data to be * inactive. - * - * @return */ public long getInactiveClientTimeOut() { return inactiveClientTimeOut; @@ -45,8 +43,6 @@ public void setInactiveClientTimeOut(long inactiveClientTimeOut) { /** * Time in milliseconds that our ServerReceiver threads should sleep for if there's * no incoming messages. - * - * @return */ public long getIdlePollDelay() { return idlePollDelay; diff --git a/ngrinder-core/src/main/java/net/grinder/engine/agent/AgentImplementationEx.java b/ngrinder-core/src/main/java/net/grinder/engine/agent/AgentImplementationEx.java index 51666b61b8..0bc79c7a10 100644 --- a/ngrinder-core/src/main/java/net/grinder/engine/agent/AgentImplementationEx.java +++ b/ngrinder-core/src/main/java/net/grinder/engine/agent/AgentImplementationEx.java @@ -27,6 +27,7 @@ import net.grinder.common.GrinderProperties.PersistenceException; import net.grinder.common.processidentity.ProcessReport; import net.grinder.communication.*; +import net.grinder.console.ConsoleFoundation; import net.grinder.engine.common.ConnectorFactory; import net.grinder.engine.common.EngineException; import net.grinder.engine.common.ScriptLocation; @@ -59,6 +60,7 @@ /** * This is the entry point of The Grinder agent process. + * Extension of {@link AgentImplementation}. * * @author Grinder Developers. * @author JunHo Yoon (modified for nGrinder) diff --git a/ngrinder-core/src/main/java/net/grinder/engine/agent/ConnectionAgentCommunicationProxy.java b/ngrinder-core/src/main/java/net/grinder/engine/agent/ConnectionAgentCommunicationProxy.java index 29bda405b3..6a35afeb21 100644 --- a/ngrinder-core/src/main/java/net/grinder/engine/agent/ConnectionAgentCommunicationProxy.java +++ b/ngrinder-core/src/main/java/net/grinder/engine/agent/ConnectionAgentCommunicationProxy.java @@ -68,8 +68,8 @@ public interface CommunicationMessageSender { } private static class SocketPipeline extends Thread { - private Socket one; - private Socket other; + private final Socket one; + private final Socket other; public SocketPipeline(Socket one, Socket other) { this.one = one; @@ -90,21 +90,18 @@ public void run() { } private Thread transfer(InputStream in, OutputStream out) { - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; - int len = in.read(buffer); - while (len > -1 && !isClosed()) { - out.write(buffer, 0, len); - len = in.read(buffer); - } - } catch (SocketException e) { - // normal case. shutdown. - } catch (Exception e) { - throw new RuntimeException(e); + Thread thread = new Thread(() -> { + try { + byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; + int len = in.read(buffer); + while (len > -1 && !isClosed()) { + out.write(buffer, 0, len); + len = in.read(buffer); } + } catch (SocketException e) { + // normal case. shutdown. + } catch (Exception e) { + throw new RuntimeException(e); } }); thread.start(); @@ -117,11 +114,8 @@ private boolean isClosed() { } public static ConnectionAgentCommunicationProxy empty() { - return new ConnectionAgentCommunicationProxy(0, 0, null, new ConnectionAgentCommunicationProxy.CommunicationMessageSender() { - @Override - public void send() { - // noop - } + return new ConnectionAgentCommunicationProxy(0, 0, null, () -> { + // noop }) { @Override public void shutdown() { diff --git a/ngrinder-core/src/main/java/net/grinder/engine/agent/FileStore.java b/ngrinder-core/src/main/java/net/grinder/engine/agent/FileStore.java index 9d412d591f..1f7e303f0b 100644 --- a/ngrinder-core/src/main/java/net/grinder/engine/agent/FileStore.java +++ b/ngrinder-core/src/main/java/net/grinder/engine/agent/FileStore.java @@ -31,7 +31,6 @@ import net.grinder.util.FileContents; import net.grinder.util.StreamCopier; import org.apache.commons.io.FileUtils; -import org.ngrinder.common.exception.NGrinderRuntimeException; import org.slf4j.Logger; import java.io.File; diff --git a/ngrinder-core/src/main/java/net/grinder/engine/agent/LocalScriptTestDriveService.java b/ngrinder-core/src/main/java/net/grinder/engine/agent/LocalScriptTestDriveService.java index 97e6760645..2fe87369d6 100644 --- a/ngrinder-core/src/main/java/net/grinder/engine/agent/LocalScriptTestDriveService.java +++ b/ngrinder-core/src/main/java/net/grinder/engine/agent/LocalScriptTestDriveService.java @@ -50,7 +50,7 @@ public class LocalScriptTestDriveService { private static final Logger LOGGER = LoggerFactory.getLogger(LocalScriptTestDriveService.class); private static final int DEFAULT_TIMEOUT = 100; - private File requiredLibraryDirectory; + private final File requiredLibraryDirectory; public LocalScriptTestDriveService(File requiredLibraryDirectory) { this.requiredLibraryDirectory = requiredLibraryDirectory; @@ -202,15 +202,12 @@ public File doValidate(File base, File script, Condition eventSynchronisation, b @SuppressWarnings("ResultOfMethodCallIgnored") private void deleteLogs(File base) { - base.listFiles(new FileFilter() { - @Override - public boolean accept(File pathName) { - String extension = FilenameUtils.getExtension(pathName.getName()); - if (extension.startsWith("log")) { - pathName.delete(); - } - return true; + base.listFiles(pathName -> { + String extension = FilenameUtils.getExtension(pathName.getName()); + if (extension.startsWith("log")) { + pathName.delete(); } + return true; }); } diff --git a/ngrinder-core/src/main/java/net/grinder/engine/agent/PropertyBuilder.java b/ngrinder-core/src/main/java/net/grinder/engine/agent/PropertyBuilder.java index 97140ee0b9..aeb33ea0a5 100644 --- a/ngrinder-core/src/main/java/net/grinder/engine/agent/PropertyBuilder.java +++ b/ngrinder-core/src/main/java/net/grinder/engine/agent/PropertyBuilder.java @@ -25,7 +25,6 @@ import javax.net.ssl.SSLSocket; import java.io.File; -import java.io.FilenameFilter; import java.io.IOException; import java.net.InetAddress; import java.util.ArrayList; @@ -51,6 +50,7 @@ * @author JunHo Yoon * @since 3.0 */ +@SuppressWarnings("UnusedReturnValue") public class PropertyBuilder { private static final Logger LOGGER = LoggerFactory.getLogger(ProcessBuilder.class); private static final Set DISABLED_SSL_PROTOCOLS = new HashSet<>(singletonList("SSLv2Hello")); @@ -64,7 +64,7 @@ public class PropertyBuilder { private final boolean server; private final boolean useXmxLimit; private final String additionalJavaOpt; - private boolean enableLocalDNS; + private final boolean enableLocalDNS; /** @@ -257,7 +257,6 @@ protected StringBuilder addNativeLibraryPath(StringBuilder jvmArguments) { } protected static final long MIN_PER_PROCESS_MEM_SIZE = 50 * 1024 * 1024; - protected static final long DEFAULT_XMX_SIZE = 500 * 1024 * 1024; protected static final long DEFAULT_MAX_XMX_SIZE = 1024 * 1024 * 1024; protected StringBuilder addMemorySettings(StringBuilder jvmArguments) { @@ -293,7 +292,7 @@ protected StringBuilder addServerMode(StringBuilder jvmArguments) { } protected StringBuilder addSecurityManager(StringBuilder jvmArguments) { - return jvmArguments.append(" -Djava.security.manager=" + getSecurityManagerBySecurityLevel(securityLevel) + " "); + return jvmArguments.append(" -Djava.security.manager=").append(getSecurityManagerBySecurityLevel(securityLevel)).append(" "); } private String getSecurityManagerBySecurityLevel(String securityLevel) { @@ -323,15 +322,12 @@ public String buildCustomClassPath(final boolean useAbsolutePath) { customClassPath.append(getPath(baseFile, useAbsolutePath)); if (libFolder.exists()) { customClassPath.append(File.pathSeparator).append(getPath(new File(baseFile, "lib"), useAbsolutePath)); - libFolder.list(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - if (name.endsWith(".jar")) { - customClassPath.append(File.pathSeparator) - .append(getPath(new File(dir, name), useAbsolutePath)); - } - return true; + libFolder.list((dir, name) -> { + if (name.endsWith(".jar")) { + customClassPath.append(File.pathSeparator) + .append(getPath(new File(dir, name), useAbsolutePath)); } + return true; }); } return customClassPath.toString(); @@ -411,7 +407,7 @@ private StringBuilder addCustomDns(StringBuilder jvmArguments) { } private StringBuilder addUserDir(StringBuilder jvmArguments) { - jvmArguments.append(" -Duser.dir=" + baseDirectory.getFile().getPath() + " "); + jvmArguments.append(" -Duser.dir=").append(baseDirectory.getFile().getPath()).append(" "); return jvmArguments; } @@ -450,6 +446,7 @@ public String rebaseHostString(String hostString) { return newHostString.toString(); } + @SuppressWarnings("SameParameterValue") void addProperties(String key, String value) { this.properties.put(key, value); } diff --git a/ngrinder-core/src/main/java/net/grinder/engine/agent/ValidationPropertyBuilder.java b/ngrinder-core/src/main/java/net/grinder/engine/agent/ValidationPropertyBuilder.java index 89a2ae90b6..219e32cd38 100644 --- a/ngrinder-core/src/main/java/net/grinder/engine/agent/ValidationPropertyBuilder.java +++ b/ngrinder-core/src/main/java/net/grinder/engine/agent/ValidationPropertyBuilder.java @@ -4,7 +4,8 @@ import net.grinder.util.Directory; public class ValidationPropertyBuilder extends PropertyBuilder { - public ValidationPropertyBuilder(GrinderProperties properties, Directory baseDirectory, boolean securityEnabled, String securityLevel, String hostString, String hostName) { + public ValidationPropertyBuilder(GrinderProperties properties, Directory baseDirectory, boolean securityEnabled, + String securityLevel, String hostString, String hostName) { super(properties, baseDirectory, securityEnabled, securityLevel, hostString, hostName); } diff --git a/ngrinder-core/src/main/java/net/grinder/engine/common/AgentControllerConnectorFactory.java b/ngrinder-core/src/main/java/net/grinder/engine/common/AgentControllerConnectorFactory.java index aca579ecdf..e6169698fe 100644 --- a/ngrinder-core/src/main/java/net/grinder/engine/common/AgentControllerConnectorFactory.java +++ b/ngrinder-core/src/main/java/net/grinder/engine/common/AgentControllerConnectorFactory.java @@ -13,7 +13,6 @@ */ package net.grinder.engine.common; -import net.grinder.communication.CommunicationException; import net.grinder.communication.ConnectionType; import net.grinder.communication.Connector; diff --git a/ngrinder-core/src/main/java/net/grinder/engine/communication/AgentDownloadGrinderMessage.java b/ngrinder-core/src/main/java/net/grinder/engine/communication/AgentDownloadGrinderMessage.java index 9c8a113c7f..7555410287 100644 --- a/ngrinder-core/src/main/java/net/grinder/engine/communication/AgentDownloadGrinderMessage.java +++ b/ngrinder-core/src/main/java/net/grinder/engine/communication/AgentDownloadGrinderMessage.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,13 +9,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.engine.communication; import net.grinder.communication.Address; import net.grinder.communication.AddressAwareMessage; -import net.grinder.communication.CommunicationException; /** * Message for agent download from agent to controller. @@ -53,7 +52,7 @@ public void setNext(int next) { } @Override - public void setAddress(Address address) throws CommunicationException { + public void setAddress(Address address) { this.address = address; } diff --git a/ngrinder-core/src/main/java/net/grinder/engine/communication/AgentUpdateGrinderMessage.java b/ngrinder-core/src/main/java/net/grinder/engine/communication/AgentUpdateGrinderMessage.java index 992c8f0765..838d0abed4 100644 --- a/ngrinder-core/src/main/java/net/grinder/engine/communication/AgentUpdateGrinderMessage.java +++ b/ngrinder-core/src/main/java/net/grinder/engine/communication/AgentUpdateGrinderMessage.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.engine.communication; diff --git a/ngrinder-core/src/main/java/net/grinder/lang/groovy/GroovyHandler.java b/ngrinder-core/src/main/java/net/grinder/lang/groovy/GroovyHandler.java index 0f0e66d145..7faef764b5 100644 --- a/ngrinder-core/src/main/java/net/grinder/lang/groovy/GroovyHandler.java +++ b/ngrinder-core/src/main/java/net/grinder/lang/groovy/GroovyHandler.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.lang.groovy; @@ -18,12 +18,12 @@ /** * Groovy Language Handler. - * + * * @author JunHo Yoon * @since 3.2 */ public class GroovyHandler extends AbstractLanguageHandler { - private GroovyGrinderClassPathProcessor classPathProcessor = new GroovyGrinderClassPathProcessor(); + private final GroovyGrinderClassPathProcessor classPathProcessor = new GroovyGrinderClassPathProcessor(); /** * Constructor. diff --git a/ngrinder-core/src/main/java/net/grinder/lang/jython/JythonHandler.java b/ngrinder-core/src/main/java/net/grinder/lang/jython/JythonHandler.java index fdb168456d..4e434eba68 100644 --- a/ngrinder-core/src/main/java/net/grinder/lang/jython/JythonHandler.java +++ b/ngrinder-core/src/main/java/net/grinder/lang/jython/JythonHandler.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.lang.jython; @@ -18,13 +18,13 @@ /** * Jython Language Handler. - * + * * @author JunHo Yoon * @since 3.1 */ public class JythonHandler extends AbstractLanguageHandler { - private JythonGrinderClassPathProcessor classPathProcessor = new JythonGrinderClassPathProcessor(); + private final JythonGrinderClassPathProcessor classPathProcessor = new JythonGrinderClassPathProcessor(); /** * JythonHandler constructor. diff --git a/ngrinder-core/src/main/java/net/grinder/message/console/AgentControllerProcessReportMessage.java b/ngrinder-core/src/main/java/net/grinder/message/console/AgentControllerProcessReportMessage.java index 4c693e58fe..6410255661 100644 --- a/ngrinder-core/src/main/java/net/grinder/message/console/AgentControllerProcessReportMessage.java +++ b/ngrinder-core/src/main/java/net/grinder/message/console/AgentControllerProcessReportMessage.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.message.console; @@ -22,7 +22,7 @@ /** * Message for informing the console of agent process status. - * + * * @author JunHo Yoon * @since 3.0 */ @@ -36,13 +36,13 @@ public class AgentControllerProcessReportMessage implements AddressAwareMessage private final SystemDataModel systemDataModel; - private int connectingPort = 0; + private final int connectingPort; - private String version; + private final String version; /** * Creates a new AgentProcessReportMessage instance. - * + * * @param state The process state. See {@link net.grinder.common.processidentity.ProcessReport}. * @param systemDataModel system performance data model * @param connectingPort agent connecting console port @@ -71,7 +71,7 @@ public void setAddress(Address address) throws CommunicationException { /** * Accessor for the process identity. - * + * * @return The process identity. */ @SuppressWarnings("UnusedDeclaration") @@ -81,7 +81,7 @@ public AgentAddress getProcessAddress() { /** * Accessor for the process identity. - * + * * @return The process identity. */ public AgentIdentity getAgentIdentity() { @@ -90,7 +90,7 @@ public AgentIdentity getAgentIdentity() { /** * Accessor for the process state. - * + * * @return The process state. */ public AgentControllerState getState() { diff --git a/ngrinder-core/src/main/java/net/grinder/message/console/AgentStatusCategory.java b/ngrinder-core/src/main/java/net/grinder/message/console/AgentStatusCategory.java index 606e9586e4..8a18cf8c2d 100644 --- a/ngrinder-core/src/main/java/net/grinder/message/console/AgentStatusCategory.java +++ b/ngrinder-core/src/main/java/net/grinder/message/console/AgentStatusCategory.java @@ -27,7 +27,7 @@ public enum AgentStatusCategory { */ ERROR("red.png", false); private final String iconName; - private boolean active; + private final boolean active; AgentStatusCategory(String iconName, boolean active) { this.iconName = iconName; diff --git a/ngrinder-core/src/main/java/net/grinder/messages/agent/RefreshCacheMessage.java b/ngrinder-core/src/main/java/net/grinder/messages/agent/RefreshCacheMessage.java index 00e274d3c2..2967ac825a 100644 --- a/ngrinder-core/src/main/java/net/grinder/messages/agent/RefreshCacheMessage.java +++ b/ngrinder-core/src/main/java/net/grinder/messages/agent/RefreshCacheMessage.java @@ -10,7 +10,7 @@ * @since 3.5.0 * */ public final class RefreshCacheMessage implements Message { - private Set disFilesDigest; + private final Set disFilesDigest; public RefreshCacheMessage(Set disFilesDigest) { this.disFilesDigest = disFilesDigest; diff --git a/ngrinder-core/src/main/java/net/grinder/util/AbstractGrinderClassPathProcessor.java b/ngrinder-core/src/main/java/net/grinder/util/AbstractGrinderClassPathProcessor.java index b2fdc2b814..583e069b30 100644 --- a/ngrinder-core/src/main/java/net/grinder/util/AbstractGrinderClassPathProcessor.java +++ b/ngrinder-core/src/main/java/net/grinder/util/AbstractGrinderClassPathProcessor.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.util; @@ -62,7 +62,7 @@ static void setJUnitContext() { * @return classpath optimized for grinder. */ public String filterClassPath(String classPath, Logger logger) { - List classPathList = new ArrayList(); + List classPathList = new ArrayList<>(); for (String eachClassPath : checkNotNull(classPath).split(File.pathSeparator)) { String filename = FilenameUtils.getName(eachClassPath); if (isUsefulJar(filename) || isUsefulReferenceProject(eachClassPath)) { @@ -88,7 +88,7 @@ private boolean isUsefulReferenceProject(String path) { * @return classpath optimized for grinder. */ public String filterForeMostClassPath(String classPath, Logger logger) { - List classPathList = new ArrayList(); + List classPathList = new ArrayList<>(); for (String eachClassPath : checkNotNull(classPath).split(File.pathSeparator)) { String filename = FilenameUtils.getName(eachClassPath); if (isForemostJar(filename) || isUsefulForForemostReferenceProject(eachClassPath)) { @@ -108,7 +108,7 @@ public String filterForeMostClassPath(String classPath, Logger logger) { * @return classpath optimized for grinder. */ public String filterPatchClassPath(String classPath, Logger logger) { - List classPathList = new ArrayList(); + List classPathList = new ArrayList<>(); for (String eachClassPath : checkNotNull(classPath).split(File.pathSeparator)) { String filename = FilenameUtils.getName(eachClassPath); if (isPatchJar(filename)) { diff --git a/ngrinder-core/src/main/java/net/grinder/util/ListenerHelper.java b/ngrinder-core/src/main/java/net/grinder/util/ListenerHelper.java index f41822004a..9335d14270 100644 --- a/ngrinder-core/src/main/java/net/grinder/util/ListenerHelper.java +++ b/ngrinder-core/src/main/java/net/grinder/util/ListenerHelper.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,24 +9,24 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.util; /** * Listener Helper to shorten the {@link ListenerSupport} creation code. - * + * * @author JunHo Yoon * @since 3.0.2 */ public abstract class ListenerHelper { /** * Create a listener instance. - * + * * @param listener type. * @return created listener */ public static ListenerSupport create() { - return new ListenerSupport(); + return new ListenerSupport<>(); } } diff --git a/ngrinder-core/src/main/java/net/grinder/util/NetworkUtils.java b/ngrinder-core/src/main/java/net/grinder/util/NetworkUtils.java index f465a7b6b7..7c322e3bc7 100644 --- a/ngrinder-core/src/main/java/net/grinder/util/NetworkUtils.java +++ b/ngrinder-core/src/main/java/net/grinder/util/NetworkUtils.java @@ -25,10 +25,7 @@ import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.net.*; import java.util.ArrayList; import java.util.Enumeration; @@ -52,6 +49,7 @@ * @author Mavlarn * @since 3.0 */ +@SuppressWarnings("SameParameterValue") public abstract class NetworkUtils { private static final Logger LOGGER = LoggerFactory.getLogger(NetworkUtils.class); public static String DEFAULT_LOCAL_HOST_ADDRESS = getLocalHostAddress(); @@ -120,7 +118,7 @@ static InetAddress getLocalInetAddress(String byConnecting, int port) { try { addr = getFirstNonLoopbackAddress(true, false); } catch (SocketException e2) { - addr = null; + noOp(); } } return addr; @@ -222,7 +220,7 @@ public static InetAddress[] getIpsFromHost(String host) { * @return port list */ public static List getAvailablePorts(String ip, int size, int from, int limit) { - List ports = new ArrayList(size); + List ports = new ArrayList<>(size); int freePort; InetAddress inetAddress = null; if (StringUtils.isNotBlank(ip)) { @@ -345,7 +343,7 @@ public IPPortPair(String ip, int port) { try { this.ip = InetAddress.getByName(ip); } catch (UnknownHostException e) { - LOGGER.error("{} is not accessible ip"); + LOGGER.error("{} is not accessible ip", ip); } this.port = port; } @@ -478,7 +476,7 @@ public static String getIP(String ipOrHost) { private static List getAllLocalNonLoopbackAddresses(boolean onlyIPv4) { - List addresses = new ArrayList(); + List addresses = new ArrayList<>(); final Enumeration networkInterfaces; try { networkInterfaces = getNetworkInterfaces(); @@ -528,10 +526,10 @@ public static String selectLocalIp(List ips) { } public static List getDnsServers() throws NamingException { - Hashtable env = new Hashtable(); + Hashtable env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); DirContext ctx = null; - List dnsServers = new ArrayList(); + List dnsServers = new ArrayList<>(); try { ctx = new InitialDirContext(env); String dnsString = (String) ctx.getEnvironment().get("java.naming.provider.url"); diff --git a/ngrinder-core/src/main/java/net/grinder/util/UnitUtils.java b/ngrinder-core/src/main/java/net/grinder/util/UnitUtils.java index 4b7364295b..c30351b9bc 100644 --- a/ngrinder-core/src/main/java/net/grinder/util/UnitUtils.java +++ b/ngrinder-core/src/main/java/net/grinder/util/UnitUtils.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.util; @@ -17,7 +17,7 @@ /** * Unit Conversion Utility. - * + * * @author JunHo Yoon * @since 3.1.2 */ @@ -39,7 +39,7 @@ public abstract class UnitUtils { /** * Get the display of the given byte size. - * + * * @param size size * @return display version of the byte size */ @@ -53,7 +53,7 @@ public static String byteCountToDisplaySize(long size) { } else if (size / ONE_KB > 0) { displaySize = format.format((double) size / ONE_KB) + "KB"; } else { - displaySize = String.valueOf(size) + "B"; + displaySize = size + "B"; } return displaySize; } diff --git a/ngrinder-core/src/main/java/net/grinder/util/VersionNumber.java b/ngrinder-core/src/main/java/net/grinder/util/VersionNumber.java index f4813655f2..0286e71fe5 100644 --- a/ngrinder-core/src/main/java/net/grinder/util/VersionNumber.java +++ b/ngrinder-core/src/main/java/net/grinder/util/VersionNumber.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.util; @@ -64,7 +64,7 @@ public String toString() { if (i != 0) { buf.append('.'); } - buf.append(Integer.toString(this.digits[i])); + buf.append(this.digits[i]); } return buf.toString(); } @@ -85,9 +85,10 @@ public int hashCode() { /* * (non-Javadoc) - * + * * @see java.lang.Comparable#compareTo(java.lang.Object) */ + @SuppressWarnings("NullableProblems") @Override public int compareTo(VersionNumber rhs) { for (int i = 0; ; i++) { diff --git a/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarter.java b/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarter.java index 13c638c2bc..a2c6b9a196 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarter.java +++ b/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarter.java @@ -182,7 +182,7 @@ public static void main(String[] args) { } final List unknownOptions = commander.getUnknownOptions(); modeParam = param.getModeParam(); - modeParam.parse(unknownOptions.toArray(new String[unknownOptions.size()])); + modeParam.parse(unknownOptions.toArray(new String[0])); if (modeParam.version != null) { LOG.info("nGrinder v" + getStaticVersion()); diff --git a/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarterParam.java b/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarterParam.java index 9c77ec8252..e7cb648ef4 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarterParam.java +++ b/ngrinder-core/src/main/java/org/ngrinder/NGrinderAgentStarterParam.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder; @@ -32,10 +32,10 @@ */ @Parameters(separators = "= ") public class NGrinderAgentStarterParam { - @Parameter(names = {"-m", "-mode", "--mode"}, required = false, + @Parameter(names = {"-m", "-mode", "--mode"}, description = "run mode. The agent/monitor modes are available.", hidden = true) public String mode = null; - @Parameter(names = {"-c", "-command", "--command"}, required = false, description = "execution command. " + + @Parameter(names = {"-c", "-command", "--command"}, description = "execution command. " + "The stop/start command are available.", hidden = true) public String command = "start"; @@ -52,17 +52,17 @@ public NGrinderModeParam getModeParam() { public enum NGrinderModeParam { agent("run_agent") { - @Parameter(names = {"-ch", "--controller-host"}, required = false, description = "controller host or ip.") + @Parameter(names = {"-ch", "--controller-host"}, description = "controller host or ip.") public String controllerHost = null; - @Parameter(names = {"-cp", "--controller-port"}, required = false, description = "controller port.") + @Parameter(names = {"-cp", "--controller-port"}, description = "controller port.") public Integer controllerPort = null; - @Parameter(names = {"-r", "--region"}, required = false, description = "region") + @Parameter(names = {"-r", "--region"}, description = "region") public String region = null; - @Parameter(names = {"-hi", "--host-id"}, required = false, description = "this agent's unique host id") + @Parameter(names = {"-hi", "--host-id"}, description = "this agent's unique host id") public String hostId = null; @@ -92,8 +92,7 @@ protected void processInternal() { } }; - @Parameter(names = {"-ah", "--agent-home"}, required = false, - description = "this agent's unique home path. The default is ~/.ngrinder_agent") + @Parameter(names = {"-ah", "--agent-home"}, description = "this agent's unique home path. The default is ~/.ngrinder_agent") public String agentHome = null; @@ -105,14 +104,14 @@ protected void processInternal() { @DynamicParameter(names = "-D", description = "dynamic parameters", hidden = true) - public Map params = new HashMap(); + public Map params = new HashMap<>(); @SuppressWarnings("FieldCanBeLocal") @Parameter(names = {"-help", "-?", "-h"}, description = "prints this message") public Boolean help = null; - private JCommander commander; + private final JCommander commander; NGrinderModeParam(String programName) { this.commander = new JCommander(NGrinderModeParam.this); diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/constants/AgentConstants.java b/ngrinder-core/src/main/java/org/ngrinder/common/constants/AgentConstants.java index dbba03825c..7d7c813362 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/constants/AgentConstants.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/constants/AgentConstants.java @@ -19,23 +19,23 @@ * @since 3.3 */ public interface AgentConstants { - public static final String PROP_AGENT_ALL_LOGS = "agent.all_logs"; - public static final String PROP_AGENT_KEEP_LOGS = "agent.keep_logs"; - public static final String PROP_AGENT_UPDATE_ALWAYS = "agent.update_always"; - public static final String PROP_AGENT_CONTROLLER_HOST = "agent.controller_host"; - public static final String PROP_AGENT_CONTROLLER_PORT = "agent.controller_port"; - public static final String PROP_AGENT_HOST_ID = "agent.host_id"; - public static final String PROP_AGENT_JAVA_OPT = "agent.java_opt"; - public static final String PROP_AGENT_JVM_CLASSPATH = "agent.jvm.classpath"; - public static final String PROP_AGENT_LIMIT_XMX = "agent.limit_xmx"; - public static final String PROP_AGENT_REGION = "agent.region"; - public static final String PROP_AGENT_SERVER_MODE = "agent.server_mode"; - public static final String PROP_AGENT_CONNECTION_MODE = "agent.connection_mode"; - public static final String PROP_AGENT_CONNECTION_PORT = "agent.connection_port"; - public static final String PROP_AGENT_BROADCAST_IP = "agent.broadcast_ip"; - public static final String PROP_AGENT_ENABLE_LOCAL_DNS = "agent.enable_local_dns"; - public static final String PROP_AGENT_ENABLE_SECURITY = "agent.enable_security"; + String PROP_AGENT_ALL_LOGS = "agent.all_logs"; + String PROP_AGENT_KEEP_LOGS = "agent.keep_logs"; + String PROP_AGENT_UPDATE_ALWAYS = "agent.update_always"; + String PROP_AGENT_CONTROLLER_HOST = "agent.controller_host"; + String PROP_AGENT_CONTROLLER_PORT = "agent.controller_port"; + String PROP_AGENT_HOST_ID = "agent.host_id"; + String PROP_AGENT_JAVA_OPT = "agent.java_opt"; + String PROP_AGENT_JVM_CLASSPATH = "agent.jvm.classpath"; + String PROP_AGENT_LIMIT_XMX = "agent.limit_xmx"; + String PROP_AGENT_REGION = "agent.region"; + String PROP_AGENT_SERVER_MODE = "agent.server_mode"; + String PROP_AGENT_CONNECTION_MODE = "agent.connection_mode"; + String PROP_AGENT_CONNECTION_PORT = "agent.connection_port"; + String PROP_AGENT_BROADCAST_IP = "agent.broadcast_ip"; + String PROP_AGENT_ENABLE_LOCAL_DNS = "agent.enable_local_dns"; + String PROP_AGENT_ENABLE_SECURITY = "agent.enable_security"; - public static final String VALUE_AGENT_TO_CONTROLLER = "agent_to_controller"; - public static final String VALUE_CONTROLLER_TO_AGENT = "controller_to_agent"; + String VALUE_AGENT_TO_CONTROLLER = "agent_to_controller"; + String VALUE_CONTROLLER_TO_AGENT = "controller_to_agent"; } diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/constants/CommonConstants.java b/ngrinder-core/src/main/java/org/ngrinder/common/constants/CommonConstants.java index cd8ad21569..bef10319aa 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/constants/CommonConstants.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/constants/CommonConstants.java @@ -19,8 +19,8 @@ * @since 3.3 */ public interface CommonConstants { - public static final String PROP_COMMON_VERBOSE = "common.verbose"; - public static final String PROP_COMMON_START_MODE = "common.start_mode"; - public static final String PROP_COMMON_DEV_MODE = "common.dev_mode"; - public static final String PROP_COMMON_SILENT_MODE = "common.silent_mode"; + String PROP_COMMON_VERBOSE = "common.verbose"; + String PROP_COMMON_START_MODE = "common.start_mode"; + String PROP_COMMON_DEV_MODE = "common.dev_mode"; + String PROP_COMMON_SILENT_MODE = "common.silent_mode"; } diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/constants/GrinderConstants.java b/ngrinder-core/src/main/java/org/ngrinder/common/constants/GrinderConstants.java index 5b1e0ee9a9..03632835c1 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/constants/GrinderConstants.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/constants/GrinderConstants.java @@ -21,32 +21,32 @@ public interface GrinderConstants { // GRINDER_PROPERTY_KEY - public static final String GRINDER_PROP_AGENTS = "grinder.agents"; - public static final String GRINDER_PROP_PROCESSES = "grinder.processes"; - public static final String GRINDER_PROP_THREAD = "grinder.threads"; - public static final String GRINDER_PROP_RUNS = "grinder.runs"; - public static final String GRINDER_PROP_PROCESS_INCREMENT = "grinder.processIncrement"; - public static final String GRINDER_PROP_PROCESS_INCREMENT_INTERVAL = "grinder.processIncrementInterval"; - public static final String GRINDER_PROP_INITIAL_PROCESS = "grinder.initialProcesses"; - public static final String GRINDER_PROP_DURATION = "grinder.duration"; - public static final String GRINDER_PROP_SCRIPT = "grinder.script"; - public static final String GRINDER_PROP_PARAM = "grinder.param"; - public static final String GRINDER_PROP_JVM_CLASSPATH = "grinder.jvm.classpath"; - public static final String GRINDER_PROP_JVM_USER_LIBRARY_CLASSPATH = "grinder.jvm.user.library.classpath"; - public static final String GRINDER_PROP_JVM_ARGUMENTS = "grinder.jvm.arguments"; - public static final String GRINDER_PROP_USE_CONSOLE = "grinder.useConsole"; - public static final String GRINDER_PROP_REPORT_TO_CONSOLE = "grinder.reportToConsole.interval"; - public static final String GRINDER_PROP_INITIAL_SLEEP_TIME = "grinder.initialSleepTime"; - public static final String GRINDER_PROP_INITIAL_THREAD_SLEEP_TIME = "grinder.initialThreadSleepTime"; - public static final String GRINDER_PROP_THREAD_RAMPUP ="grinder.threadRampUp"; - public static final String GRINDER_PROP_TEST_ID = "grinder.test.id"; - public static final String GRINDER_PROP_IGNORE_SAMPLE_COUNT = "grinder.ignoreSampleCount"; - public static final String GRINDER_PROP_SECURITY = "grinder.security"; - public static final String GRINDER_PROP_SECURITY_LEVEL = "grinder.security.level"; - public static final String GRINDER_PROP_USER = "grinder.user"; - public static final String GRINDER_PROP_ETC_HOSTS = "ngrinder.etc.hosts"; - public static final String GRINDER_SECURITY_LEVEL_LIGHT = "light"; - public static final String GRINDER_SECURITY_LEVEL_NORMAL = "normal"; - public static final String DEFAULT_GRINDER_PROPERTIES = "grinder.properties"; + String GRINDER_PROP_AGENTS = "grinder.agents"; + String GRINDER_PROP_PROCESSES = "grinder.processes"; + String GRINDER_PROP_THREAD = "grinder.threads"; + String GRINDER_PROP_RUNS = "grinder.runs"; + String GRINDER_PROP_PROCESS_INCREMENT = "grinder.processIncrement"; + String GRINDER_PROP_PROCESS_INCREMENT_INTERVAL = "grinder.processIncrementInterval"; + String GRINDER_PROP_INITIAL_PROCESS = "grinder.initialProcesses"; + String GRINDER_PROP_DURATION = "grinder.duration"; + String GRINDER_PROP_SCRIPT = "grinder.script"; + String GRINDER_PROP_PARAM = "grinder.param"; + String GRINDER_PROP_JVM_CLASSPATH = "grinder.jvm.classpath"; + String GRINDER_PROP_JVM_USER_LIBRARY_CLASSPATH = "grinder.jvm.user.library.classpath"; + String GRINDER_PROP_JVM_ARGUMENTS = "grinder.jvm.arguments"; + String GRINDER_PROP_USE_CONSOLE = "grinder.useConsole"; + String GRINDER_PROP_REPORT_TO_CONSOLE = "grinder.reportToConsole.interval"; + String GRINDER_PROP_INITIAL_SLEEP_TIME = "grinder.initialSleepTime"; + String GRINDER_PROP_INITIAL_THREAD_SLEEP_TIME = "grinder.initialThreadSleepTime"; + String GRINDER_PROP_THREAD_RAMPUP ="grinder.threadRampUp"; + String GRINDER_PROP_TEST_ID = "grinder.test.id"; + String GRINDER_PROP_IGNORE_SAMPLE_COUNT = "grinder.ignoreSampleCount"; + String GRINDER_PROP_SECURITY = "grinder.security"; + String GRINDER_PROP_SECURITY_LEVEL = "grinder.security.level"; + String GRINDER_PROP_USER = "grinder.user"; + String GRINDER_PROP_ETC_HOSTS = "ngrinder.etc.hosts"; + String GRINDER_SECURITY_LEVEL_LIGHT = "light"; + String GRINDER_SECURITY_LEVEL_NORMAL = "normal"; + String DEFAULT_GRINDER_PROPERTIES = "grinder.properties"; } diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/constants/InternalConstants.java b/ngrinder-core/src/main/java/org/ngrinder/common/constants/InternalConstants.java index 20c830848f..3ab56f9d49 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/constants/InternalConstants.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/constants/InternalConstants.java @@ -19,5 +19,5 @@ * @since 3.3 */ public interface InternalConstants { - public static final String PROP_INTERNAL_NGRINDER_VERSION = "ngrinder.version"; + String PROP_INTERNAL_NGRINDER_VERSION = "ngrinder.version"; } diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/constants/MonitorConstants.java b/ngrinder-core/src/main/java/org/ngrinder/common/constants/MonitorConstants.java index d6e413c744..be962eb6d9 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/constants/MonitorConstants.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/constants/MonitorConstants.java @@ -19,14 +19,14 @@ * @since 3.3 */ public interface MonitorConstants { - public static final String PROP_MONITOR_BINDING_IP = "monitor.binding_ip"; - public static final String PROP_MONITOR_BINDING_PORT = "monitor.binding_port"; + String PROP_MONITOR_BINDING_IP = "monitor.binding_ip"; + String PROP_MONITOR_BINDING_PORT = "monitor.binding_port"; /** * Monitor Constant */ - public static final int DEFAULT_MONITOR_COLLECTOR_INTERVAL = 1; - public static final String DEFAULT_MONITOR_DOMAIN = "org.ngrinder.monitor"; - public static final String SYSTEM = "name=System"; - public static final String MONITOR_FILE_PREFIX = "monitor_system_"; + int DEFAULT_MONITOR_COLLECTOR_INTERVAL = 1; + String DEFAULT_MONITOR_DOMAIN = "org.ngrinder.monitor"; + String SYSTEM = "name=System"; + String MONITOR_FILE_PREFIX = "monitor_system_"; } diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/util/AccessUtils.java b/ngrinder-core/src/main/java/org/ngrinder/common/util/AccessUtils.java index 7ca40612cf..07af682900 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/util/AccessUtils.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/util/AccessUtils.java @@ -30,7 +30,7 @@ public static long getSafe(Long value) { } public static boolean getSafe(Boolean value) { - return (value == null) ? false : value; + return value != null && value; } public static boolean getSafe(Boolean value, boolean b) { diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/util/CollectionUtils.java b/ngrinder-core/src/main/java/org/ngrinder/common/util/CollectionUtils.java index f1db4ec005..ad369617ee 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/util/CollectionUtils.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/util/CollectionUtils.java @@ -17,7 +17,7 @@ public abstract class CollectionUtils { * @return {@link HashMap} */ public static Map newHashMap() { - return new HashMap(); + return new HashMap<>(); } /** @@ -28,7 +28,7 @@ public static Map newHashMap() { * @return {@link LinkedHashMap} */ public static Map newLinkedHashMap() { - return new LinkedHashMap(); + return new LinkedHashMap<>(); } /** @@ -38,7 +38,7 @@ public static Map newLinkedHashMap() { * @return {@link HashSet} */ public static Set newHashSet() { - return new HashSet(); + return new HashSet<>(); } /** @@ -48,7 +48,7 @@ public static Set newHashSet() { * @return {@link LinkedHashSet} */ public static Set newLinkedHashSet() { - return new LinkedHashSet(); + return new LinkedHashSet<>(); } /** @@ -59,7 +59,7 @@ public static Set newLinkedHashSet() { * @return {@link ArrayList} */ public static List newArrayList(int size) { - return new ArrayList(size); + return new ArrayList<>(size); } /** @@ -69,7 +69,7 @@ public static List newArrayList(int size) { * @return {@link ArrayList} */ public static List newArrayList() { - return new ArrayList(); + return new ArrayList<>(); } /** @@ -82,7 +82,7 @@ public static List newArrayList() { * @return created map */ public static Map buildMap(K key1, V value1) { - Map map = new HashMap(1); + Map map = new HashMap<>(1); map.put(key1, value1); return map; } @@ -99,7 +99,7 @@ public static Map buildMap(K key1, V value1) { * @return create map */ public static Map buildMap(K key1, V value1, K key2, V value2) { - Map map = new HashMap(2); + Map map = new HashMap<>(2); map.put(key1, value1); map.put(key2, value2); return map; @@ -119,7 +119,7 @@ public static Map buildMap(K key1, V value1, K key2, V value2) { * @return create map */ public static Map buildMap(K key1, V value1, K key2, V value2, K key3, V value3) { - Map map = new HashMap(3); + Map map = new HashMap<>(3); map.put(key1, value1); map.put(key2, value2); map.put(key3, value3); @@ -186,7 +186,7 @@ public static Map buildMap(K key1, V value1, K key2, V value2, K ke * @return set */ public static Set selectSome(Set set, int count) { - Set newSet = new HashSet(); + Set newSet = new HashSet<>(); int i = 0; for (T each : set) { if (++i > count) { @@ -206,7 +206,7 @@ public static Set selectSome(Set set, int count) { * @return created {@link HashMap} instance */ public static HashMap newHashMap(int size) { - return new HashMap(size); + return new HashMap<>(size); } /** @@ -218,7 +218,7 @@ public static HashMap newHashMap(int size) { * @return created {@link HashMap} instance */ public static HashMap newHashMap(Collection base) { - return new HashMap(base.size()); + return new HashMap<>(base.size()); } /** diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/util/CompressionUtils.java b/ngrinder-core/src/main/java/org/ngrinder/common/util/CompressionUtils.java index 3a4a61c4ef..4bad6814a1 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/util/CompressionUtils.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/util/CompressionUtils.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; @@ -22,8 +22,6 @@ import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.*; import java.nio.charset.Charset; @@ -42,9 +40,8 @@ * * @author JunHo Yoon */ -@SuppressWarnings("All") +@SuppressWarnings({"ResultOfMethodCallIgnored", "unused"}) public abstract class CompressionUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(CompressionUtils.class); /** * Unzip the given zipped file with given character set. @@ -110,9 +107,9 @@ public static void unzip(InputStream is, File destDir, String charsetName) { ZipInputStream zis = null; FileOutputStream fos = null; try { - File folder = destDir; - if (!folder.exists()) { - folder.mkdir(); + + if (!destDir.exists()) { + destDir.mkdir(); } zis = new ZipInputStream(is); @@ -246,7 +243,7 @@ public static void zip(File src, OutputStream os, String charsetName, boolean in byte[] buf = new byte[8 * 1024]; String name; - Stack stack = new Stack(); + Stack stack = new Stack<>(); File root; if (src.isDirectory()) { if (includeSrc) { @@ -254,8 +251,8 @@ public static void zip(File src, OutputStream os, String charsetName, boolean in root = src.getParentFile(); } else { File[] fs = checkNotNull(src.listFiles()); - for (int i = 0; i < fs.length; i++) { - stack.push(fs[i]); + for (File f : fs) { + stack.push(f); } root = src; @@ -270,11 +267,11 @@ public static void zip(File src, OutputStream os, String charsetName, boolean in name = toPath(root, f); if (f.isDirectory()) { File[] fs = checkNotNull(f.listFiles()); - for (int i = 0; i < fs.length; i++) { - if (fs[i].isDirectory()) { - stack.push(fs[i]); + for (File file : fs) { + if (file.isDirectory()) { + stack.push(file); } else { - stack.add(0, fs[i]); + stack.add(0, file); } } } else { @@ -319,7 +316,7 @@ private static String toPath(File root, File dir) { */ @SuppressWarnings("resource") public static List untar(final File inFile, final File outputDir) { - final List untaredFiles = new LinkedList(); + final List untaredFiles = new LinkedList<>(); InputStream is = null; TarArchiveInputStream debInputStream = null; try { @@ -405,7 +402,6 @@ public static File ungzip(final File inFile, final File outFile) { * * @param jarFile jar file * @param processor jar file entry predicate - * @throws IOException thrown when having IO problem. */ public static void processJarEntries(File jarFile, ZipEntryProcessor processor) { try { @@ -481,11 +477,11 @@ public static void addInputStreamToTar(TarArchiveOutputStream tarStream, InputSt /** * Add the given byte into tar. * - * @param tarStream TarArchive outputStream - * @param data data byte array - * @param path relative path to append - * @param size size of stream - * @param mode mode for this entry + * @param tarArchiveOutputStream TarArchive outputStream + * @param data data byte array + * @param path relative path to append + * @param size size of stream + * @param mode mode for this entry * @throws IOException thrown when having IO problem. */ public static void addByteToTar(TarArchiveOutputStream tarArchiveOutputStream, byte[] data, String path, long size, int mode) throws IOException { @@ -530,10 +526,10 @@ public static void addFileToTar(TarArchiveOutputStream tarStream, File file, Str public interface ZipEntryProcessor { - public void process(ZipFile zipFile, ZipEntry je) throws IOException; + void process(ZipFile zipFile, ZipEntry je) throws IOException; } public interface FilePredicate { - public boolean evaluate(Object object); + boolean evaluate(Object object); } } diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/util/DateUtils.java b/ngrinder-core/src/main/java/org/ngrinder/common/util/DateUtils.java index 10270825d9..a983018724 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/util/DateUtils.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/util/DateUtils.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; @@ -27,10 +27,11 @@ /** * Date Utility. - * + * * @author JunHo Yoon * @since 3.0 */ +@SuppressWarnings("JavadocReference") public abstract class DateUtils { private static final int CONSTANT_10 = 10; @@ -47,18 +48,18 @@ public abstract class DateUtils { /** * Get the time in long format : "yyyyMMddHHmmss". - * + * * @param date date to be format * @return time time in format of long type */ public static long getCollectTimeInLong(Date date) { SimpleDateFormat collectTimeFormat = new SimpleDateFormat("yyyyMMddHHmmss"); - return Long.valueOf(collectTimeFormat.format(date)); + return Long.parseLong(collectTimeFormat.format(date)); } /** * Convert user date to new date with server side Locale. - * + * * @param userTimeZone user TimeZone id * @param userDate date in user's Local * @return serverDate data in server's Local @@ -71,7 +72,7 @@ public static Date convertToServerDate(String userTimeZone, Date userDate) { /** * Convert server date to new date with user Locale. - * + * * @param userTimeZone user TimeZone id * @param serverDate date in server's Local * @return serverDate data in user's Local @@ -84,7 +85,7 @@ public static Date convertToUserDate(String userTimeZone, Date serverDate) { /** * Format date to {@value #FULL_DATE_FORMAT}. - * + * * @param date date * @return formatted string */ @@ -94,12 +95,12 @@ public static String dateToString(Date date) { /** * Get time zones. - * + * * @return map time zone id and GMT */ public static Map getFilteredTimeZoneMap() { if (timezoneIDMap == null) { - timezoneIDMap = new LinkedHashMap(); + timezoneIDMap = new LinkedHashMap<>(); String[] ids = TimeZone.getAvailableIDs(); for (String id : ids) { TimeZone zone = TimeZone.getTimeZone(id); @@ -116,7 +117,7 @@ public static Map getFilteredTimeZoneMap() { /** * Convert string date to Date with {@value #SIMPLE_DATE_FORMAT}. - * + * * @param strDate date string * @return date * @throws ParseException @@ -129,11 +130,11 @@ public static Date toSimpleDate(String strDate) throws ParseException { /** * Convert string date to Date with {@value #FULL_DATE_FORMAT}. - * + * * @param strDate * date string * @return date - * + * * @throws ParseException * thrown when the given strDate is not {@link #FULL_DATE_FORMAT} */ @@ -144,7 +145,7 @@ public static Date toDate(String strDate) throws ParseException { /** * Add days on date. - * + * * @param date base date * @param days days to be added. * @return added Date @@ -158,7 +159,7 @@ public static Date addDay(Date date, int days) { /** * Convert millisecond to DD:HH:MM:SS style. - * + * * @param ms Millisecond * @return DD:HH:MM:SS formatted string */ @@ -178,7 +179,7 @@ public static String ms2Time(long ms) { /** * Convert time to millisecond. - * + * * @param day day * @param hour hour * @param min min @@ -191,7 +192,7 @@ public static long timeToMs(int day, int hour, int min, int sec) { /** * Compare two date in minute detail. - * + * * @param d1 date * @param d2 date * @return true if two {@link Date} are same in minute level diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/util/Preconditions.java b/ngrinder-core/src/main/java/org/ngrinder/common/util/Preconditions.java index 9cc1482988..350de6c49b 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/util/Preconditions.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/util/Preconditions.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; @@ -268,7 +268,7 @@ public static T checkExist(T reference, String message, Object... args) { * @param errorMessageTemplate error message template * @param errorMessageArgs arguments to be filled in the template. */ - + @SuppressWarnings("UnusedReturnValue") public static T checkNull(T reference, String errorMessageTemplate, Object... errorMessageArgs) { if (reference != null) { // If either of these parameters is null, the right thing happens anyway @@ -337,20 +337,20 @@ public static T checkNotNull(T reference, @Nullable String errorMessageTempl /* * All recent hotspots (as of 2009) *really* like to have the natural code - * + * * if (guardExpression) { throw new BadException(messageExpression); } - * + * * refactored so that messageExpression is moved to a separate String-returning method. - * + * * if (guardExpression) { throw new BadException(badMsg(...)); } - * + * * The alternative natural refactorings into void or Exception-returning methods are much slower. This is a big deal * - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This is a hotspot optimizer bug, which * should be fixed, but that's a separate, big project). - * + * * The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a RangeCheckMicroBenchmark in * the JDK that was used to test this. - * + * * But the methods in this class want to throw different exceptions, depending on the args, so it appears that this * pattern is not directly applicable. But we can use the ridiculous, devious trick of throwing an exception in the * middle of the construction of another exception. Hotspot is fine with that. @@ -485,7 +485,7 @@ static String format(String template, @Nullable Object... args) { if (placeholderStart == -1) { break; } - builder.append(template.substring(templateStart, placeholderStart)); + builder.append(template, templateStart, placeholderStart); builder.append(args[i++]); templateStart = placeholderStart + 2; } diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/util/PropertiesKeyMapper.java b/ngrinder-core/src/main/java/org/ngrinder/common/util/PropertiesKeyMapper.java index 5d7b32ca93..8b28968bfc 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/util/PropertiesKeyMapper.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/util/PropertiesKeyMapper.java @@ -9,8 +9,8 @@ import static org.ngrinder.common.util.Preconditions.checkNotNull; public class PropertiesKeyMapper { - private Map> keyMaps = new HashMap>(); - private Map defaultValues = new HashMap(); + private final Map> keyMaps = new HashMap<>(); + private final Map defaultValues = new HashMap<>(); private PropertiesKeyMapper() { } @@ -25,7 +25,7 @@ public PropertiesKeyMapper init(String propertyMapName) { } String[] split = line.split(","); String key = null; - List values = new ArrayList(); + List values = new ArrayList<>(); for (int i = 0; i < split.length; i++) { if (i == 0) { key = split[0]; diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/util/PropertiesWrapper.java b/ngrinder-core/src/main/java/org/ngrinder/common/util/PropertiesWrapper.java index 3b52d498d4..1acd12fddb 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/util/PropertiesWrapper.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/util/PropertiesWrapper.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; @@ -33,7 +33,7 @@ public class PropertiesWrapper { private final Properties properties; @SuppressWarnings("UnusedDeclaration") private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesWrapper.class); - private PropertiesKeyMapper propertiesKeyMapper; + private final PropertiesKeyMapper propertiesKeyMapper; /** * Constructor. diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/util/SystemInfoUtils.java b/ngrinder-core/src/main/java/org/ngrinder/common/util/SystemInfoUtils.java index 6e38ed697c..272c8244b3 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/util/SystemInfoUtils.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/util/SystemInfoUtils.java @@ -43,15 +43,15 @@ */ public class SystemInfoUtils { - private static OperatingSystem operatingSystem; - private static CentralProcessor centralProcessor; - private static GlobalMemory globalMemory; + private static final OperatingSystem operatingSystem; + private static final CentralProcessor centralProcessor; + private static final GlobalMemory globalMemory; + + private static final List networkIFs; // For calculate current cpu load. private static long[] prevTicks; - private static List networkIFs; - static { SystemInfo systemInfo = new SystemInfo(); HardwareAbstractionLayer hardware = systemInfo.getHardware(); @@ -67,6 +67,7 @@ public static OSProcess getProcess(int pid) { return operatingSystem.getProcess(pid); } + @SuppressWarnings("UnusedReturnValue") public static List killProcess(int pid) { return isWindows() ? runNative("taskkill /f /pid " + pid) : runNative("kill -9 " + pid); } diff --git a/ngrinder-core/src/main/java/org/ngrinder/extension/OnControllerLifeCycleRunnable.java b/ngrinder-core/src/main/java/org/ngrinder/extension/OnControllerLifeCycleRunnable.java index ca523c33cf..b9e40d09aa 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/extension/OnControllerLifeCycleRunnable.java +++ b/ngrinder-core/src/main/java/org/ngrinder/extension/OnControllerLifeCycleRunnable.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.extension; @@ -17,9 +17,9 @@ /** * Plugin extension point which is executable when controller start and finish. - * + * * This plugin is necessary if you want to notify the controller start and end. - * + * * @author JunHo Yoon * @since 3.0 */ @@ -27,19 +27,19 @@ public interface OnControllerLifeCycleRunnable extends ExtensionPoint { /** * Callback method which will be invoked whenever Controller is started. - * - * + * + * * @param ip ip * @param version version */ - public void start(String ip, String version); + void start(String ip, String version); /** * Callback method which will be invoked whenever Controller is stopped. - * - * + * + * * @param ip ip * @param version version */ - public void finish(String ip, String version); + void finish(String ip, String version); } diff --git a/ngrinder-core/src/main/java/org/ngrinder/extension/OnLoginRunnable.java b/ngrinder-core/src/main/java/org/ngrinder/extension/OnLoginRunnable.java index 4afa3a3bbb..5268b2d245 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/extension/OnLoginRunnable.java +++ b/ngrinder-core/src/main/java/org/ngrinder/extension/OnLoginRunnable.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.extension; @@ -18,31 +18,31 @@ /** * Plugin extension point for the custom user authentication. - * + * * @author JunHo Yoon * @since 3.0 */ public interface OnLoginRunnable extends ExtensionPoint { /** * Load user by userId. - * + * * When the user having the given userId exists in the local DB, this method is not called by the nGrinder user * management system. However there are no user in local DB, nGrinder user management calls this to get to know who * it is. If you have LDAP or other system which can returns user id, email, cellphone number, please create the * {@link User} instance in this method using these info so that nGrinder save the user account into DB * automatically after {@link #validateUser(String, String, String, Object, Object)} is passed. - * + * * @param userId user id * @return User instance */ - public User loadUser(String userId); + User loadUser(String userId); /** * Validate user with userId and password. - * + * * encPass / encoder / salt are only when the password is saved in the local DB. When you implement this with remote * password validation system, you may only need userId and password which is input by an user in the nGrinder login page. - * + * * @param userId user providing id * @param password user providing password * @param encPass encrypted password stored in the DB @@ -50,13 +50,13 @@ public interface OnLoginRunnable extends ExtensionPoint { * @param salt salt of encoding * @return true is validated */ - public boolean validateUser(String userId, String password, String encPass, Object encoder, Object salt); + boolean validateUser(String userId, String password, String encPass, Object encoder, Object salt); /** * Save the given user. Usually dummy implementation is enough - * + * * @param user user to be saved. * @deprecated */ - public void saveUser(User user); + void saveUser(User user); } diff --git a/ngrinder-core/src/main/java/org/ngrinder/extension/OnPeriodicWorkingAgentCheckRunnable.java b/ngrinder-core/src/main/java/org/ngrinder/extension/OnPeriodicWorkingAgentCheckRunnable.java index b2c1e97272..185ac853fc 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/extension/OnPeriodicWorkingAgentCheckRunnable.java +++ b/ngrinder-core/src/main/java/org/ngrinder/extension/OnPeriodicWorkingAgentCheckRunnable.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.extension; @@ -21,8 +21,8 @@ /** * Plugin extension point which is executed whenever the controller periodically check currently * working agent status. - * - * + * + * * @author JunHo Yoon * @since 3.1.2. */ @@ -30,8 +30,8 @@ public interface OnPeriodicWorkingAgentCheckRunnable extends ExtensionPoint { /** * Check currently working agent status. - * + * * @param workingAgents working agent set */ - public void checkWorkingAgent(Set workingAgents); + void checkWorkingAgent(Set workingAgents); } diff --git a/ngrinder-core/src/main/java/org/ngrinder/extension/OnTestLifeCycleRunnable.java b/ngrinder-core/src/main/java/org/ngrinder/extension/OnTestLifeCycleRunnable.java index 9c3f2356f3..99ebd07863 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/extension/OnTestLifeCycleRunnable.java +++ b/ngrinder-core/src/main/java/org/ngrinder/extension/OnTestLifeCycleRunnable.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.extension; @@ -19,9 +19,9 @@ /** * Plugin extension point for {@link PerfTest} start and finish. - * + * * This plugin is necessary if you want to be notified whenever the test start and end. - * + * * @author JunHo Yoon * @since 3.0 */ @@ -29,21 +29,21 @@ public interface OnTestLifeCycleRunnable extends ExtensionPoint { /** * Callback method which will be invoked whenever {@link PerfTest} is started. - * + * * @param perfTest Performance Test * @param perfTestService perfTestService interface * @param version ngrinder version */ - public void start(PerfTest perfTest, IPerfTestService perfTestService, String version); + void start(PerfTest perfTest, IPerfTestService perfTestService, String version); /** * Callback method which will be invoked whenever {@link PerfTest} is finished. - * - * + * + * * @param perfTest Performance Test * @param stopReason stop reason * @param perfTestService perfTestService interface * @param version ngrinder version */ - public void finish(PerfTest perfTest, String stopReason, IPerfTestService perfTestService, String version); + void finish(PerfTest perfTest, String stopReason, IPerfTestService perfTestService, String version); } diff --git a/ngrinder-core/src/main/java/org/ngrinder/extension/OnTestSamplingRunnable.java b/ngrinder-core/src/main/java/org/ngrinder/extension/OnTestSamplingRunnable.java index d68085e9ca..8bda58e142 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/extension/OnTestSamplingRunnable.java +++ b/ngrinder-core/src/main/java/org/ngrinder/extension/OnTestSamplingRunnable.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.extension; @@ -21,9 +21,9 @@ /** * Plugin extension point for {@link PerfTest} control by examining each sampling statistics. - * + * * Ex) You can finish the test if the response byte is over than 1G bps. - * + * * @author JunHo Yoon * @since 3.0.3 */ @@ -32,33 +32,33 @@ public interface OnTestSamplingRunnable extends ExtensionPoint { /** * Callback method which will be invoked when the given {@link PerfTest} test sampling is * started. - * + * * @param singleConsole {@link ISingleConsole} * @param perfTest {@link PerfTest} * @param perfTestService {@link IPerfTestService} */ - public void startSampling(ISingleConsole singleConsole, PerfTest perfTest, IPerfTestService perfTestService); + void startSampling(ISingleConsole singleConsole, PerfTest perfTest, IPerfTestService perfTestService); /** * Callback method which will be invoked whenever test sampling is performed. - * + * * @param singleConsole {@link ISingleConsole} * @param perfTest {@link PerfTest} * @param perfTestService {@link IPerfTestService} * @param intervalStatistics sampling statistics on this time * @param cumulativeStatistics cumulative sampling statistics. */ - public void sampling(ISingleConsole singleConsole, PerfTest perfTest, IPerfTestService perfTestService, + void sampling(ISingleConsole singleConsole, PerfTest perfTest, IPerfTestService perfTestService, ImmutableStatisticsSet intervalStatistics, ImmutableStatisticsSet cumulativeStatistics); /** * Callback method which will be invoked when the given {@link PerfTest} test sampling is * finished. - * + * * @param singleConsole {@link ISingleConsole} * @param perfTest {@link PerfTest} * @param perfTestService {@link IPerfTestService} */ - public void endSampling(ISingleConsole singleConsole, PerfTest perfTest, IPerfTestService perfTestService); + void endSampling(ISingleConsole singleConsole, PerfTest perfTest, IPerfTestService perfTestService); } diff --git a/ngrinder-core/src/main/java/org/ngrinder/infra/AgentConfig.java b/ngrinder-core/src/main/java/org/ngrinder/infra/AgentConfig.java index 5052ff6c13..19a5c9e0f5 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/infra/AgentConfig.java +++ b/ngrinder-core/src/main/java/org/ngrinder/infra/AgentConfig.java @@ -60,10 +60,10 @@ public class AgentConfig implements AgentConstants, MonitorConstants, CommonCons private PropertiesWrapper commonProperties; private PropertiesWrapper internalProperties; - private PropertiesKeyMapper internalPropertyMapper = PropertiesKeyMapper.create("internal-properties.map"); - private PropertiesKeyMapper agentPropertyMapper = PropertiesKeyMapper.create("agent-properties.map"); - private PropertiesKeyMapper monitorPropertyMapper = PropertiesKeyMapper.create("monitor-properties.map"); - private PropertiesKeyMapper commonPropertyMapper = PropertiesKeyMapper.create("common-properties.map"); + private final PropertiesKeyMapper internalPropertyMapper = PropertiesKeyMapper.create("internal-properties.map"); + private final PropertiesKeyMapper agentPropertyMapper = PropertiesKeyMapper.create("agent-properties.map"); + private final PropertiesKeyMapper monitorPropertyMapper = PropertiesKeyMapper.create("monitor-properties.map"); + private final PropertiesKeyMapper commonPropertyMapper = PropertiesKeyMapper.create("common-properties.map"); /** * Initialize. @@ -79,6 +79,7 @@ public AgentConfig init() { return this; } + @SuppressWarnings("ResultOfMethodCallIgnored") private void copyDefaultConfigurationFiles() { checkNotNull(home); final File agentConfig = home.getFile("agent.conf"); @@ -372,7 +373,7 @@ public PropertiesWrapper getCommonProperties() { } public static class NullAgentConfig extends AgentConfig { - public int counter = 0; + public int counter; private int controllerPort = 0; public NullAgentConfig(int i) { @@ -397,7 +398,7 @@ public boolean isSilentMode() { @Override protected AgentHome resolveHome() { AgentHome resolveHome = super.resolveHome(); - File directory = new File(resolveHome.getDirectory(), "tmp_" + String.valueOf(counter)); + File directory = new File(resolveHome.getDirectory(), "tmp_" + counter); resolveHome = new AgentHome(directory); try { FileUtils.forceDeleteOnExit(directory); diff --git a/ngrinder-core/src/main/java/org/ngrinder/infra/AgentHome.java b/ngrinder-core/src/main/java/org/ngrinder/infra/AgentHome.java index 246935706c..3106373eae 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/infra/AgentHome.java +++ b/ngrinder-core/src/main/java/org/ngrinder/infra/AgentHome.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.infra; @@ -85,6 +85,7 @@ public File getDirectory() { * * @return agent native directory */ + @SuppressWarnings("unused") public File getNativeDirectory() { return mkDir(getFile("native")); } diff --git a/ngrinder-core/src/main/java/org/ngrinder/model/AgentInfo.java b/ngrinder-core/src/main/java/org/ngrinder/model/AgentInfo.java index 9faeee2598..6110561ca1 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/AgentInfo.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/AgentInfo.java @@ -34,7 +34,7 @@ * @author JunHo Yoon * @since 3.0 */ -@SuppressWarnings({"deprecation", "UnusedDeclaration", "JpaDataSourceORMInspection"}) +@SuppressWarnings({"UnusedDeclaration", "JpaDataSourceORMInspection"}) @Getter @Setter @ToString @@ -114,7 +114,7 @@ public void setHostName(String name) { } public boolean isApproved() { - return approved == null ? false : approved; + return approved != null && approved; } @JsonIgnore diff --git a/ngrinder-core/src/main/java/org/ngrinder/model/BaseEntity.java b/ngrinder-core/src/main/java/org/ngrinder/model/BaseEntity.java index 59ce9bd472..69f519003f 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/BaseEntity.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/BaseEntity.java @@ -43,7 +43,7 @@ public class BaseEntity implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", unique = true, nullable = false, insertable = true, updatable = false) + @Column(name = "id", unique = true, nullable = false, updatable = false) private Long id; @Override diff --git a/ngrinder-core/src/main/java/org/ngrinder/model/BaseModel.java b/ngrinder-core/src/main/java/org/ngrinder/model/BaseModel.java index 80b4c06e9c..1ec9e68cd5 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/BaseModel.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/BaseModel.java @@ -14,15 +14,11 @@ package org.ngrinder.model; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import org.hibernate.annotations.Index; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; -import javax.persistence.Column; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.MappedSuperclass; -import java.util.Date; +import java.time.Instant; +import javax.persistence.*; import lombok.Getter; import lombok.Setter; @@ -40,24 +36,25 @@ public class BaseModel extends BaseEntity { private static final long serialVersionUID = -3876339828833595694L; - @Column(name = "created_date", insertable = true, updatable = false) - private Date createdDate; + @Column(name = "created_at", updatable = false) + private Instant createdAt; @JsonSerialize(using = User.UserReferenceSerializer.class) @ManyToOne - @JoinColumn(name = "created_user", insertable = true, updatable = false) - @Index(name = "created_user_index") + @JoinColumn(name = "created_by", updatable = false) + @NotFound(action = NotFoundAction.IGNORE) - private User createdUser; + private User createdBy; + - @Column(name = "last_modified_date", insertable = true, updatable = true) - private Date lastModifiedDate; + @Column(name = "last_modified_at") + private Instant lastModifiedAt; @JsonSerialize(using = User.UserReferenceSerializer.class) @ManyToOne - @JoinColumn(name = "last_modified_user", insertable = true, updatable = true) - @Index(name = "last_modified_user_index") + @JoinColumn(name = "last_modified_By") + @NotFound(action = NotFoundAction.IGNORE) - private User lastModifiedUser; + private User lastModifiedBy; } diff --git a/ngrinder-core/src/main/java/org/ngrinder/model/IFileEntry.java b/ngrinder-core/src/main/java/org/ngrinder/model/IFileEntry.java index fc66f832d8..7ab865fde0 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/IFileEntry.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/IFileEntry.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.model; @@ -24,40 +24,40 @@ public interface IFileEntry { /** * Get the relative path of file. - * + * * @return relative path */ - public abstract String getPath(); + String getPath(); /** * Get the content. - * + * * @return content string */ - public abstract String getContent(); + String getContent(); /** * Get the encoding of content. - * + * * @return encoding */ - public abstract String getEncoding(); + String getEncoding(); /** * Get the create user. - * + * * @return user * @since 3.2 */ @SuppressWarnings("UnusedDeclaration") - public abstract User getCreatedUser(); + User getCreatedUser(); /** * Get the revision of the file entity. - * + * * @return revision * @since 3.2 */ - public abstract long getRevision(); + long getRevision(); } diff --git a/ngrinder-core/src/main/java/org/ngrinder/model/PerfTest.java b/ngrinder-core/src/main/java/org/ngrinder/model/PerfTest.java index 0ce74f48b2..26900dbf5c 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/PerfTest.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/PerfTest.java @@ -21,26 +21,27 @@ import net.grinder.common.GrinderProperties; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.hibernate.annotations.Index; import org.hibernate.annotations.SortNatural; import org.hibernate.annotations.Type; -import org.ngrinder.common.util.DateUtils; import javax.persistence.*; +import java.time.Instant; import java.util.ArrayList; -import java.util.Date; import java.util.List; import java.util.SortedSet; import static com.sun.jmx.mbeanserver.Util.cast; +import static java.util.Date.from; import static org.apache.commons.lang.ObjectUtils.defaultIfNull; import static org.ngrinder.common.util.AccessUtils.getSafe; +import static org.ngrinder.common.util.DateUtils.dateToString; +import static org.ngrinder.common.util.DateUtils.ms2Time; /** * Performance Test Entity. */ -@SuppressWarnings({"JpaDataSourceORMInspection", "UnusedDeclaration", "JpaAttributeTypeInspection"}) +@SuppressWarnings({"JpaDataSourceORMInspection", "UnusedDeclaration", "JpaAttributeTypeInspection", "DanglingJavadoc"}) @Getter @Setter @Entity @@ -67,8 +68,8 @@ public PerfTest() { * @param createdUser crested user. */ public PerfTest(User createdUser) { - this.setCreatedUser(createdUser); - this.setLastModifiedUser(createdUser); + this.setCreatedBy(createdUser); + this.setLastModifiedBy(createdUser); } @Cloneable @@ -94,16 +95,15 @@ public PerfTest(User createdUser) { /** the scheduled time of this test. */ @Column(name = "scheduled_time") - @Index(name = "scheduled_time_index") - private Date scheduledTime; + private Instant scheduledTime; /** the start time of this test. */ @Column(name = "start_time") - private Date startTime; + private Instant startTime; /** the finish time of this test. */ @Column(name = "finish_time") - private Date finishTime; + private Instant finishTime; /** * the target host to test. @@ -320,7 +320,7 @@ public void init() { @JsonIgnore public String getTestIdentifier() { - return "perftest_" + getId() + "_" + getLastModifiedUser().getUserId(); + return "perftest_" + getId() + "_" + getLastModifiedBy().getUserId(); } /** @@ -339,8 +339,8 @@ public String getDescription() { } @JsonIgnore - public String getLastModifiedDateToStr() { - return DateUtils.dateToString(getLastModifiedDate()); + public String getLastModifiedAtToStr() { + return dateToString(from(getLastModifiedAt())); } /** @@ -352,14 +352,14 @@ public String getLastModifiedDateToStr() { */ @JsonIgnore public List getTargetHostIP() { - List targetIPList = new ArrayList(); + List targetIPList = new ArrayList<>(); String[] hostsList = StringUtils.split(StringUtils.trimToEmpty(targetHosts), ","); for (String hosts : hostsList) { String[] addresses = StringUtils.split(hosts, ":"); if (addresses.length <= 2) { targetIPList.add(addresses[addresses.length - 1]); } else { - targetIPList.add(hosts.substring(hosts.indexOf(":") + 1, hosts.length())); + targetIPList.add(hosts.substring(hosts.indexOf(":") + 1)); } } return targetIPList; @@ -386,8 +386,8 @@ public boolean isStopRequest() { */ @JsonProperty("runtime") public String getRuntimeStr() { - long ms = (this.finishTime == null || this.startTime == null) ? 0 : this.finishTime.getTime() - this.startTime.getTime(); - return DateUtils.ms2Time(ms); + long runtimeSecond = (this.finishTime == null || this.startTime == null) ? 0 : this.finishTime.getEpochSecond() - this.startTime.getEpochSecond(); + return ms2Time(runtimeSecond * 1000); } @Override diff --git a/ngrinder-core/src/main/java/org/ngrinder/model/Permission.java b/ngrinder-core/src/main/java/org/ngrinder/model/Permission.java index 9320732575..f5c4c4c08c 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/Permission.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/Permission.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.model; @@ -37,6 +37,6 @@ public enum Permission { CHECK_SCRIPT_OF_OTHER, /** Validate script that other created. */ - VALIDATE_SCRIPT_OF_OTHER; + VALIDATE_SCRIPT_OF_OTHER } diff --git a/ngrinder-core/src/main/java/org/ngrinder/model/RampUp.java b/ngrinder-core/src/main/java/org/ngrinder/model/RampUp.java index 3abfd44e29..97b9421785 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/RampUp.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/RampUp.java @@ -27,7 +27,7 @@ public enum RampUp { * Thread Ramp Up */ THREAD("thread"); - private String messageKey; + private final String messageKey; RampUp(String messageKey) { this.messageKey = messageKey; diff --git a/ngrinder-core/src/main/java/org/ngrinder/model/Role.java b/ngrinder-core/src/main/java/org/ngrinder/model/Role.java index a9b9e929ca..4ad1cda22b 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/Role.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/Role.java @@ -42,20 +42,15 @@ public enum Role { */ public boolean hasPermission(Permission type) { switch (type) { - case GET_ALL_TESTS: - return true; - case DELETE_TEST_OF_OTHER: - return true; - case CHECK_SCRIPT_OF_OTHER: - return true; - case VALIDATE_SCRIPT_OF_OTHER: - return true; - case STOP_TEST_OF_OTHER: - return true; - case SWITCH_TO_ANYONE: - return true; - default: - return false; + case GET_ALL_TESTS: + case DELETE_TEST_OF_OTHER: + case CHECK_SCRIPT_OF_OTHER: + case VALIDATE_SCRIPT_OF_OTHER: + case STOP_TEST_OF_OTHER: + case SWITCH_TO_ANYONE: + return true; + default: + return false; } } }, @@ -73,15 +68,12 @@ public boolean hasPermission(Permission type) { public boolean hasPermission(Permission type) { switch (type) { case GET_ALL_TESTS: - return true; - case CHECK_SCRIPT_OF_OTHER: - return true; - case VALIDATE_SCRIPT_OF_OTHER: - return true; - case SWITCH_TO_ANYONE: - return true; - default: - return false; + case CHECK_SCRIPT_OF_OTHER: + case VALIDATE_SCRIPT_OF_OTHER: + case SWITCH_TO_ANYONE: + return true; + default: + return false; } } }, diff --git a/ngrinder-core/src/main/java/org/ngrinder/model/Status.java b/ngrinder-core/src/main/java/org/ngrinder/model/Status.java index c71a80e447..4e570b42a5 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/Status.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/Status.java @@ -90,7 +90,7 @@ public enum Status { /** * Detected Abnormal testing. */ - ABNORMAL_TESTING(StatusCategory.TESTING), + ABNORMAL_TESTING(StatusCategory.ABNORMAL_TESTING), /** * Test finished. */ @@ -191,17 +191,19 @@ public static Status[] getProcessingOrTestingTestStatus() { status.add(each); } } - return status.toArray(new Status[status.size()]); + return status.toArray(new Status[0]); } /** * Check this status is the working status. * * @param status status - * @return true if it's in {@link StatusCategory}'s PROCESSING or TESTING. + * @return true if it's in {@link StatusCategory}'s PROCESSING or TESTING or ABNORMAL_TESTING. */ private static boolean isWorkingStatus(Status status) { - return status.getCategory() == StatusCategory.PROGRESSING || status.getCategory() == StatusCategory.TESTING; + return status.getCategory() == StatusCategory.PROGRESSING || + status.getCategory() == StatusCategory.TESTING || + status.getCategory() == StatusCategory.ABNORMAL_TESTING; } /** @@ -216,7 +218,7 @@ public static Status[] getTestingTestStates() { status.add(each); } } - return status.toArray(new Status[status.size()]); + return status.toArray(new Status[0]); } /** @@ -224,6 +226,7 @@ public static Status[] getTestingTestStates() { * * @return message key */ + @SuppressWarnings("unused") public String getSpringMessageKey() { return "perftest.status." + name().toLowerCase(); } diff --git a/ngrinder-core/src/main/java/org/ngrinder/model/StatusCategory.java b/ngrinder-core/src/main/java/org/ngrinder/model/StatusCategory.java index 482bfe40e3..429ee41175 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/StatusCategory.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/StatusCategory.java @@ -32,6 +32,10 @@ public enum StatusCategory { * Testing. */ TESTING("green_anime.gif", true, false, false), + /** + * Abnormal testing. + */ + ABNORMAL_TESTING("yellow_anime.gif", false, false, false), /** * Finished normally. */ diff --git a/ngrinder-core/src/main/java/org/ngrinder/model/User.java b/ngrinder-core/src/main/java/org/ngrinder/model/User.java index 62792419e8..0a981002f3 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/User.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/User.java @@ -24,7 +24,6 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.apache.commons.lang.StringUtils; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Type; @@ -46,6 +45,7 @@ * @author Mavlarn * @since 3.0 */ +@SuppressWarnings("JpaDataSourceORMInspection") @Getter @Setter @Entity @@ -57,11 +57,11 @@ public class User extends BaseModel { private static final long serialVersionUID = 7398072895183814285L; @Column(name = "user_id", unique = true, nullable = false) - /** User Id */ + /* User Id */ private String userId; @Column(name = "user_name") - /** User Name e.g) Jone Dogh. */ + /* User Name e.g) Jone Dogh. */ private String userName; private String password; @@ -89,7 +89,7 @@ public class User extends BaseModel { private Boolean external; @Column(name = "authentication_provider_class") - /** Who provide the authentication */ + /* Who provide the authentication */ private String authProviderClass; @Transient @@ -197,15 +197,13 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } + User other = (User) obj; + if (userId == null) { - if (other.userId != null) { - return false; - } - } else if (!userId.equals(other.userId)) { - return false; + return other.userId == null; } - return true; + return userId.equals(other.userId); } public Boolean isEnabled() { diff --git a/ngrinder-core/src/main/java/org/ngrinder/monitor/MonitorContext.java b/ngrinder-core/src/main/java/org/ngrinder/monitor/MonitorContext.java index 93d835eefa..4a4778afd2 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/monitor/MonitorContext.java +++ b/ngrinder-core/src/main/java/org/ngrinder/monitor/MonitorContext.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.monitor; @@ -19,7 +19,7 @@ /** * Monitor context class, used to store the collectors of monitor. Currently, there is only system * data collector. - * + * * @author Mavlarn * @since 3.0 */ @@ -34,7 +34,7 @@ public static MonitorContext getInstance() { return INSTANCE; } - private Set dataCollectors = new HashSet(); + private Set dataCollectors = new HashSet<>(); public void setDataCollectors(Set dataCollectors) { this.dataCollectors = dataCollectors; diff --git a/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/MXBeanStorage.java b/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/MXBeanStorage.java index 7ed31d5340..c804012df0 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/MXBeanStorage.java +++ b/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/MXBeanStorage.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.monitor.agent; @@ -20,15 +20,15 @@ import java.util.concurrent.ConcurrentHashMap; /** - * + * * Used to store monitor MXBean in a map, with the domain name as the key. * * @author Mavlarn * @since 2.0 */ public final class MXBeanStorage { - private Map cachedMxBeans = new ConcurrentHashMap(); private static final MXBeanStorage INSTANCE = new MXBeanStorage(); + private final Map cachedMxBeans = new ConcurrentHashMap<>(); private MXBeanStorage() { } diff --git a/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/MonitorServer.java b/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/MonitorServer.java index f4f3795a10..4b503261cd 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/MonitorServer.java +++ b/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/MonitorServer.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.monitor.agent; @@ -65,7 +65,7 @@ public static MonitorServer getInstance() { */ public void init(AgentConfig agentConfig) throws IOException { this.agentConfig = agentConfig; - Set systemDataCollector = new HashSet(); + Set systemDataCollector = new HashSet<>(); systemDataCollector.add(SYSTEM); MonitorContext.getInstance().setDataCollectors(systemDataCollector); int port = agentConfig.getMonitorProperties().getPropertyInt(PROP_MONITOR_BINDING_PORT); diff --git a/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/RegisterMXBean.java b/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/RegisterMXBean.java index 10da4b5450..97c0780e60 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/RegisterMXBean.java +++ b/ngrinder-core/src/main/java/org/ngrinder/monitor/agent/RegisterMXBean.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.monitor.agent; @@ -54,6 +54,7 @@ public void addDefaultMXBean(MBeanServer mbeanServer) { LOG.info("Default MXBean Initialized."); } + @SuppressWarnings("SameParameterValue") void addMXBean(MBeanServer mbeanServer, String subDomainName, MXBean bean) { ObjectName objectName; try { diff --git a/ngrinder-core/src/main/java/org/ngrinder/monitor/domain/MonitorCollectionInfoDomain.java b/ngrinder-core/src/main/java/org/ngrinder/monitor/domain/MonitorCollectionInfoDomain.java index 975a4c60bf..d02b890ecf 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/monitor/domain/MonitorCollectionInfoDomain.java +++ b/ngrinder-core/src/main/java/org/ngrinder/monitor/domain/MonitorCollectionInfoDomain.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.monitor.domain; @@ -25,8 +25,8 @@ */ @Getter public class MonitorCollectionInfoDomain { - private ObjectName objectName; - private String attrName; + private final ObjectName objectName; + private final String attrName; /** * Constructor for the collection info. diff --git a/ngrinder-core/src/main/java/org/ngrinder/monitor/mxbean/SystemMonitoringData.java b/ngrinder-core/src/main/java/org/ngrinder/monitor/mxbean/SystemMonitoringData.java index 068221182a..758303f881 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/monitor/mxbean/SystemMonitoringData.java +++ b/ngrinder-core/src/main/java/org/ngrinder/monitor/mxbean/SystemMonitoringData.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.monitor.mxbean; @@ -22,18 +22,18 @@ import java.io.File; /** - * + * * MXBean implementation for monitoring system data. - * + * * @author Mavlarn * @since 2.0 */ public class SystemMonitoringData extends MXBean implements SystemMXBean { private static final long serialVersionUID = -3568524400212296536L; - private SystemInfo systemInfo; + private final SystemDataCollector agentSystemDataCollector = new SystemDataCollector(); - private SystemDataCollector agentSystemDataCollector = new SystemDataCollector(); + private SystemInfo systemInfo; @Override public DataCollector gainDataCollector(File agentHome) { diff --git a/ngrinder-core/src/main/java/org/ngrinder/monitor/mxbean/core/SystemMXBean.java b/ngrinder-core/src/main/java/org/ngrinder/monitor/mxbean/core/SystemMXBean.java index e0b6849385..a14f63f718 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/monitor/mxbean/core/SystemMXBean.java +++ b/ngrinder-core/src/main/java/org/ngrinder/monitor/mxbean/core/SystemMXBean.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,24 +9,24 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.monitor.mxbean.core; import org.ngrinder.monitor.share.domain.SystemInfo; /** - * + * * MXBean interface for system data monitoring. * * @author Mavlarn * @since 2.0 */ public interface SystemMXBean { - + /** * get system data. * @return SystemInfo of current time */ - public SystemInfo getSystemInfo(); + SystemInfo getSystemInfo(); } diff --git a/ngrinder-core/src/main/java/org/ngrinder/monitor/share/domain/MBeanClient.java b/ngrinder-core/src/main/java/org/ngrinder/monitor/share/domain/MBeanClient.java index 46667da0b3..9f23476fee 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/monitor/share/domain/MBeanClient.java +++ b/ngrinder-core/src/main/java/org/ngrinder/monitor/share/domain/MBeanClient.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.monitor.share.domain; @@ -40,7 +40,7 @@ public class MBeanClient { private static final String JMX_URI = "/jndi/rmi://%s:%s/jmxrmi"; - private JMXServiceURL jmxUrl = null; + private final JMXServiceURL jmxUrl; private volatile boolean connected = false; @@ -56,7 +56,8 @@ public class MBeanClient { * @param timeout the connection timeout og mbean client. * @throws IOException wraps JMX MalformedURLException exception */ - public MBeanClient(String hostName, int port, int timeout) throws IOException { + @SuppressWarnings("unused") + public MBeanClient(String hostName, int port, int timeout) throws IOException { this(hostName, port); this.timeout = timeout; } @@ -79,7 +80,7 @@ public void connect() { try { connectClient(); } catch (Exception e) { - LOGGER.info("Timeout while connecting to {}:{} monitor : {}", jmxUrl.getHost(), jmxUrl.getPort()); + LOGGER.error("Timeout while connecting to {}:{} monitor : {}", jmxUrl.getHost(), jmxUrl.getPort(), e.getMessage()); } } @@ -126,11 +127,7 @@ private void connectClient() throws IOException, TimeoutException { private JMXConnector connectWithTimeout(final JMXServiceURL jmxUrl, int timeout) throws NGrinderRuntimeException, TimeoutException { try { ExecutorService executor = Executors.newSingleThreadExecutor(); - Future future = executor.submit(new Callable() { - public JMXConnector call() throws IOException { - return JMXConnectorFactory.connect(jmxUrl); - } - }); + Future future = executor.submit(() -> JMXConnectorFactory.connect(jmxUrl)); return future.get(timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { diff --git a/ngrinder-core/src/main/java/org/ngrinder/service/IConfig.java b/ngrinder-core/src/main/java/org/ngrinder/service/IConfig.java index 8cd144b837..85dcdb12cf 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/service/IConfig.java +++ b/ngrinder-core/src/main/java/org/ngrinder/service/IConfig.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.service; @@ -28,14 +28,14 @@ public interface IConfig { * * @return true if test mode */ - public abstract boolean isDevMode(); + boolean isDevMode(); /** * Check if it's the security enabled mode. * * @return true if security is enabled. */ - public abstract boolean isSecurityEnabled(); + boolean isSecurityEnabled(); /** * Check if plugin support is enabled. The reason why we need this configuration is that it @@ -43,21 +43,21 @@ public interface IConfig { * * @return true if plugin is supported. */ - public abstract boolean isPluginSupported(); + boolean isPluginSupported(); /** * Get the controller properties. * * @return {@link PropertiesWrapper} which is loaded from system.conf. */ - public abstract PropertiesWrapper getControllerProperties(); + PropertiesWrapper getControllerProperties(); /** * Get the cluster properties. * * @return {@link PropertiesWrapper} which is loaded from system.conf. */ - public abstract PropertiesWrapper getClusterProperties(); + PropertiesWrapper getClusterProperties(); /** * Get the system properties. @@ -65,6 +65,6 @@ public interface IConfig { * @return {@link PropertiesWrapper} which is loaded from system.conf. * @deprecated use #getControllerProperties() instead */ - public abstract PropertiesWrapper getSystemProperties(); + PropertiesWrapper getSystemProperties(); -} \ No newline at end of file +} diff --git a/ngrinder-core/src/main/java/org/ngrinder/service/IPerfTestService.java b/ngrinder-core/src/main/java/org/ngrinder/service/IPerfTestService.java index 3f76ee42dd..e2220c69bd 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/service/IPerfTestService.java +++ b/ngrinder-core/src/main/java/org/ngrinder/service/IPerfTestService.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.service; @@ -23,7 +23,7 @@ /** * {@link PerfTest} service interface. This is visible from plugin. - * + * * @author JunHo Yoon * @since 3.0 */ @@ -31,162 +31,162 @@ public interface IPerfTestService { /** * get test detail. - * + * * @param user current operation user. * @param id test id * @return perftest {@link PerfTest} */ - public abstract PerfTest getOne(User user, Long id); + PerfTest getOne(User user, Long id); /** * Get {@link PerfTest} list created within the given time frame. - * + * * @param start start time. * @param end end time. * @return found {@link PerfTest} list */ - public abstract List getAll(Date start, Date end); + List getAll(Date start, Date end); /** * Get {@link PerfTest} list created within the given time frame and region name. - * + * * @param start start time. * @param end end time. * @param region region * @return found {@link PerfTest} list */ - public abstract List getAll(Date start, Date end, String region); + List getAll(Date start, Date end, String region); /** * Get {@link PerfTest} list of some IDs. - * + * * @param user current operation user * @param ids test IDs, which is in format: "1,3,6,11" * @return perftest list test list of those IDs */ - public abstract List getAll(User user, Long[] ids); + List getAll(User user, Long[] ids); /** * Get PerfTest count which have given status. - * + * * @param user user who created test. null to retrieve all * @param statuses status set * @return the count */ - public abstract long count(User user, Status[] statuses); + long count(User user, Status[] statuses); /** * Get {@link PerfTest} list which have give state. - * + * * @param user user who created {@link PerfTest}. if null, retrieve all test * @param statuses set of {@link Status} * @return found {@link PerfTest} list. */ - public abstract List getAll(User user, Status[] statuses); + List getAll(User user, Status[] statuses); /** * Save {@link PerfTest}. This function includes logic the updating script revision when it's * READY status. - * + * * @param user user * @param perfTest {@link PerfTest} instance to be saved. * @return Saved {@link PerfTest} */ - public abstract PerfTest save(User user, PerfTest perfTest); + PerfTest save(User user, PerfTest perfTest); /** * Get PerfTest by testId. - * + * * @param testId PerfTest id * @return found {@link PerfTest}, null otherwise */ - public abstract PerfTest getOne(Long testId); + PerfTest getOne(Long testId); /** * Get PerfTest with tag infos by testId. - * + * * @param testId PerfTest id * @return found {@link PerfTest}, null otherwise */ - public abstract PerfTest getOneWithTag(Long testId); + PerfTest getOneWithTag(Long testId); /** * Get currently testing PerfTest. - * + * * @return found {@link PerfTest} list */ - public abstract List getAllTesting(); + List getAllTesting(); /** * Get PerfTest Directory in which the distributed file is stored. - * + * * @param perfTest pefTest from which distribution directory calculated * @return path on in files are saved. */ - public abstract File getDistributionPath(PerfTest perfTest); + File getDistributionPath(PerfTest perfTest); /** * Get perf test base directory. - * + * * @param perfTest perfTest * @return directory prefTest base path */ - public abstract File getPerfTestDirectory(PerfTest perfTest); + File getPerfTestDirectory(PerfTest perfTest); /** * Get all perf test list. - * + * * Note : This is only for test - * + * * @return all {@link PerfTest} list - * + * */ - public abstract List getAllPerfTest(); + List getAllPerfTest(); /** * Mark Stop on {@link PerfTest}. - * + * * @param user user * @param id perftest id */ - public abstract void stop(User user, Long id); + void stop(User user, Long id); /** * Return stop requested test. - * + * * @return stop requested perf test */ - public abstract List getAllStopRequested(); + List getAllStopRequested(); /** * Add comment on {@link PerfTest}. - * + * * @param user current operated user * @param testId perftest id * @param testComment comment * @param tagString tagString */ - public abstract void addCommentOn(User user, Long testId, String testComment, String tagString); + void addCommentOn(User user, Long testId, String testComment, String tagString); /** * Save performance test with given status. - * + * * This method is only used for changing {@link Status} - * + * * @param perfTest {@link PerfTest} instance which will be saved. * @param status Status to be assigned * @param message progress message * @return saved {@link PerfTest} */ - public abstract PerfTest markStatusAndProgress(PerfTest perfTest, Status status, String message); + PerfTest markStatusAndProgress(PerfTest perfTest, Status status, String message); /** * Get performance test statistic path. - * + * * @param perfTest perftest * @return statistic path */ @SuppressWarnings("UnusedDeclaration") - public abstract File getStatisticPath(PerfTest perfTest); + File getStatisticPath(PerfTest perfTest); -} \ No newline at end of file +} diff --git a/ngrinder-core/src/main/java/org/ngrinder/service/IScriptValidationService.java b/ngrinder-core/src/main/java/org/ngrinder/service/IScriptValidationService.java index fb3dbbb0a4..44fb35c4c8 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/service/IScriptValidationService.java +++ b/ngrinder-core/src/main/java/org/ngrinder/service/IScriptValidationService.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.service; @@ -38,5 +38,5 @@ public interface IScriptValidationService { * @param hostString HOSTNAME:IP,... pairs for host manipulation * @return validation result. */ - public abstract String validate(User user, IFileEntry scriptEntry, boolean useScriptInSVN, String hostString); -} \ No newline at end of file + String validate(User user, IFileEntry scriptEntry, boolean useScriptInSVN, String hostString); +} diff --git a/ngrinder-core/src/main/java/org/ngrinder/service/ISingleConsole.java b/ngrinder-core/src/main/java/org/ngrinder/service/ISingleConsole.java index d58e106816..bcad962fb3 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/service/ISingleConsole.java +++ b/ngrinder-core/src/main/java/org/ngrinder/service/ISingleConsole.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.service; @@ -22,78 +22,79 @@ /** * {@link SingleConsole} interface for plugin use. - * + * */ +@SuppressWarnings("JavadocReference") public interface ISingleConsole { /** * Mark the cancel status. */ - public abstract void cancel(); + void cancel(); /** * Get current running time in ms. - * + * * @return running time */ - public abstract long getCurrentRunningTime(); + long getCurrentRunningTime(); /** * Get the current total execution count(test count + error count). - * + * * @return current total execution count */ - public abstract long getCurrentExecutionCount(); + long getCurrentExecutionCount(); /** * Get statistics index map used. - * + * * @return {@link StatisticsIndexMap} */ - public StatisticsIndexMap getStatisticsIndexMap(); + StatisticsIndexMap getStatisticsIndexMap(); /** * Get report path. - * + * * @return report path */ - public abstract File getReportPath(); + File getReportPath(); /** * Get peak TPS. - * + * * @return peak tps */ - public abstract double getPeakTpsForGraph(); + double getPeakTpsForGraph(); /** * Get the count of current running threads. - * + * * @return running threads. */ - public abstract int getRunningThread(); + int getRunningThread(); /** * Get the count of current running processes. - * + * * @return running processes */ - public abstract int getRunningProcess(); + int getRunningProcess(); /** * Get the all agents attached in this processes. - * + * * @return {@link AgentIdentity} list * @since 3.1.2 */ - public abstract List getAllAttachedAgents(); + List getAllAttachedAgents(); /** * Return the assigned console port. - * + * * @return console port */ - public abstract int getConsolePort(); + int getConsolePort(); /** @@ -101,5 +102,5 @@ public interface ISingleConsole { * * @return grinder properties. null if the test is not started. */ - public abstract GrinderProperties getGrinderProperties(); + GrinderProperties getGrinderProperties(); } diff --git a/ngrinder-core/src/main/java/org/ngrinder/service/IUserService.java b/ngrinder-core/src/main/java/org/ngrinder/service/IUserService.java index 46f95ae2ca..21cdc517f4 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/service/IUserService.java +++ b/ngrinder-core/src/main/java/org/ngrinder/service/IUserService.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.service; @@ -28,7 +28,7 @@ public interface IUserService { * * @param user user */ - public abstract void encodePassword(User user); + void encodePassword(User user); /** * Get user by user id. @@ -37,7 +37,7 @@ public interface IUserService { * @return user * @since 3.3 */ - public abstract User getOne(String userId); + User getOne(String userId); /** @@ -47,7 +47,7 @@ public interface IUserService { * @return result * @since 3.3 */ - public User saveWithoutPasswordEncoding(User user); + User saveWithoutPasswordEncoding(User user); /** @@ -56,7 +56,7 @@ public interface IUserService { * @param user include id, userID, fullName, role, password. * @return result */ - public abstract User save(User user); + User save(User user); /** @@ -67,6 +67,6 @@ public interface IUserService { * @param user include id, userID, fullName, role, password. * @return result */ - public abstract User createUser(User user); + User createUser(User user); -} \ No newline at end of file +} diff --git a/ngrinder-core/src/test/java/net/grinder/AgentControllerTest.java b/ngrinder-core/src/test/java/net/grinder/AgentControllerTest.java index 265aa3b562..56760c3ece 100644 --- a/ngrinder-core/src/test/java/net/grinder/AgentControllerTest.java +++ b/ngrinder-core/src/test/java/net/grinder/AgentControllerTest.java @@ -32,7 +32,7 @@ import static net.grinder.StopReason.SCRIPT_ERROR; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; public class AgentControllerTest extends AbstractMultiGrinderTestBase { diff --git a/ngrinder-core/src/test/java/net/grinder/SingleConsoleTest.java b/ngrinder-core/src/test/java/net/grinder/SingleConsoleTest.java index 01f03a935e..a4a9fff3dd 100644 --- a/ngrinder-core/src/test/java/net/grinder/SingleConsoleTest.java +++ b/ngrinder-core/src/test/java/net/grinder/SingleConsoleTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder; @@ -27,11 +27,12 @@ import java.util.*; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.ngrinder.common.util.NoOp.noOp; public class SingleConsoleTest { double errorCount = 0; @@ -42,18 +43,10 @@ public class SingleConsoleTest { * @return a free port number on localhost, or -1 if unable to find a free port */ public int getFreePort() { - ServerSocket socket = null; - try { - socket = new ServerSocket(0); + try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } catch (IOException e) { - } finally { - if (socket != null) { - try { - socket.close(); - } catch (IOException e) { - } - } + noOp(); } return -1; } diff --git a/ngrinder-core/src/test/java/net/grinder/engine/agent/AgentDaemonTest.java b/ngrinder-core/src/test/java/net/grinder/engine/agent/AgentDaemonTest.java index dffaee5f97..cb6de02327 100644 --- a/ngrinder-core/src/test/java/net/grinder/engine/agent/AgentDaemonTest.java +++ b/ngrinder-core/src/test/java/net/grinder/engine/agent/AgentDaemonTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,12 +9,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.engine.agent; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import net.grinder.AgentDaemon; import net.grinder.SingleConsole; import net.grinder.util.thread.Condition; diff --git a/ngrinder-core/src/test/java/net/grinder/engine/agent/PropertyBuilderTest.java b/ngrinder-core/src/test/java/net/grinder/engine/agent/PropertyBuilderTest.java index b500b8a4ab..2301086378 100644 --- a/ngrinder-core/src/test/java/net/grinder/engine/agent/PropertyBuilderTest.java +++ b/ngrinder-core/src/test/java/net/grinder/engine/agent/PropertyBuilderTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.engine.agent; @@ -22,7 +22,7 @@ import java.io.File; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; import static org.ngrinder.common.constants.GrinderConstants.GRINDER_SECURITY_LEVEL_NORMAL; @@ -32,17 +32,17 @@ public void testPropertyBuilder() throws DirectoryException { System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparator + new File("./native_lib").getAbsolutePath()); - PropertyBuilder propertyBuilder = createPropertyBuilder("www.samples.com,:127.0.0.1"); - assertTrue(propertyBuilder.rebaseHostString("www.samples.com,:127.0.0.1") - .matches("www.samples.com:.*,:127.0.0.1")); - assertThat(propertyBuilder.rebaseHostString("www.samples.com:74.125.128.99"), - is("www.samples.com:74.125.128.99")); + PropertyBuilder propertyBuilder = createPropertyBuilder("www.sample.com,:127.0.0.1"); + assertTrue(propertyBuilder.rebaseHostString("www.sample.com,:127.0.0.1") + .matches("www.sample.com:.*,:127.0.0.1")); + assertThat(propertyBuilder.rebaseHostString("www.sample.com:74.125.128.99"), + is("www.sample.com:74.125.128.99")); assertThat(propertyBuilder.rebaseHostString(":127.0.0.1"), is(":127.0.0.1")); } @Test public void testDnsServerResolver() throws DirectoryException { - PropertyBuilder propertyBuilder = createPropertyBuilder("www.samples.com,:127.0.0.1"); + PropertyBuilder propertyBuilder = createPropertyBuilder("www.sample.com,:127.0.0.1"); StringBuilder builder = new StringBuilder(); propertyBuilder.addDnsIP(builder); assertThat(builder.toString(), containsString("ngrinder.dns.ip=")); @@ -54,7 +54,7 @@ public void testPropertyBuilderMemSize() throws DirectoryException { System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparator + new File("./native_lib").getAbsolutePath()); - PropertyBuilder propertyBuilder = createPropertyBuilder("www.samples.com,:127.0.0.1"); + PropertyBuilder propertyBuilder = createPropertyBuilder("www.sample.com,:127.0.0.1"); propertyBuilder.addProperties("grinder.processes", "10"); String buildJVMArgument = propertyBuilder.buildJVMArgument(); assertThat(buildJVMArgument, containsString("-Xmx")); diff --git a/ngrinder-core/src/test/java/net/grinder/engine/agent/SingleConsoleThreadTest.java b/ngrinder-core/src/test/java/net/grinder/engine/agent/SingleConsoleThreadTest.java index 3b8cbe0cb2..b369387fc6 100644 --- a/ngrinder-core/src/test/java/net/grinder/engine/agent/SingleConsoleThreadTest.java +++ b/ngrinder-core/src/test/java/net/grinder/engine/agent/SingleConsoleThreadTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.engine.agent; @@ -23,7 +23,7 @@ import org.ngrinder.AbstractMultiGrinderTestBase; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class SingleConsoleThreadTest extends AbstractMultiGrinderTestBase { diff --git a/ngrinder-core/src/test/java/net/grinder/util/LogCompressUtilTest.java b/ngrinder-core/src/test/java/net/grinder/util/LogCompressUtilTest.java index aa5169cfa4..a0ee26fadd 100644 --- a/ngrinder-core/src/test/java/net/grinder/util/LogCompressUtilTest.java +++ b/ngrinder-core/src/test/java/net/grinder/util/LogCompressUtilTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package net.grinder.util; @@ -21,7 +21,7 @@ import java.nio.charset.Charset; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class LogCompressUtilTest { @Test diff --git a/ngrinder-core/src/test/java/net/grinder/util/NetworkUtilTest.java b/ngrinder-core/src/test/java/net/grinder/util/NetworkUtilTest.java index da332e5fd0..ab757abfba 100644 --- a/ngrinder-core/src/test/java/net/grinder/util/NetworkUtilTest.java +++ b/ngrinder-core/src/test/java/net/grinder/util/NetworkUtilTest.java @@ -20,7 +20,7 @@ import java.net.UnknownHostException; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class NetworkUtilTest { diff --git a/ngrinder-core/src/test/java/org/ngrinder/AbstractMultiGrinderTestBase.java b/ngrinder-core/src/test/java/org/ngrinder/AbstractMultiGrinderTestBase.java index 100da95ef0..da535f72ad 100644 --- a/ngrinder-core/src/test/java/org/ngrinder/AbstractMultiGrinderTestBase.java +++ b/ngrinder-core/src/test/java/org/ngrinder/AbstractMultiGrinderTestBase.java @@ -30,7 +30,7 @@ import java.util.Set; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; abstract public class AbstractMultiGrinderTestBase { public AgentConfig.NullAgentConfig agentConfig1; diff --git a/ngrinder-core/src/test/java/org/ngrinder/NGrinderAgentStarterTest.java b/ngrinder-core/src/test/java/org/ngrinder/NGrinderAgentStarterTest.java index 3e50f74f42..4ad2ce1a54 100644 --- a/ngrinder-core/src/test/java/org/ngrinder/NGrinderAgentStarterTest.java +++ b/ngrinder-core/src/test/java/org/ngrinder/NGrinderAgentStarterTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder; @@ -19,7 +19,7 @@ import org.ngrinder.infra.AgentConfig; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; public class NGrinderAgentStarterTest { diff --git a/ngrinder-core/src/test/java/org/ngrinder/common/util/CollectionUtilsTest.java b/ngrinder-core/src/test/java/org/ngrinder/common/util/CollectionUtilsTest.java index e64e3ae6ad..c616efcf3b 100644 --- a/ngrinder-core/src/test/java/org/ngrinder/common/util/CollectionUtilsTest.java +++ b/ngrinder-core/src/test/java/org/ngrinder/common/util/CollectionUtilsTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,11 +9,11 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; import static org.hamcrest.Matchers.is; diff --git a/ngrinder-core/src/test/java/org/ngrinder/common/util/DateUtilsTest.java b/ngrinder-core/src/test/java/org/ngrinder/common/util/DateUtilsTest.java index 121d1b3b64..c7db0dafcf 100644 --- a/ngrinder-core/src/test/java/org/ngrinder/common/util/DateUtilsTest.java +++ b/ngrinder-core/src/test/java/org/ngrinder/common/util/DateUtilsTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,13 +9,13 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; import java.text.ParseException; @@ -27,7 +27,7 @@ /** * Class description. - * + * * @author Mavlarn * @since */ @@ -90,7 +90,7 @@ public void testGetFilteredTimeZoneMap() { /** * Test method for {@link DateUtils#toSimpleDate(java.lang.String)}. - * + * * @throws ParseException */ @Test @@ -102,7 +102,7 @@ public void testToSimpleDate() throws ParseException { /** * Test method for {@link DateUtils#toDate(java.lang.String)}. - * + * * @throws ParseException */ @Test diff --git a/ngrinder-core/src/test/java/org/ngrinder/common/util/PropertiesWrapperTest.java b/ngrinder-core/src/test/java/org/ngrinder/common/util/PropertiesWrapperTest.java index 20296700bb..7adc8cc615 100644 --- a/ngrinder-core/src/test/java/org/ngrinder/common/util/PropertiesWrapperTest.java +++ b/ngrinder-core/src/test/java/org/ngrinder/common/util/PropertiesWrapperTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; @@ -18,7 +18,7 @@ import java.util.Properties; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; /** diff --git a/ngrinder-core/src/test/java/org/ngrinder/common/util/ReflectionUtilTest.java b/ngrinder-core/src/test/java/org/ngrinder/common/util/ReflectionUtilTest.java index a7ab70f7d4..03ef70552a 100644 --- a/ngrinder-core/src/test/java/org/ngrinder/common/util/ReflectionUtilTest.java +++ b/ngrinder-core/src/test/java/org/ngrinder/common/util/ReflectionUtilTest.java @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -9,7 +9,7 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ngrinder.common.util; @@ -22,11 +22,11 @@ import java.util.List; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * Class description. - * + * * @author Mavlarn * @since */ diff --git a/ngrinder-core/src/test/java/org/ngrinder/model/PerfTestModelTest.java b/ngrinder-core/src/test/java/org/ngrinder/model/PerfTestModelTest.java index 32ce075650..dcb7800070 100644 --- a/ngrinder-core/src/test/java/org/ngrinder/model/PerfTestModelTest.java +++ b/ngrinder-core/src/test/java/org/ngrinder/model/PerfTestModelTest.java @@ -4,7 +4,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * PerfTest test diff --git a/ngrinder-core/src/test/java/org/ngrinder/monitor/collector/MonitorCollectorTest.java b/ngrinder-core/src/test/java/org/ngrinder/monitor/collector/MonitorCollectorTest.java index ede3fff9af..059afdf2fa 100644 --- a/ngrinder-core/src/test/java/org/ngrinder/monitor/collector/MonitorCollectorTest.java +++ b/ngrinder-core/src/test/java/org/ngrinder/monitor/collector/MonitorCollectorTest.java @@ -5,7 +5,7 @@ import org.ngrinder.monitor.share.domain.SystemInfo; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.spy; import static org.ngrinder.common.util.ThreadUtils.sleep; diff --git a/ngrinder-frontend/build.gradle b/ngrinder-frontend/build.gradle index b47a993dde..7933219052 100644 --- a/ngrinder-frontend/build.gradle +++ b/ngrinder-frontend/build.gradle @@ -1,15 +1,15 @@ plugins { - id 'com.github.node-gradle.node' version '2.2.2' + id "com.github.node-gradle.node" version "2.2.2" } node { - version = '12.16.2' + version = "12.16.2" // Enabled the automatic download. False is the default (for now). download = true } -task webpack(dependsOn: 'npmInstall', type: NodeTask) { - script = file('node_modules/webpack/bin/webpack.js') +task webpack(dependsOn: "npmInstall", type: NodeTask) { + script = file("node_modules/webpack/bin/webpack.js") if (profile) { args = ["--$profile"] } diff --git a/ngrinder-frontend/package.json b/ngrinder-frontend/package.json index d6baba50ff..0fe2f4745c 100644 --- a/ngrinder-frontend/package.json +++ b/ngrinder-frontend/package.json @@ -1,6 +1,6 @@ { "name": "ngrinder", - "version": "3.5.2", + "version": "3.5.3", "description": "ngrinder GUI", "private": true, "repository": { @@ -42,10 +42,12 @@ "moment-timezone": "^0.5.25", "numeral": "^2.0.6", "popper.js": "^1.15.0", + "dateformat": "^3.0.3", "promise-retry": "^1.1.1", "q": "^1.4.1", "retry-axios": "^0.3.2", "splitpanes": "^2.1.1", + "vuejs-datepicker": "^1.6.2", "vee-validate": "^2.2.0", "vue": "^2.6.10", "vue-authenticate": "^1.3.4", diff --git a/ngrinder-frontend/src/js/components/Base.vue b/ngrinder-frontend/src/js/components/Base.vue index 48f2111895..99a5659e78 100644 --- a/ngrinder-frontend/src/js/components/Base.vue +++ b/ngrinder-frontend/src/js/components/Base.vue @@ -225,8 +225,8 @@ .control-group.error { input, select, .input-group-text { - color: @error-color; - border-color: @error-color; + color: @error-color !important; + border-color: @error-color !important; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); &.input-group-text { diff --git a/ngrinder-frontend/src/js/components/perftest/detail/Config.vue b/ngrinder-frontend/src/js/components/perftest/detail/Config.vue index 97d24151a8..861c5eeec6 100644 --- a/ngrinder-frontend/src/js/components/perftest/detail/Config.vue +++ b/ngrinder-frontend/src/js/components/perftest/detail/Config.vue @@ -577,7 +577,7 @@ showScript() { let showScriptUrl = `${this.contextPath}/script/detail/${this.test.config.scriptName}?r=${this.test.config.scriptRevision}`; if (this.isAdmin || this.isSuperUser) { - showScriptUrl += `&ownerId=${this.test.createdUser.userId}`; + showScriptUrl += `&ownerId=${this.test.createdBy.userId}`; } const openedWindow = window.open(showScriptUrl, 'scriptSource'); openedWindow.focus(); diff --git a/ngrinder-frontend/src/js/components/perftest/detail/Detail.vue b/ngrinder-frontend/src/js/components/perftest/detail/Detail.vue index 580dc99800..8d34cc4b53 100644 --- a/ngrinder-frontend/src/js/components/perftest/detail/Detail.vue +++ b/ngrinder-frontend/src/js/components/perftest/detail/Detail.vue @@ -38,7 +38,7 @@ :src="`${contextPath}${perftestStatus.iconPath}`"/>
-
+