Commit 5c540f3c authored by kmohiuddin's avatar kmohiuddin

adding project to git

parents
This diff is collapsed.
## Apache Maven Tutorial
Source code for mkyong.com Apache Maven tutorial
https://www.mkyong.com/tutorials/maven-tutorials/
\ No newline at end of file
# Maven – How to create a multi module project
Maven, Spring MVC, thymeleaf, a simple MVC web app to hash a string with either MD5 or the SHA-256 algorithm.
Project Link - https://www.mkyong.com/maven/maven-how-to-create-a-multi-module-project/
## How to run this project?
```
$ git clone https://github.com/mkyong/maven-examples.git
$ cd java-multi-modules
$ mvn install
$ mvn -pl web jetty:run
```
Output
```
Visit above project link for output.
```
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>java-multi-modules</artifactId>
<groupId>com.mkyong.multi</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<!-- password-md5 info -->
<groupId>com.mkyong.password</groupId>
<artifactId>password-md5</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.mkyong.password</groupId>
<artifactId>password</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.mkyong.password;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@Service
public class PasswordServiceImpl implements PasswordService {
@Override
public String hash(String input) {
return md5(input);
}
@Override
public String algorithm() {
return "md5";
}
private String md5(String input) {
StringBuilder result = new StringBuilder();
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
byte[] hashInBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
for (byte b : hashInBytes) {
result.append(String.format("%02x", b));
}
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
return result.toString();
}
}
package com.mkyong.password;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestPasswordService {
PasswordService passwordService;
@BeforeEach
void init() {
passwordService = new PasswordServiceImpl();
}
@DisplayName("md5 -> hex")
@ParameterizedTest
@CsvSource({
"123456, e10adc3949ba59abbe56e057f20f883e",
"hello world, 5eb63bbbe01eeed093cb22bb8f5acdc3"
})
void testMd5hex(String input, String expected) {
assertEquals(expected, passwordService.hash(input));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>java-multi-modules</artifactId>
<groupId>com.mkyong.multi</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.password</groupId>
<artifactId>password-sha</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<commos.codec.version>1.11</commos.codec.version>
</properties>
<dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commos.codec.version}</version>
</dependency>
<dependency>
<groupId>com.mkyong.password</groupId>
<artifactId>password</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.mkyong.password;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
@Service
public class PasswordServiceImpl implements PasswordService {
@Override
public String hash(String input) {
return DigestUtils.sha256Hex(input);
}
@Override
public String algorithm() {
return "sha256";
}
}
\ No newline at end of file
package com.mkyong.password;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestPasswordService {
PasswordService passwordService;
@BeforeEach
void init() {
passwordService = new PasswordServiceImpl();
}
@DisplayName("sha256 -> hex")
@ParameterizedTest
@CsvSource({
"123456, 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
"hello world, b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
})
void testSha256hex(String input, String expected) {
assertEquals(expected, passwordService.hash(input));
}
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>java-multi-modules</artifactId>
<groupId>com.mkyong.multi</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.password</groupId>
<artifactId>password</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
</project>
\ No newline at end of file
package com.mkyong.password;
public interface PasswordService {
String hash(String input);
String algorithm();
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.multi</groupId>
<artifactId>java-multi-modules</artifactId>
<packaging>pom</packaging>
<version>1.0</version>
<properties>
<!-- https://maven.apache.org/general.html#encoding-warning -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>5.3.1</junit.version>
<spring.version>5.1.0.RELEASE</spring.version>
</properties>
<modules>
<module>web</module>
<module>password</module>
<module>password-sha</module>
<module>password-md5</module>
</modules>
<dependencies>
<!-- Spring DI for all modules -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- unit test -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.1</version>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- this is a parent pom -->
<parent>
<groupId>com.mkyong.multi</groupId>
<artifactId>java-multi-modules</artifactId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<!-- web project info -->
<groupId>com.mkyong</groupId>
<artifactId>web</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<properties>
<thymeleaf.version>3.0.10.RELEASE</thymeleaf.version>
</properties>
<dependencies>
<!-- md5 hash -->
<dependency>
<groupId>com.mkyong.password</groupId>
<artifactId>password-md5</artifactId>
<version>1.0</version>
</dependency>
<!-- sha
<dependency>
<groupId>com.mkyong.password</groupId>
<artifactId>password-sha</artifactId>
<version>1.0</version>
</dependency>
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- logging , spring 5 no more bridge, thanks spring-jcl -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- need this for unit test -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<!-- servlet api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- thymeleaf view -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>${thymeleaf.version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>${thymeleaf.version}</version>
</dependency>
</dependencies>
<build>
<finalName>java-web-project</finalName>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.12.v20180830</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.mkyong.web;
import com.mkyong.web.config.SpringConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
package com.mkyong.web.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
@EnableWebMvc
@Configuration
@ComponentScan({"com.mkyong"})
public class SpringConfig implements WebMvcConfigurer {
@Autowired
private ApplicationContext applicationContext;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
@Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCacheable(true);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
}
}
package com.mkyong.web.controller;
import com.mkyong.password.PasswordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class WelcomeController {
private final Logger logger = LoggerFactory.getLogger(WelcomeController.class);
@Autowired
private PasswordService passwordService;
@GetMapping("/")
public String welcome(@RequestParam(name = "query",
required = false, defaultValue = "123456") String query, Model model) {
logger.debug("Welcome to mkyong.com... Query : {}", query);
model.addAttribute("query", query);
model.addAttribute("hash", passwordService.hash(query));
model.addAttribute("algorithm", passwordService.algorithm());
return "index";
}
}
package com.mkyong.web;
import com.mkyong.web.config.SpringConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
//https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/testing.html#integration-testing-annotations-junit-jupiter
//@ExtendWith(SpringExtension.class)
//@WebAppConfiguration
//@ContextConfiguration(classes = SpringConfig.class)
@SpringJUnitWebConfig(SpringConfig.class)
@DisplayName("Test Spring MVC default view")
public class TestWelcome {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webAppContext;
@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
}
@Test
public void testDefault() throws Exception {
this.mockMvc.perform(
get("/"))
//.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("index"))
.andExpect(model().attribute("query", "123456"));
//.andExpect(model().attribute("sha256", "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92"))
//.andExpect(model().attribute("md5", "e10adc3949ba59abbe56e057f20f883e"));
}
}
# Maven – How to create a Java project
Maven 3, Apache Commons Codec, a simple Java project to hash a string with the SHA-256 algorithm.
Project Link - https://www.mkyong.com/maven/how-to-create-a-java-project-with-maven/
## How to run this project?
```
$ git clone https://github.com/mkyong/maven-examples.git
$ cd java-project
$ mvn package
$ java -jar target/java-project-1.0-SNAPSHOT.jar 123456
```
Output
```
8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
```
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.hashing</groupId>
<artifactId>java-project</artifactId>
<name>java-project</name>
<version>1.0-SNAPSHOT</version>
<url>http://maven.apache.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer>
<mainClass>com.mkyong.hashing.App</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.hashing</groupId>
<artifactId>java-project</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>java-project</name>
<url>http://maven.apache.org</url>
<properties>
<!-- https://maven.apache.org/general.html#encoding-warning -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<!-- Attach the shade into the package phase -->
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.mkyong.hashing.App</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<!-- fat-jar -->
<!-- https://books.sonatype.com/mvnex-book/reference/customizing-sect-custom-packaged.html -->
<!--
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.mkyong.hashing.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>simple-command</id>
<phase>package</phase>
<goals>
<goal>attached</goal>
</goals>
</execution>
</executions>
</plugin>
-->
</plugins>
</build>
</project>
package com.mkyong.hashing;
import org.apache.commons.codec.digest.DigestUtils;
public class App {
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("Please provide an input!");
System.exit(0);
}
System.out.println(sha256hex(args[0]));
}
public static String sha256hex(String input) {
return DigestUtils.sha256Hex(input);
}
}
package com.mkyong.hashing;
import org.junit.Assert;
import org.junit.Test;
public class AppTest {
private String INPUT = "123456";
@Test
public void testLength() {
Assert.assertEquals(64, App.sha256hex(INPUT).length());
}
@Test
public void testHex() {
String expected = "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92";
Assert.assertEquals(expected, App.sha256hex(INPUT));
}
}
\ No newline at end of file
#Generated by Maven
#Mon Jan 20 14:30:40 PKT 2020
groupId=com.mkyong.hashing
artifactId=java-project
version=1.0-SNAPSHOT
/home/kmohiuddin/course/jenkins/maven-examples/java-project/src/main/java/com/mkyong/hashing/App.java
/home/kmohiuddin/course/jenkins/maven-examples/java-project/src/test/java/com/mkyong/hashing/AppTest.java
<?xml version="1.0" encoding="UTF-8" ?>
<testsuite tests="2" failures="0" name="com.mkyong.hashing.AppTest" time="0.065" errors="0" skipped="0">
<properties>
<property name="java.runtime.name" value="OpenJDK Runtime Environment"/>
<property name="java.vm.version" value="11.0.5+10-post-Ubuntu-0ubuntu1.118.04"/>
<property name="sun.boot.library.path" value="/usr/lib/jvm/java-11-openjdk-amd64/lib"/>
<property name="maven.multiModuleProjectDirectory" value="/home/kmohiuddin/course/jenkins/maven-examples/java-project"/>
<property name="java.vm.vendor" value="Private Build"/>
<property name="java.vendor.url" value="Unknown"/>
<property name="guice.disable.misplaced.annotation.check" value="true"/>
<property name="path.separator" value=":"/>
<property name="java.vm.name" value="OpenJDK 64-Bit Server VM"/>
<property name="sun.os.patch.level" value="unknown"/>
<property name="user.country" value="US"/>
<property name="sun.java.launcher" value="SUN_STANDARD"/>
<property name="java.vm.specification.name" value="Java Virtual Machine Specification"/>
<property name="user.dir" value="/home/kmohiuddin/course/jenkins/maven-examples/java-project"/>
<property name="java.vm.compressedOopsMode" value="Zero based"/>
<property name="java.runtime.version" value="11.0.5+10-post-Ubuntu-0ubuntu1.118.04"/>
<property name="java.awt.graphicsenv" value="sun.awt.X11GraphicsEnvironment"/>
<property name="os.arch" value="amd64"/>
<property name="java.io.tmpdir" value="/tmp"/>
<property name="line.separator" value="
"/>
<property name="java.vm.specification.vendor" value="Oracle Corporation"/>
<property name="os.name" value="Linux"/>
<property name="classworlds.conf" value="/home/kmohiuddin/.sdkman/candidates/maven/current/bin/m2.conf"/>
<property name="sun.jnu.encoding" value="UTF-8"/>
<property name="java.library.path" value="/usr/java/packages/lib:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib"/>
<property name="maven.conf" value="/home/kmohiuddin/.sdkman/candidates/maven/current/conf"/>
<property name="jdk.debug" value="release"/>
<property name="java.class.version" value="55.0"/>
<property name="java.specification.name" value="Java Platform API Specification"/>
<property name="sun.management.compiler" value="HotSpot 64-Bit Tiered Compilers"/>
<property name="os.version" value="5.0.0-37-generic"/>
<property name="library.jansi.path" value="/home/kmohiuddin/.sdkman/candidates/maven/current/lib/jansi-native"/>
<property name="user.home" value="/home/kmohiuddin"/>
<property name="user.timezone" value="Asia/Karachi"/>
<property name="java.awt.printerjob" value="sun.print.PSPrinterJob"/>
<property name="file.encoding" value="UTF-8"/>
<property name="java.specification.version" value="11"/>
<property name="user.name" value="kmohiuddin"/>
<property name="java.class.path" value="/home/kmohiuddin/.sdkman/candidates/maven/current/boot/plexus-classworlds-2.6.0.jar"/>
<property name="java.vm.specification.version" value="11"/>
<property name="sun.arch.data.model" value="64"/>
<property name="sun.java.command" value="org.codehaus.plexus.classworlds.launcher.Launcher install"/>
<property name="java.home" value="/usr/lib/jvm/java-11-openjdk-amd64"/>
<property name="user.language" value="en"/>
<property name="java.specification.vendor" value="Oracle Corporation"/>
<property name="awt.toolkit" value="sun.awt.X11.XToolkit"/>
<property name="java.vm.info" value="mixed mode"/>
<property name="java.version" value="11.0.5"/>
<property name="securerandom.source" value="file:/dev/./urandom"/>
<property name="java.vendor" value="Private Build"/>
<property name="maven.home" value="/home/kmohiuddin/.sdkman/candidates/maven/current"/>
<property name="file.separator" value="/"/>
<property name="java.version.date" value="2019-10-15"/>
<property name="java.vendor.url.bug" value="Unknown"/>
<property name="sun.io.unicode.encoding" value="UnicodeLittle"/>
<property name="sun.cpu.endian" value="little"/>
<property name="sun.desktop" value="gnome"/>
<property name="sun.cpu.isalist" value=""/>
</properties>
<testcase classname="com.mkyong.hashing.AppTest" name="testHex" time="0.063"/>
<testcase classname="com.mkyong.hashing.AppTest" name="testLength" time="0.002"/>
</testsuite>
\ No newline at end of file
-------------------------------------------------------------------------------
Test set: com.mkyong.hashing.AppTest
-------------------------------------------------------------------------------
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.216 sec
# Maven - How to create a Java web application project
Maven 3, Spring 5 MVC, JUnit 5, Logback and Jetty web server. A simple web project to display a current date.
Project Link - https://www.mkyong.com/maven/how-to-create-a-web-application-project-with-maven/
## 1. How to run this project?
### 1.1 Test it with Jetty web server.
```
$ git clone https://github.com/mkyong/maven-examples.git
$ cd java-web-project
$ mvn jetty:run
```
Access http://localhost:8080
### 1.2 Create a WAR file for deployment :
```
$ git clone https://github.com/mkyong/maven-examples.git
$ cd java-web-project
$ mvn package or mvn war:war
```
A WAR is generated at 'target/finalName'
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.web</groupId>
<artifactId>java-web-project</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>java-web-project Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<!-- https://maven.apache.org/general.html#encoding-warning -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.1.0.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- logging , spring 5 no more bridge, thanks spring-jcl -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- junit 5, unit test -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.3.1</version>
<scope>test</scope>
</dependency>
<!-- unit test -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<!-- for web servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- Some containers like Tomcat don't have jstl library -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>java-web-project</finalName>
<plugins>
<!-- http://www.eclipse.org/jetty/documentation/current/jetty-maven-plugin.html -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.12.v20180830</version>
</plugin>
<!-- Default is too old, update to latest to run the latest Spring 5 + jUnit 5 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
</plugin>
<!-- Default 2.2 is too old, update to latest -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
</plugins>
</build>
</project>
package com.mkyong.web;
import com.mkyong.web.config.SpringConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
package com.mkyong.web.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Date;
@Controller
public class WelcomeController {
private final Logger logger = LoggerFactory.getLogger(WelcomeController.class);
@GetMapping("/")
public String index(Model model) {
logger.debug("Welcome to mkyong.com...");
model.addAttribute("msg", getMessage());
model.addAttribute("today", new Date());
return "index";
}
public String getMessage() {
return "Hello World";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
</Pattern>
</layout>
</appender>
<logger name="com.mkyong.web" level="debug"
additivity="false">
<appender-ref ref="STDOUT"/>
</logger>
<root level="error">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
\ No newline at end of file
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<html>
<body>
<h1>${msg}</h1>
<h2>Today is <fmt:formatDate value="${today}" pattern="yyy-MM-dd" /></h2>
</body>
</html>
\ No newline at end of file
package com.mkyong.web;
import com.mkyong.web.config.SpringConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
//https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/testing.html#integration-testing-annotations-junit-jupiter
@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration(classes = SpringConfig.class)
//@SpringJUnitWebConfig(SpringConfig.class)
public class TestWelcome {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webAppContext;
@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
}
@Test
public void testWelcome() throws Exception {
this.mockMvc.perform(
get("/"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("index"))
.andExpect(forwardedUrl("/WEB-INF/views/index.jsp"))
.andExpect(model().attribute("msg", "Hello World"));
}
@Test
public void testAbc() {
assertEquals(2, 1 + 1);
}
}
# Maven – JaCoCo code coverage example
Maven, JUnit 5 + JaCoCo example.
Project Link - https://www.mkyong.com/maven/maven-jacoco-code-coverage-example/
## How to run this project?
```
$ git clone https://github.com/mkyong/maven-examples.git
$ cd maven-code-coverage
$ mvn clean test
# view report at 'target/site/jacoco/index.html'
```
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.examples</groupId>
<artifactId>maven-code-coverage</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<!-- https://maven.apache.org/general.html#encoding-warning -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>5.3.1</junit.version>
<jacoco.version>0.8.2</jacoco.version>
</properties>
<dependencies>
<!-- junit 5, unit test -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>maven-code-coverage</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>jacoco-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>PACKAGE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.9</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
package com.mkyong.examples;
public class MessageBuilder {
public String getMessage(String name) {
StringBuilder result = new StringBuilder();
if (name == null || name.trim().length() == 0) {
result.append("Please provide a name!");
} else {
result.append("Hello " + name);
}
return result.toString();
}
}
package com.mkyong.examples;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestMessageBuilder {
@Test
public void testNameMkyong() {
MessageBuilder obj = new MessageBuilder();
assertEquals("Hello mkyong", obj.getMessage("mkyong"));
}
/*@Test
public void testNameEmpty() {
MessageBuilder obj = new MessageBuilder();
assertEquals("Please provide a name!", obj.getMessage(" "));
}
@Test
public void testNameNull() {
MessageBuilder obj = new MessageBuilder();
assertEquals("Please provide a name!", obj.getMessage(null));
}*/
}
\ No newline at end of file
# Maven – PITest mutation testing example
Maven, JUnit 5 + PITest example.
Project Link - https://www.mkyong.com/maven/maven-pitest-mutation-testing-example/
## How to run this project?
```
$ git clone https://github.com/mkyong/maven-examples.git
$ cd maven-mutation-testing
$ mvn clean org.pitest:pitest-maven:mutationCoverage
#or
$ mvn clean test
# view report at target/pit-reports/YYYYMMDDHHMI/index.html
```
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.examples</groupId>
<artifactId>maven-mutation-testing</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<!-- https://maven.apache.org/general.html#encoding-warning -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>5.3.1</junit.version>
<pitest.version>1.4.3</pitest.version>
</properties>
<dependencies>
<!-- junit 5, unit test -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>maven-mutation-testing</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
<plugin>
<groupId>org.pitest</groupId>
<artifactId>pitest-maven</artifactId>
<version>${pitest.version}</version>
<executions>
<execution>
<id>pit-report</id>
<phase>test</phase>
<goals>
<goal>mutationCoverage</goal>
</goals>
</execution>
</executions>
<!-- https://github.com/hcoles/pitest/issues/284 -->
<!-- Need this to support JUnit 5 -->
<dependencies>
<dependency>
<groupId>org.pitest</groupId>
<artifactId>pitest-junit5-plugin</artifactId>
<version>0.8</version>
</dependency>
</dependencies>
<configuration>
<targetClasses>
<param>com.mkyong.examples.*Calculator*</param>
<param>com.mkyong.examples.*Stock*</param>
</targetClasses>
<targetTests>
<param>com.mkyong.examples.*</param>
</targetTests>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.mkyong.examples;
public class CalculatorService {
public boolean isPositive(int number) {
boolean result = false;
if (number >= 0) {
result = true;
}
return result;
}
}
package com.mkyong.examples;
public class StockService {
private int qtyOnHand;
public StockService(int qtyOnHand) {
this.qtyOnHand = qtyOnHand;
}
private void isValidQty(int qty) {
if (qty < 0) {
throw new IllegalArgumentException("Quality should be positive!");
}
}
public int add(int qty) {
isValidQty(qty);
qtyOnHand = qtyOnHand + qty;
return qtyOnHand;
}
public int deduct(int qty) {
isValidQty(qty);
int newQty = qtyOnHand - qty;
if (newQty < 0) {
throw new IllegalArgumentException("Out of Stock!");
} else {
qtyOnHand = newQty;
}
return qtyOnHand;
}
}
package com.mkyong.examples;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestCalculatorService {
@Test
public void testPositive() {
CalculatorService obj = new CalculatorService();
assertEquals(true, obj.isPositive(10));
//kill mutation #1
assertEquals(true, obj.isPositive(0));
}
}
package com.mkyong.examples;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestStockService {
@DisplayName("Test deduct stock")
@Test
public void testDeduct() {
StockService obj = new StockService(100);
assertEquals(90, obj.deduct(10));
assertEquals(0, obj.deduct(90));
assertEquals(0, obj.deduct(0));
Assertions.assertThrows(IllegalArgumentException.class, () -> {
obj.deduct(-1);
});
Assertions.assertThrows(IllegalArgumentException.class, () -> {
obj.deduct(100);
});
}
@DisplayName("Test add stock")
@Test
public void testAdd() {
StockService obj = new StockService(100);
assertEquals(110, obj.add(10));
assertEquals(110, obj.add(0));
Assertions.assertThrows(IllegalArgumentException.class, () -> {
obj.add(-1);
});
}
}
\ No newline at end of file
# Maven Profiles example
Maven profile examples to pass different parameters for different environment (development, test or production).
Project Link - https://www.mkyong.com/maven/maven-profiles-example/
## How to run this project?
```
$ git clone https://github.com/mkyong/maven-examples.git
$ cd maven-profiles
# Test the example 1 with profile ‘prod’
$ mvn -pl example1 package -Pprod
$ java -jar example1/target/example1-1.0.jar
# Test the example 2 with profile ‘test’
$ mvn -pl example2 package -Ptest
$ java -jar example2/target/example2-1.0.jar
```
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>maven-profiles</artifactId>
<groupId>com.mkyong</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>example1</artifactId>
<profiles>
<profile>
<id>dev</id>
<activation>
<!-- this profile is active by default -->
<activeByDefault>true</activeByDefault>
<!-- activate if system properties 'env=dev' -->
<property>
<name>env</name>
<value>dev</value>
</property>
</activation>
<properties>
<db.driverClassName>com.mysql.jdbc.Driver</db.driverClassName>
<db.url>jdbc:mysql://localhost:3306/dev</db.url>
<db.username>mkyong</db.username>
<db.password>8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92</db.password>
</properties>
</profile>
<profile>
<id>prod</id>
<activation>
<!-- activate if system properties 'env=prod' -->
<property>
<name>env</name>
<value>prod</value>
</property>
</activation>
<properties>
<db.driverClassName>com.mysql.jdbc.Driver</db.driverClassName>
<db.url>jdbc:mysql://live01:3306/prod</db.url>
<db.username>mkyong</db.username>
<db.password>8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92</db.password>
</properties>
</profile>
</profiles>
<build>
<!-- map ${} variable -->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.mkyong.example1.App1</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<!--
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.mkyong.password.App1</mainClass>
<arguments>
<argument>123456</argument>
</arguments>
<systemProperties>
<systemProperty>
<key>db.driverClassName</key>
<value>${db.driverClassName}</value>
</systemProperty>
<systemProperty>
<key>db.url</key>
<value>${db.url}</value>
</systemProperty>
<systemProperty>
<key>db.user</key>
<value>${db.user}</value>
</systemProperty>
<systemProperty>
<key>db.password</key>
<value>${db.password}</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
-->
</plugins>
</build>
</project>
\ No newline at end of file
package com.mkyong.example1;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class App1 {
public static void main(String[] args) {
App1 app = new App1();
Properties prop = app.loadPropertiesFile("db.properties");
prop.forEach((k, v) -> System.out.println(k + ":" + v));
}
public Properties loadPropertiesFile(String filePath) {
Properties prop = new Properties();
try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(filePath)) {
prop.load(resourceAsStream);
} catch (IOException e) {
System.err.println("Unable to load properties file : " + filePath);
}
return prop;
}
}
db.driverClassName=${db.driverClassName}
db.url=${db.url}
db.username=${db.username}
db.password=${db.password}
\ No newline at end of file
package com.mkyong.example1;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestApp1 {
@Test
@DisplayName("Testing App1")
public void testApp1() {
assertEquals(1, 1);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>maven-profiles</artifactId>
<groupId>com.mkyong</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>example2</artifactId>
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<env>dev</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
</profiles>
<build>
<!-- Loading all ${} -->
<filters>
<filter>src/main/resources/env/config.${env}.properties</filter>
</filters>
<!-- Map ${} into resources -->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>*.properties</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.mkyong.example2.App2</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.mkyong.example2;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class App2 {
public static void main(String[] args) {
App2 app = new App2();
Properties prop = app.loadPropertiesFile("config.properties");
prop.forEach((k, v) -> System.out.println(k + ":" + v));
}
public Properties loadPropertiesFile(String filePath) {
Properties prop = new Properties();
try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(filePath)) {
prop.load(resourceAsStream);
} catch (IOException e) {
System.err.println("Unable to load properties file : " + filePath);
}
return prop;
}
}
# Database Config
db.driverClassName=${db.driverClassName}
db.url=${db.url}
db.username=${db.username}
db.password=${db.password}
# Email Server
email.server=${email.server}
# Log Files
log.file.location=${log.file.location}
\ No newline at end of file
# Database Config
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/dev
db.username=mkyong
db.password=8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
# Email Server
email.server=email-dev:8888
# Log Files
log.file.location=dev/file.log
# Database Config
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://live01:3306/prod
db.username=mkyong
db.password=8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
# Email Server
email.server=email-prod:25
# Log Files
log.file.location=prod/file.log
# Database Config
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://test01:3306/test
db.username=mkyong
db.password=8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
# Email Server
email.server=email-test:8888
# Log Files
log.file.location=test/file.log
package com.mkyong.example2;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestApp2 {
@Test
@DisplayName("Testing App2")
public void testApp2() {
assertEquals(1, 1);
}
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong</groupId>
<artifactId>maven-profiles</artifactId>
<packaging>pom</packaging>
<version>1.0</version>
<!-- sub modules -->
<modules>
<module>example1</module>
<module>example2</module>
</modules>
<properties>
<!-- https://maven.apache.org/general.html#encoding-warning -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>5.3.1</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<!-- skip unit test -->
<profile>
<id>xtest</id>
<properties>
<maven.test.skip>true</maven.test.skip>
</properties>
</profile>
</profiles>
<build>
<plugins>
<!-- display active profile in compile phase -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-help-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>show-profiles</id>
<phase>compile</phase>
<goals>
<goal>active-profiles</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
# Maven – Static Code Analysis
Maven, SpotBugs, PMD, static code analysis.
Maven SpotBugs example
https://www.mkyong.com/maven/maven-spotbugs-example/
Maven PMD example
http://www.mkyong.com/maven/maven-pmd-example/
## How to run this project?
```
$ git clone https://github.com/mkyong/maven-examples.git
$ cd maven-static-code-analysis
$ mvn compile site
# view report at target/site/pmd.html
# view report at target/site/spotbugs.html
```
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.examples</groupId>
<artifactId>maven-static-code-analysis</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<!-- https://maven.apache.org/general.html#encoding-warning -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spotbugs.version>3.1.8</spotbugs.version>
<pmd.version>3.11.0</pmd.version>
</properties>
<reporting>
<plugins>
<!-- https://spotbugs.github.io/ -->
<!-- https://spotbugs.github.io/spotbugs-maven-plugin/usage.html -->
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>${spotbugs.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>${pmd.version}</version>
</plugin>
</plugins>
</reporting>
<build>
<finalName>maven-static-code-analysis</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
-->
</plugins>
</build>
</project>
package com.mkyong.examples;
public class StaticCodeExample {
//Unused field
private int abc;
// Do not hard code the IP address
private String ip = "127.0.0.1";
public void test() {
String[] field = {"a", "b", "c", "s", "e"};
//concatenates strings using + in a loop
String s = "";
for (int i = 0; i < field.length; ++i) {
s = s + field[i];
}
System.out.println(ip);
}
}
# Maven - How to run Unit Test
Maven unit test examples, JUnit 5.
Project Link - https://www.mkyong.com/maven/how-to-run-unit-test-with-maven/
## How to run this project?
```
$ git clone https://github.com/mkyong/maven-examples.git
$ cd maven-unit-test
$ mvn test
$ mvn -Dtest=TestMessageBuilder test
$ mvn -Dtest=TestMessageBuilder#testHelloWorld test
```
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.examples</groupId>
<artifactId>maven-unit-test</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<!-- https://maven.apache.org/general.html#encoding-warning -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- junit 5, unit test -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.3.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>maven-unit-test</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
</plugin>
</plugins>
</build>
</project>
package com.mkyong.examples;
public class MagicBuilder {
public static int getLucky() {
return 7;
}
}
package com.mkyong.examples;
public class MessageBuilder {
public static String getHelloWorld(){
return "hello world";
}
public static int getNumber10(){
return 10;
}
}
package com.mkyong.examples;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestMagicBuilder {
@Test
public void testLucky() {
assertEquals(7, MagicBuilder.getLucky());
}
}
package com.mkyong.examples;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestMessageBuilder {
@Test
public void testHelloWorld() {
assertEquals("hello world", MessageBuilder.getHelloWorld());
}
@Test
public void testNumber10() {
assertEquals(10, MessageBuilder.getNumber10());
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment