diff --git a/build.gradle b/build.gradle index 28a4f3a73d..a3bc77090c 100644 --- a/build.gradle +++ b/build.gradle @@ -29,7 +29,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" diff --git a/ngrinder-controller/build.gradle b/ngrinder-controller/build.gradle index 6717b58464..e4a9ea4868 100644 --- a/ngrinder-controller/build.gradle +++ b/ngrinder-controller/build.gradle @@ -75,17 +75,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-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 3e1927cc57..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 @@ -74,7 +74,6 @@ 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; @@ -528,7 +527,7 @@ public void update(Map getLeftPanelEntries(String feedURL) { return getPanelEntries(feedURL, PANEL_ENTRY_SIZE, false); @@ -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/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 163ae96ac3..dc78f53502 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 @@ -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/SecurityConfig.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/config/SecurityConfig.java index 9968b742c6..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 @@ -179,7 +179,6 @@ protected void configure(HttpSecurity http) throws Exception { /** * 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/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 751e3b803f..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,6 +48,7 @@ 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) { @@ -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..0cdaa3f5b6 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 @@ -13,6 +13,7 @@ * */ public class ApplicationPreparedListener implements ApplicationListener { + @SuppressWarnings("NullableProblems") @Override public void onApplicationEvent(ApplicationPreparedEvent event) { removeCacheProviderExceptCaffeineCacheProvider(); 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/WebhookActivation.java b/ngrinder-controller/src/main/java/org/ngrinder/infra/webhook/model/WebhookActivation.java index c28e9821ab..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 @@ -36,6 +36,7 @@ * * @since 3.5.2 */ +@SuppressWarnings("JpaDataSourceORMInspection") @Getter @Setter @Entity 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 c28f7f9583..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 @@ -36,6 +36,7 @@ * * @since 3.5.2 */ +@SuppressWarnings("JpaDataSourceORMInspection") @Getter @Setter @Entity 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 d869dadf4b..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 @@ -44,9 +44,9 @@ 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) { 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/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/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 83afc09276..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. * @@ -476,7 +473,6 @@ private String getStatusMessage(PerfTest perfTest) { 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 a93c5d5ac6..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,6 +200,7 @@ 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)) { 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 f81eb1fd09..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 @@ -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,6 +70,7 @@ 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 findAllByCreatedAtAndRegion(Date start, Date end, String region); 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 c55ddf2960..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 @@ -13,10 +13,6 @@ */ 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; 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 2d6db85927..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 @@ -13,10 +13,6 @@ */ 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; 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 a88c5cb501..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 @@ -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; @@ -57,6 +56,7 @@ 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; @@ -220,7 +220,7 @@ public void doTest(final PerfTest perfTest) { } catch (SingleConsoleCancellationException ex) { // In case of error, mark the occurs error on perftest. LOG.error(format(perfTest, "Error while preparing a single console : {} ", ex.getMessage())); - doCancel(perfTest, singleConsole); + doCancel(perfTest, requireNonNull(singleConsole)); notifyFinish(perfTest, StopReason.CANCEL_BY_USER); } catch (Exception ex) { // In case of error, mark the occurs error on perftest. @@ -330,6 +330,7 @@ public void distributed(String fileName) { perfTestService.markProgress(perfTest, " - " + fileName); } + @SuppressWarnings("ConstantConditions") @Override public boolean start(File dir, boolean safe) { if (safe) { @@ -399,14 +400,12 @@ 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) { - PerfTest fetchedPerftest = perfTestService.getOne(perfTest.getId()); - if (fetchedPerftest.getStatus().isStoppable()) { - perfTestService.markAbnormalTermination(perfTest, stopReason); - LOG.error(format(perfTest, "Abnormal test due to {}", stopReason.name())); - } + + singleConsole.addListener(stopReason -> { + PerfTest fetchedPerftest = perfTestService.getOne(perfTest.getId()); + if (fetchedPerftest.getStatus().isStoppable()) { + perfTestService.markAbnormalTermination(perfTest, stopReason); + LOG.error(format(perfTest, "Abnormal test due to {}", stopReason.name())); } }); 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 0943699956..9954afe325 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,8 +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; @@ -100,6 +101,7 @@ * * @since 3.0 */ +@SuppressWarnings({"ResultOfMethodCallIgnored", "BooleanMethodIsAlwaysInverted", "UnusedReturnValue", "SameParameterValue", "ConstantConditions"}) @RequiredArgsConstructor public class PerfTestService extends AbstractPerfTestService implements ControllerConstants, GrinderConstants { @@ -201,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); } @@ -231,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); @@ -585,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(), "")); @@ -763,25 +763,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; } @@ -839,7 +828,7 @@ public List getLogFiles(long testId) { if (!logFileDirectory.exists() || !logFileDirectory.isDirectory()) { return Collections.emptyList(); } - return asList(logFileDirectory.list()); + return asList(requireNonNull(logFileDirectory.list())); } /** @@ -1172,14 +1161,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 +1170,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 +1186,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 +1200,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 +1216,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 +1239,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 +1314,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 +1324,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 +1341,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 +1389,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 +1446,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 +1457,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)) { 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 ede4dfb73c..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 @@ -28,6 +28,7 @@ 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.*; @@ -86,7 +87,7 @@ 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); } @@ -130,6 +131,7 @@ public Tag saveTag(User user, Tag tag) { * @param user user * @param tag tag */ + @SuppressWarnings("unused") @Transactional public void deleteTag(User user, Tag tag) { for (PerfTest each : tag.getPerfTests()) { 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 15b645d449..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 @@ -14,7 +14,6 @@ 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; @@ -49,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. @@ -80,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(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; - 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(format(perfTest, "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())); } } }); 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/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/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/NullScriptHandler.java b/ngrinder-controller/src/main/java/org/ngrinder/script/handler/NullScriptHandler.java index ab6fa6b000..26137be9a7 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 @@ -34,7 +34,7 @@ @Component public class NullScriptHandler extends ScriptHandler { - private Map codeMirrorKey = newHashMap(); + private final Map codeMirrorKey = newHashMap(); public NullScriptHandler() { super("", "", null, null); @@ -54,7 +54,6 @@ public void prepareDist(PerfTest perfTest, User user, FileEntry script, // } - @SuppressWarnings("SpellCheckingInspection") @Override public boolean isValidatable() { return false; @@ -66,7 +65,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 a15420d916..4ecc054dee 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 @@ -114,7 +114,7 @@ public boolean canHandle(FileEntry fileEntry) { */ protected abstract Integer order(); - @SuppressWarnings("SpellCheckingInspection") + @SuppressWarnings("unused") @JsonProperty public boolean isValidatable() { return true; @@ -197,8 +197,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; } 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/FileType.java b/ngrinder-controller/src/main/java/org/ngrinder/script/model/FileType.java index 4fb8455410..586230ee93 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,19 @@ /** * 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), - + /** Xml. */ XML("xml", "xml", FileCategory.DATA, true, true), /** Text. */ @@ -57,7 +57,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 +68,7 @@ public enum FileType { /** * Constructor. - * + * * @param description description of this file type * @param extension file extension. * @param fileCategory category of FileType. @@ -86,7 +86,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 +96,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 +111,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 1d922b54df..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 @@ -132,10 +132,7 @@ 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())) { @@ -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,9 +171,7 @@ 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)) { @@ -193,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); @@ -217,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)); @@ -230,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); @@ -249,10 +242,8 @@ 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); @@ -262,7 +253,6 @@ public FileEntry findOne(User user, String path, SVNRevision revision) { return null; } finally { closeSVNClientManagerQuietly(svnClientManager); - IOUtils.closeQuietly(outputStream); } return script; } @@ -284,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); @@ -333,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()); } @@ -399,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 { @@ -505,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(); @@ -520,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 4a8704e2c6..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 @@ -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); } @@ -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 445a015ac1..6d1f1958ea 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 @@ -124,7 +124,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 +148,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)) { 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 9b8787b4de..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 @@ -38,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; @@ -115,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/NGrinderAuthenticationProvider.java b/ngrinder-controller/src/main/java/org/ngrinder/security/NGrinderAuthenticationProvider.java index 4f6e0d14e3..f56c32dfe0 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/security/NGrinderAuthenticationProvider.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/security/NGrinderAuthenticationProvider.java @@ -31,7 +31,6 @@ 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; @@ -56,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) { @@ -149,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 @@ -158,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/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/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 4283073094..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") @@ -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(); @@ -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/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/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 e28b474301..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,8 +11,8 @@ 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.DIST_MAP_NAME_RECENTLY_USED_AGENTS; import static org.ngrinder.common.util.CollectionUtils.newHashSet; 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 f75a76b0bd..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 @@ -24,7 +24,7 @@ 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; 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/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 d022e96222..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 @@ -14,6 +14,7 @@ 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; 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/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/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 a2b0218f68..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 @@ -42,7 +42,7 @@ 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; 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 e47e92d8d4..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 @@ -29,7 +29,7 @@ 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 { 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/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/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 be543e3e93..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 @@ -14,9 +14,9 @@ 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; 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 8e85724a16..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 @@ -31,8 +31,8 @@ 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 { 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 cd522dd264..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; } @@ -415,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(); @@ -444,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()); }); } @@ -541,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; } } @@ -652,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); @@ -664,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); }); } @@ -802,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; @@ -838,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(); @@ -892,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"); @@ -1033,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); }); } } @@ -1119,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; } @@ -1175,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()); }); } } @@ -1206,47 +1172,35 @@ public void unregisterSampling() { } 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/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..98df469b5a 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; @@ -30,7 +30,7 @@ public class AgentUpdateGrinderMessage implements Message { /** * -1 is ending, -2 is error */ - private int next; + private final int next; private final long checksum; /** 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 df11cc52d1..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.time.Instant; +import javax.persistence.*; import lombok.Getter; import lombok.Setter; @@ -40,23 +36,24 @@ public class BaseModel extends BaseEntity { private static final long serialVersionUID = -3876339828833595694L; - @Column(name = "created_at", insertable = true, updatable = false) + @Column(name = "created_at", updatable = false) private Instant createdAt; @JsonSerialize(using = User.UserReferenceSerializer.class) @ManyToOne - @JoinColumn(name = "created_by", insertable = true, updatable = false) - @Index(name = "created_by_index") + @JoinColumn(name = "created_by", updatable = false) + @NotFound(action = NotFoundAction.IGNORE) private User createdBy; - @Column(name = "last_modified_at", insertable = true, updatable = true) + + @Column(name = "last_modified_at") private Instant lastModifiedAt; @JsonSerialize(using = User.UserReferenceSerializer.class) @ManyToOne - @JoinColumn(name = "last_modified_By", insertable = true, updatable = true) - @Index(name = "last_modified_by_index") + @JoinColumn(name = "last_modified_By") + @NotFound(action = NotFoundAction.IGNORE) 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 b1f3a495f4..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,7 +21,6 @@ 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; @@ -42,7 +41,7 @@ * Performance Test Entity. */ -@SuppressWarnings({"JpaDataSourceORMInspection", "UnusedDeclaration", "JpaAttributeTypeInspection"}) +@SuppressWarnings({"JpaDataSourceORMInspection", "UnusedDeclaration", "JpaAttributeTypeInspection", "DanglingJavadoc"}) @Getter @Setter @Entity @@ -96,7 +95,6 @@ public PerfTest(User createdUser) { /** the scheduled time of this test. */ @Column(name = "scheduled_time") - @Index(name = "scheduled_time_index") private Instant scheduledTime; /** the start time of this test. */ @@ -354,14 +352,14 @@ public String getLastModifiedAtToStr() { */ @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; 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 0a0797f4c1..4e570b42a5 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/Status.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/Status.java @@ -191,7 +191,7 @@ public static Status[] getProcessingOrTestingTestStatus() { status.add(each); } } - return status.toArray(new Status[status.size()]); + return status.toArray(new Status[0]); } /** @@ -218,7 +218,7 @@ public static Status[] getTestingTestStates() { status.add(each); } } - return status.toArray(new Status[status.size()]); + return status.toArray(new Status[0]); } /** @@ -226,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/User.java b/ngrinder-core/src/main/java/org/ngrinder/model/User.java index 48a9ca0ef9..0a981002f3 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/model/User.java +++ b/ngrinder-core/src/main/java/org/ngrinder/model/User.java @@ -45,6 +45,7 @@ * @author Mavlarn * @since 3.0 */ +@SuppressWarnings("JpaDataSourceORMInspection") @Getter @Setter @Entity @@ -56,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; @@ -88,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 @@ -196,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 492733a445..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 @@ -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.error("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 167705a4bd..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 @@ -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; 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-groovy/build.gradle b/ngrinder-groovy/build.gradle index 9f1295e44b..8eb72573bd 100644 --- a/ngrinder-groovy/build.gradle +++ b/ngrinder-groovy/build.gradle @@ -9,11 +9,11 @@ configurations { dependencies { compile (project(":ngrinder-runtime")) compile (group: "org.codehaus.groovy", name: "groovy", version: groovy_version) - compile (group: 'org.codehaus.groovy', name: 'groovy-datetime', version: groovy_version) - compile (group: 'org.codehaus.groovy', name: 'groovy-templates', version: groovy_version) - compile (group: 'org.codehaus.groovy', name: 'groovy-json', version: groovy_version) - compile (group: 'org.codehaus.groovy', name: 'groovy-sql', version: groovy_version) - compile (group: 'org.codehaus.groovy', name: 'groovy-xml', version: groovy_version) + compile (group: "org.codehaus.groovy", name: "groovy-datetime", version: groovy_version) + compile (group: "org.codehaus.groovy", name: "groovy-templates", version: groovy_version) + compile (group: "org.codehaus.groovy", name: "groovy-json", version: groovy_version) + compile (group: "org.codehaus.groovy", name: "groovy-sql", version: groovy_version) + compile (group: "org.codehaus.groovy", name: "groovy-xml", version: groovy_version) testCompile (group: "org.mockito", name: "mockito-core", version: mockito_version) diff --git a/ngrinder-groovy/src/main/java/net/grinder/engine/process/JUnitThreadContextInitializer.java b/ngrinder-groovy/src/main/java/net/grinder/engine/process/JUnitThreadContextInitializer.java index 72113a5708..f43d794b6a 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/engine/process/JUnitThreadContextInitializer.java +++ b/ngrinder-groovy/src/main/java/net/grinder/engine/process/JUnitThreadContextInitializer.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.process; @@ -47,9 +47,9 @@ */ public class JUnitThreadContextInitializer { private static final Logger LOGGER = LoggerFactory.getLogger(JUnitThreadContextInitializer.class); - private ThreadContexts m_threadContexts = new ThreadContexts(); + private final ThreadContexts m_threadContexts = new ThreadContexts(); + private final Times m_times = new Times(); private StatisticsServices m_statisticsServices; - private Times m_times = new Times(); /** * Constructor. @@ -63,7 +63,7 @@ public JUnitThreadContextInitializer() { */ public void initialize() { m_statisticsServices = StatisticsServicesImplementation.getInstance(); - List list = new ArrayList(); + List list = new ArrayList<>(); DCRContextImplementation context = DCRContextImplementation.create(LOGGER); if (context == null) { diff --git a/ngrinder-groovy/src/main/java/net/grinder/engine/process/JUnitThreadContextUpdater.java b/ngrinder-groovy/src/main/java/net/grinder/engine/process/JUnitThreadContextUpdater.java index 2361894788..1be044a963 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/engine/process/JUnitThreadContextUpdater.java +++ b/ngrinder-groovy/src/main/java/net/grinder/engine/process/JUnitThreadContextUpdater.java @@ -4,20 +4,20 @@ /** * ThreadContext updater in JUnit context. - * + * * This class is responsible to update the Grinder thread context values when it's not executed in * the Grinder agent. - * + * * @author JunHo Yoon * @since 3.2.1 - * + * */ public class JUnitThreadContextUpdater { - private ThreadContexts m_threadContexts; + private final ThreadContexts m_threadContexts; /** * Constructor. - * + * * @param threadContexts threadContexts */ public JUnitThreadContextUpdater(ThreadContexts threadContexts) { @@ -25,12 +25,12 @@ public JUnitThreadContextUpdater(ThreadContexts threadContexts) { } /** - * Set run count in thread context. - * + * Set run count in thread context.NullStatement + * * @param count count */ public void setRunCount(int count) { m_threadContexts.get().setCurrentRunNumber(count); } - + } diff --git a/ngrinder-groovy/src/main/java/net/grinder/engine/process/NullSender.java b/ngrinder-groovy/src/main/java/net/grinder/engine/process/NullSender.java index d4b00a349c..2f3832296e 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/engine/process/NullSender.java +++ b/ngrinder-groovy/src/main/java/net/grinder/engine/process/NullSender.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,23 @@ * 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.process; -import net.grinder.communication.CommunicationException; import net.grinder.communication.Message; import net.grinder.communication.Sender; /** * NullSender to ignore {@link Sender} behavior. - * + * * @author JunHo Yoon * @since 3.2 */ public class NullSender implements Sender { @Override - public void send(Message message) throws CommunicationException { + public void send(Message message) { // Do nothing } diff --git a/ngrinder-groovy/src/main/java/net/grinder/engine/process/NullStatement.java b/ngrinder-groovy/src/main/java/net/grinder/engine/process/NullStatement.java index 16b5c9195f..f9938b2596 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/engine/process/NullStatement.java +++ b/ngrinder-groovy/src/main/java/net/grinder/engine/process/NullStatement.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.process; @@ -17,27 +17,27 @@ /** * Empty statement which does nothing. - * + * * This class is get by {@link #getInstance()} method. - * + * * @author JunHo Yoon * @since 3.2 */ public class NullStatement extends Statement { - private static NullStatement instance = new NullStatement(); + private static final NullStatement instance = new NullStatement(); NullStatement() { } @Override - public void evaluate() throws Throwable { + public void evaluate() { // Do Nothing } /** * Get the instance. - * + * * @return NullStatement instance */ public static Statement getInstance() { diff --git a/ngrinder-groovy/src/main/java/net/grinder/engine/process/SimpleAgentIdentity.java b/ngrinder-groovy/src/main/java/net/grinder/engine/process/SimpleAgentIdentity.java index 2bdac98f93..37ffef2f0d 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/engine/process/SimpleAgentIdentity.java +++ b/ngrinder-groovy/src/main/java/net/grinder/engine/process/SimpleAgentIdentity.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.process; @@ -17,19 +17,19 @@ /** * Simplified Agent Identity implementation which will be ignored in the unit test context. - * + * * @author JunHo Yoon * @since 3.2 */ public class SimpleAgentIdentity implements AgentIdentity { /** UUID. */ private static final long serialVersionUID = 2674072961464183737L; - private String name; - private int number; + private final String name; + private final int number; /** * Constructor. - * + * * @param name agent identity name * @param number agent number. */ diff --git a/ngrinder-groovy/src/main/java/net/grinder/engine/process/SimpleWorkerIdentity.java b/ngrinder-groovy/src/main/java/net/grinder/engine/process/SimpleWorkerIdentity.java index fb0db4ad61..54fe9c3539 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/engine/process/SimpleWorkerIdentity.java +++ b/ngrinder-groovy/src/main/java/net/grinder/engine/process/SimpleWorkerIdentity.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.process; @@ -18,19 +18,19 @@ /** * Simplified {@link WorkerIdentity}y implementation which will be ignored in the unit test context. - * + * * @author JunHo Yoon * @since 3.2 */ public class SimpleWorkerIdentity implements WorkerIdentity { private static final long serialVersionUID = 3; - private int m_number; - private SimpleAgentIdentity simpleAgentIdentity; + private final int m_number; + private final SimpleAgentIdentity simpleAgentIdentity; /** * Constructor. - * + * * @param name worker name * @param number worker number */ @@ -55,4 +55,4 @@ public String getName() { public AgentIdentity getAgentIdentity() { return simpleAgentIdentity; } -} \ No newline at end of file +} diff --git a/ngrinder-groovy/src/main/java/net/grinder/script/GTest.java b/ngrinder-groovy/src/main/java/net/grinder/script/GTest.java index d4b7d4614f..fdf0a7e5d0 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/script/GTest.java +++ b/ngrinder-groovy/src/main/java/net/grinder/script/GTest.java @@ -35,7 +35,7 @@ public class GTest extends Test { */ private static final long serialVersionUID = 8370116882992463352L; - private String context; + private final String context; /** * Constructor. * @@ -70,7 +70,7 @@ public final void record(Object target, String methodName) throws NonInstrumenta * @since 3.2.1 */ static class MethodNameFilter implements InstrumentationFilter { - private String methodName; + private final String methodName; /** * Constructor. diff --git a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/exception/AbstractExceptionProcessor.java b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/exception/AbstractExceptionProcessor.java index 27cb5b1e5d..c79548bf33 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/exception/AbstractExceptionProcessor.java +++ b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/exception/AbstractExceptionProcessor.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.scriptengine.exception; @@ -20,7 +20,7 @@ /** * Exception filtering processor. - * + * * @author JunHo Yoon * @since 3.2 */ @@ -28,7 +28,7 @@ public abstract class AbstractExceptionProcessor { /** * Filter exception. - * + * * @param throwable throwable * @return filtered {@link Throwable} */ @@ -38,10 +38,10 @@ public Throwable filterException(Throwable throwable) { /** * Get the root cause of the given {@link Throwable} instance. - * + * * It stops finding the root cause until it meets the null root cause or * net.grinder.engine.process.ShutdownException. - * + * * @param throwable throwable * @return root cause of the given {@link Throwable} instance. */ @@ -61,7 +61,7 @@ public Throwable getRootCause(Throwable throwable) { /** * Return true if the given {@link Throwable} is by the generic grinder * shutdown event. - * + * * @param cause cause * @return true if generic shutdown */ @@ -78,7 +78,7 @@ public boolean isGenericShutdown(Throwable cause) { /** * Filter the stack trace elements with only interesting one. - * + * * @param throwable throwable * @return {@link Throwable} instance with interested stacktrace elements. */ @@ -87,7 +87,7 @@ public Throwable sanitize(Throwable throwable) { while (t != null) { // Note that this getBoolean access may well be synced... StackTraceElement[] trace = t.getStackTrace(); - List newTrace = new ArrayList(); + List newTrace = new ArrayList<>(); for (StackTraceElement stackTraceElement : trace) { if (isApplicationClass(stackTraceElement.getClassName())) { newTrace.add(stackTraceElement); @@ -103,7 +103,7 @@ public Throwable sanitize(Throwable throwable) { /** * Check if the given class name is the application class or not. - * + * * @param className class name including package name * @return true if application class */ @@ -118,7 +118,7 @@ public boolean isApplicationClass(String className) { /** * Get interesting packages. - * + * * @return interesting packages */ @SuppressWarnings("UnusedDeclaration") @@ -126,7 +126,7 @@ public boolean isApplicationClass(String className) { /** * Get interesting packages. - * + * * @return interesting packages */ protected abstract String[] getUninterestingPackages(); diff --git a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/GroovyScriptEngine.java b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/GroovyScriptEngine.java index ecddde7280..c2aaaba9fd 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/GroovyScriptEngine.java +++ b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/GroovyScriptEngine.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.scriptengine.groovy; @@ -40,10 +40,12 @@ * @author JunHo Yoon (modified by) */ public class GroovyScriptEngine implements ScriptEngine { - private AbstractExceptionProcessor exceptionProcessor = new GroovyExceptionProcessor(); + + private final AbstractExceptionProcessor exceptionProcessor = new GroovyExceptionProcessor(); + private final GrinderContextExecutor m_grinderRunner; + // For unit test, make it package protected. Class m_groovyClass; - private GrinderContextExecutor m_grinderRunner; /** * Construct a GroovyScriptEngine that will use the supplied ScriptLocation. @@ -99,7 +101,7 @@ public ScriptEngineService.WorkerRunnable createWorkerRunnable(Object testRunner */ public final class GroovyWorkerRunnable implements ScriptEngineService.WorkerRunnable { private final GrinderContextExecutor m_groovyThreadRunner; - private RunNotifier notifier = new RunNotifier() { + private final RunNotifier notifier = new RunNotifier() { @SuppressWarnings("ThrowableResultOfMethodCallIgnored") public void fireTestFailure(Failure failure) { if (exceptionProcessor.isGenericShutdown(failure.getException())) { @@ -117,7 +119,7 @@ private GroovyWorkerRunnable(GrinderContextExecutor groovyRunner) throws EngineE this.m_groovyThreadRunner = groovyRunner; this.notifier.addListener(new RunListener() { @Override - public void testFailure(Failure failure) throws Exception { + public void testFailure(Failure failure) { // Skip Generic Shutdown... It's not failure. Throwable rootCause = exceptionProcessor.getRootCause(failure.getException()); if (exceptionProcessor.isGenericShutdown(rootCause)) { diff --git a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/GroovyScriptEngineService.java b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/GroovyScriptEngineService.java index 9c97819af9..61e50a577a 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/GroovyScriptEngineService.java +++ b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/GroovyScriptEngineService.java @@ -34,7 +34,7 @@ /** * Groovy script engine service. - * + * * @author Mavlarn * @since 3.0 */ @@ -48,7 +48,7 @@ public class GroovyScriptEngineService implements ScriptEngineService { /** * Constructor. - * + * * @param properties Properties. * @param dcrContext DCR context. * @param scriptLocation Script location. @@ -79,9 +79,9 @@ public GroovyScriptEngineService() { * {@inheritDoc} */ @Override - public List createInstrumenters() throws EngineException { + public List createInstrumenters() { - final List instrumenters = new ArrayList(); + final List instrumenters = new ArrayList<>(); /* * if (!m_forceDCRInstrumentation) { @@ -89,9 +89,7 @@ public List createInstrumenters() throws EngineException { * } */ if (m_dcrContext != null) { - if (instrumenters.size() == 0) { - instrumenters.add(new JavaDCRInstrumenterEx(m_dcrContext)); - } + instrumenters.add(new JavaDCRInstrumenterEx(m_dcrContext)); } return instrumenters; diff --git a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/GrinderRunner.java b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/GrinderRunner.java index 985c3a4b79..0ae05ebd3f 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/GrinderRunner.java +++ b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/GrinderRunner.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.scriptengine.groovy.junit; @@ -81,13 +81,15 @@ * @since 1.0 */ public class GrinderRunner extends BlockJUnit4ClassRunner { + + private final TestObjectFactory testTargetFactory; + private final AbstractExceptionProcessor exceptionProcessor = new GroovyExceptionProcessor(); + private final Map frameworkMethodCache = new HashMap<>(); + private JUnitThreadContextInitializer threadContextInitializer; private JUnitThreadContextUpdater threadContextUpdater; - private TestObjectFactory testTargetFactory; private PerThreadStatement finalPerThreadStatement; - private AbstractExceptionProcessor exceptionProcessor = new GroovyExceptionProcessor(); private boolean enableRateRunner = true; - private Map frameworkMethodCache = new HashMap(); /** * Constructor. @@ -128,7 +130,7 @@ public TestClass getTestClass() { } @Override - public Object createTest() throws Exception { + public Object createTest() { return runner; } }; @@ -298,22 +300,22 @@ protected Statement withBeforeThread(Statement statement) { protected void registerRunNotifierListener(RunNotifier notifier) { notifier.addFirstListener(new RunListener() { @Override - public void testStarted(Description description) throws Exception { + public void testStarted(Description description) { } @Override - public void testRunStarted(Description description) throws Exception { + public void testRunStarted(Description description) { attachWorker(); } @Override - public void testRunFinished(Result result) throws Exception { + public void testRunFinished(Result result) { detachWorker(); } @Override - public void testFailure(Failure failure) throws Exception { + public void testFailure(Failure failure) { Throwable exception = failure.getException(); Throwable filtered = exceptionProcessor.filterException(exception); if (exception != filtered) { diff --git a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/RunRateStatement.java b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/RunRateStatement.java index 913790b1ec..24c29a7416 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/RunRateStatement.java +++ b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/RunRateStatement.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.scriptengine.groovy.junit; @@ -21,7 +21,7 @@ * RunRateStatement is a custom JUnit 4.5+ {@link Statement} which adds support for * {@link net.grinder.scriptengine.groovy.junit.annotation.RunRate} annotation by deciding if the * test is runnable for the current run. - * + * * @see #evaluate() * @author JunHo Yoon * @since 3.2 @@ -29,12 +29,12 @@ public class RunRateStatement extends Statement { private final Statement statement; - private float interval; - private float percent; + private final float interval; + private final float percent; /** * Constructor. - * + * * @param statement statement to be repeated * @param runRate the percent of run */ diff --git a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/TestObjectFactory.java b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/TestObjectFactory.java index 82b7dbbfcb..72af2eeeb0 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/TestObjectFactory.java +++ b/ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/junit/TestObjectFactory.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.scriptengine.groovy.junit; @@ -23,21 +23,22 @@ /** * Abstract test object factory. This class is mainly responsible to keep the created object and * return the created one when it's created again. - * + * * This delegates the real object creation logic into sub class. - * + * * @author JunHo Yoon * @since 3.2 */ abstract class TestObjectFactory { - private Map testObjectMap = new HashMap(); + + private final Map testObjectMap = new HashMap<>(); public TestObjectFactory() { } /** * Get current test object - * + * * @return test object. */ public Object getTestObject() { diff --git a/ngrinder-groovy/src/main/java/net/grinder/util/GrinderUtils.java b/ngrinder-groovy/src/main/java/net/grinder/util/GrinderUtils.java index 20e95aac47..c2d0b67dfb 100644 --- a/ngrinder-groovy/src/main/java/net/grinder/util/GrinderUtils.java +++ b/ngrinder-groovy/src/main/java/net/grinder/util/GrinderUtils.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 @@ private static InternalScriptContext getGrinderInstance() { return grinder; } - private static Random random = new Random(); + private static final Random random = new Random(); /** * Convert nvpair map to array. With this user can create NVPair array using diff --git a/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyExceptionProcessorTest.java b/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyExceptionProcessorTest.java index 5db90c2045..e0ca406f4d 100644 --- a/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyExceptionProcessorTest.java +++ b/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyExceptionProcessorTest.java @@ -6,7 +6,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class GroovyExceptionProcessorTest { @SuppressWarnings("ThrowableResultOfMethodCallIgnored") diff --git a/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyParseErrorTest.java b/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyParseErrorTest.java index b063879f80..0c2e41f1e7 100644 --- a/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyParseErrorTest.java +++ b/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyParseErrorTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import static org.hamcrest.text.StringContains.containsString; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; public class GroovyParseErrorTest { diff --git a/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyScriptEngineTest.java b/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyScriptEngineTest.java index b253d541b5..2405cb583b 100644 --- a/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyScriptEngineTest.java +++ b/ngrinder-groovy/src/test/java/net/grinder/scriptengine/groovy/GroovyScriptEngineTest.java @@ -28,7 +28,7 @@ import java.io.File; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * Class description. diff --git a/ngrinder-groovy/src/test/java/net/grinder/util/EngineDiscoveryTest.java b/ngrinder-groovy/src/test/java/net/grinder/util/EngineDiscoveryTest.java index 41f98d1832..e02c850af9 100644 --- a/ngrinder-groovy/src/test/java/net/grinder/util/EngineDiscoveryTest.java +++ b/ngrinder-groovy/src/test/java/net/grinder/util/EngineDiscoveryTest.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 static net.grinder.util.ClassLoaderUtilities.allResourceLines; import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class EngineDiscoveryTest { diff --git a/ngrinder-runtime/src/main/java/org/ngrinder/dns/LocalManagedDnsProxy.java b/ngrinder-runtime/src/main/java/org/ngrinder/dns/LocalManagedDnsProxy.java index c4f391614e..6be89847d9 100644 --- a/ngrinder-runtime/src/main/java/org/ngrinder/dns/LocalManagedDnsProxy.java +++ b/ngrinder-runtime/src/main/java/org/ngrinder/dns/LocalManagedDnsProxy.java @@ -56,7 +56,7 @@ public String getHostByAddr(byte[] ip) throws UnknownHostException { public InetAddress[] lookupAllHostAddr(String name) throws UnknownHostException { Set ipAddresses = instance.get(name); if (ipAddresses != null) { - return DnsUtils.shuffle(ipAddresses.toArray(new InetAddress[ipAddresses.size()])); + return DnsUtils.shuffle(ipAddresses.toArray(new InetAddress[0])); } else { return defaultDnsImpl.lookupAllHostAddr(name); } diff --git a/ngrinder-runtime/src/main/java/org/ngrinder/dns/NameServiceProxy.java b/ngrinder-runtime/src/main/java/org/ngrinder/dns/NameServiceProxy.java index 8c84d32a9b..b6e3fb56e3 100644 --- a/ngrinder-runtime/src/main/java/org/ngrinder/dns/NameServiceProxy.java +++ b/ngrinder-runtime/src/main/java/org/ngrinder/dns/NameServiceProxy.java @@ -43,6 +43,7 @@ public interface NameServiceProxy extends InvocationHandler { * @param dns NameService implementation to be replaced. * Replace NameService implementation of {@link InetAddress}. */ + @SuppressWarnings("JavaReflectionMemberAccess") static void set(NameServiceProxy dns) throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException { Class inetAddressClass = InetAddress.class; Object proxyInstance; @@ -65,6 +66,7 @@ static void set(NameServiceProxy dns) throws NoSuchFieldException, ClassNotFound nameServiceField.setAccessible(false); } + @SuppressWarnings("SuspiciousInvocationHandlerImplementation") @Override default Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.getName().equalsIgnoreCase("lookupAllHostAddr") ? diff --git a/ngrinder-runtime/src/main/java/org/ngrinder/dns/NameStore.java b/ngrinder-runtime/src/main/java/org/ngrinder/dns/NameStore.java index 973b0e3841..d30c3532fa 100644 --- a/ngrinder-runtime/src/main/java/org/ngrinder/dns/NameStore.java +++ b/ngrinder-runtime/src/main/java/org/ngrinder/dns/NameStore.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.dns; @@ -34,7 +34,7 @@ public class NameStore { private final Map> globalNames; private NameStore() { - globalNames = new ConcurrentHashMap>(); + globalNames = new ConcurrentHashMap<>(); } /** @@ -90,12 +90,7 @@ private static void noOp() { * @param ipAddress ip address */ public void put(String hostName, String ipAddress) { - Set ipAddresses = globalNames.get(hostName); - if (ipAddresses == null) { - ipAddresses = new HashSet(); - globalNames.put(hostName, ipAddresses); - } - + Set ipAddresses = globalNames.computeIfAbsent(hostName, k -> new HashSet<>()); try { InetAddress address = InetAddress.getByAddress(DnsUtils.textToNumericFormat(ipAddress)); ipAddresses.add(address); diff --git a/ngrinder-runtime/src/main/java/org/ngrinder/sm/NGrinderSecurityManager.java b/ngrinder-runtime/src/main/java/org/ngrinder/sm/NGrinderSecurityManager.java index 3552af93fc..0d02d5b940 100644 --- a/ngrinder-runtime/src/main/java/org/ngrinder/sm/NGrinderSecurityManager.java +++ b/ngrinder-runtime/src/main/java/org/ngrinder/sm/NGrinderSecurityManager.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.sm; @@ -47,9 +47,9 @@ public class NGrinderSecurityManager extends SecurityManager { private final String pythonCache = System.getProperty("python.cachedir"); private final String etcHosts = System.getProperty("ngrinder.etc.hosts", ""); private final String consoleIP = System.getProperty("ngrinder.console.ip", "127.0.0.1"); - private final List allowedHost = new ArrayList(); - private final List writeAllowedDirectory = new ArrayList(); - private final List deleteAllowedDirectory = new ArrayList(); + private final List allowedHost = new ArrayList<>(); + private final List writeAllowedDirectory = new ArrayList<>(); + private final List deleteAllowedDirectory = new ArrayList<>(); { this.init(); diff --git a/ngrinder-runtime/src/test/java/org/ngrinder/dns/LocalManagedDnsTest.java b/ngrinder-runtime/src/test/java/org/ngrinder/dns/LocalManagedDnsTest.java index 823f5e84ac..298b6df5a9 100644 --- a/ngrinder-runtime/src/test/java/org/ngrinder/dns/LocalManagedDnsTest.java +++ b/ngrinder-runtime/src/test/java/org/ngrinder/dns/LocalManagedDnsTest.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.dns; @@ -21,7 +21,7 @@ import java.net.UnknownHostException; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * To test the custom DNS, should to add vm arguments as below: