├── .gitignore ├── .travis.yml ├── README.md ├── core-java-9 ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── stackify │ │ └── optional │ │ └── User.java │ └── test │ └── java │ └── com │ └── stackify │ └── optional │ └── OptionalTest.java ├── core-java ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── stackify │ │ │ ├── optional │ │ │ ├── Address.java │ │ │ ├── Country.java │ │ │ ├── User.java │ │ │ └── chaining │ │ │ │ ├── Address.java │ │ │ │ ├── Country.java │ │ │ │ └── User.java │ │ │ ├── optionalparams │ │ │ ├── MultiVitamin.java │ │ │ ├── MultiVitaminAllowingNulls.java │ │ │ ├── MultiVitaminOverloading.java │ │ │ ├── MultiVitaminStaticFactoryMethods.java │ │ │ └── MultiVitaminWithBuilder.java │ │ │ └── stream │ │ │ ├── Employee.java │ │ │ └── EmployeeRepository.java │ └── resources │ │ └── log4j2.xml │ └── test │ ├── java │ └── com │ │ └── stackify │ │ ├── optional │ │ ├── OptionalTest.java │ │ └── chaining │ │ │ └── OptionalChainingTest.java │ │ ├── optionalparams │ │ └── OptionalParamsUnitTest.java │ │ └── stream │ │ └── EmployeeTest.java │ └── resources │ └── .keep ├── core-kotlin ├── .gitignore ├── pom.xml └── src │ └── test │ └── kotlin │ └── com │ └── stackify │ └── kotlinvsjava │ ├── CompanionObjectTest.kt │ ├── ConstructorTest.kt │ ├── DataClassTest.kt │ ├── DelegationTest.kt │ ├── ExceptionsTest.kt │ ├── ExtensionFunctionsTest.kt │ ├── FunctionsTest.kt │ ├── IsOperatorTest.kt │ ├── NullSafetyTest.kt │ ├── OperatorsOverloadingTest.kt │ └── PropertiesTest.kt ├── deep-jsf ├── .settings │ ├── .jsdtscope │ ├── org.eclipse.jdt.core.prefs │ ├── org.eclipse.m2e.core.prefs │ ├── org.eclipse.wst.common.component │ ├── org.eclipse.wst.common.project.facet.core.prefs.xml │ ├── org.eclipse.wst.common.project.facet.core.xml │ ├── org.eclipse.wst.jsdt.ui.superType.container │ ├── org.eclipse.wst.jsdt.ui.superType.name │ └── org.eclipse.wst.validation.prefs ├── README.md ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── stackify │ │ └── deepjsf │ │ ├── GreetControllerBean.java │ │ ├── PhaseListenerBean.java │ │ ├── UserBean.java │ │ └── UserControllerBean.java │ └── webapp │ ├── WEB-INF │ └── faces-config.xml │ ├── greet.xhtml │ ├── hello.xhtml │ ├── index.xhtml │ └── register.xhtml ├── junit5-example ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── stackify │ │ │ ├── daos │ │ │ └── UserDAO.java │ │ │ ├── models │ │ │ └── User.java │ │ │ ├── test │ │ │ └── conditions │ │ │ │ ├── DisabledOnEnvironment.java │ │ │ │ └── DisabledOnEnvironmentCondition.java │ │ │ └── utils │ │ │ └── ConnectionUtil.java │ └── resources │ │ ├── application.properties │ │ ├── com │ │ └── stackify │ │ │ └── utils │ │ │ └── jdbc.properties │ │ └── log4j2.xml │ └── test │ └── java │ └── com │ └── stackify │ └── test │ ├── DatabaseConnectionTest.java │ ├── DynamicTests.java │ ├── IncrementTest.java │ ├── TaggedTest.java │ └── UsersTest.java ├── log4j2-example ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── stackify │ │ │ ├── models │ │ │ └── User.java │ │ │ └── services │ │ │ └── MyService.java │ └── resources │ │ └── log4j2.xml │ └── test │ └── java │ └── com │ └── stackify │ └── services │ └── MyServiceTest.java ├── logback-example ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── stackify │ │ │ ├── logging │ │ │ └── IgnoreLoggerFilter.java │ │ │ ├── models │ │ │ └── Employee.java │ │ │ └── services │ │ │ └── EmployeeService.java │ └── resources │ │ ├── application.properties │ │ └── logback.xml │ └── test │ └── java │ └── com │ └── stackify │ └── services │ └── EmployeeServiceTest.java ├── memory-leaks ├── pom.xml └── src │ └── test │ ├── java │ └── com │ │ └── baeldung │ │ ├── Key.java │ │ └── MemoryLeaksTest.java │ └── resources │ └── large.txt ├── pom.xml ├── remote-debugging ├── README.md ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── stackify │ └── debug │ ├── JavaRemoteDebuggingApplication.java │ ├── config │ └── WebInitializer.java │ └── rest │ └── HelloController.java ├── slf4j └── guide │ ├── pom.xml │ ├── slf4j-log4j │ ├── .gitignore │ ├── pom.xml │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── stackify │ │ │ │ └── slf4j │ │ │ │ └── guide │ │ │ │ ├── Application.java │ │ │ │ └── controllers │ │ │ │ └── SimpleController.java │ │ └── resources │ │ │ ├── application.properties │ │ │ └── log4j.xml │ │ └── test │ │ ├── java │ │ └── com │ │ │ └── stackify │ │ │ └── slf4j │ │ │ └── guide │ │ │ ├── controllers │ │ │ └── SimpleControllerIntegrationTest.java │ │ │ └── utils │ │ │ └── ListAppender.java │ │ └── resources │ │ └── log4j.xml │ ├── slf4j-log4j2 │ ├── .gitignore │ ├── pom.xml │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── stackify │ │ │ │ └── slf4j │ │ │ │ └── guide │ │ │ │ ├── Application.java │ │ │ │ └── controllers │ │ │ │ └── SimpleController.java │ │ └── resources │ │ │ ├── application.properties │ │ │ └── log4j2-spring.xml │ │ └── test │ │ ├── java │ │ └── com │ │ │ └── stackify │ │ │ └── slf4j │ │ │ └── guide │ │ │ └── controllers │ │ │ └── SimpleControllerIntegrationTest.java │ │ └── resources │ │ └── log4j2-test.xml │ └── slf4j-logback │ ├── .gitignore │ ├── pom.xml │ └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── stackify │ │ │ └── slf4j │ │ │ └── guide │ │ │ ├── Application.java │ │ │ ├── controllers │ │ │ └── SimpleController.java │ │ │ ├── l10n │ │ │ └── Messages.java │ │ │ └── xlogger │ │ │ └── XLoggerController.java │ └── resources │ │ ├── application.properties │ │ ├── logback-spring.xml │ │ ├── messages_en_US.properties │ │ └── messages_es_ES.properties │ └── test │ ├── java │ └── com │ │ └── stackify │ │ └── slf4j │ │ └── guide │ │ ├── controllers │ │ └── SimpleControllerIntegrationTest.java │ │ └── utils │ │ └── ListAppender.java │ └── resources │ └── logback-test.xml ├── spring-boot-app ├── .gitignore ├── README.md ├── WebContent │ └── META-INF │ │ └── MANIFEST.MF ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── stackify │ │ │ ├── Application.java │ │ │ ├── config │ │ │ └── PersistenceConfig.java │ │ │ ├── controller │ │ │ └── EmployeeController.java │ │ │ ├── model │ │ │ └── Employee.java │ │ │ └── repository │ │ │ └── EmployeeRepository.java │ └── resources │ │ ├── application.properties │ │ ├── myData.sql │ │ └── mySchema.sql │ └── test │ └── java │ └── com │ └── stackify │ └── test │ └── EmployeeControllerTest.java ├── spring-mvc ├── .gitignore ├── .settings │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.core.prefs │ ├── org.eclipse.m2e.core.prefs │ └── org.eclipse.wst.common.project.facet.core.xml ├── .springBeans ├── README.md ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── stackify │ │ └── guest │ │ └── springmvc │ │ ├── Spring5Application.java │ │ ├── model │ │ └── LoginData.java │ │ └── web │ │ ├── InternalsController.java │ │ ├── MyInputResource.java │ │ ├── MyOutputResource.java │ │ └── RestfulWebServiceController.java │ └── resources │ └── templates │ ├── failure.html │ ├── login.html │ └── success.html ├── spring-security ├── README.md ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── stackify │ │ └── guest │ │ └── springsecurity │ │ ├── Application.java │ │ └── config │ │ ├── WebMvcConfiguration.java │ │ └── WebSecurityConfig.java │ └── resources │ ├── data.sql │ ├── schema.sql │ ├── static │ └── css │ │ └── styles.css │ └── templates │ ├── customLogin.html │ └── index.html ├── thread-pools ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── stackify │ ├── models │ └── Employee.java │ ├── services │ └── EmployeeService.java │ └── threadpools │ ├── FactorialTask.java │ └── ThreadsApplication.java ├── tomcat-app ├── WebContent │ ├── META-INF │ │ └── MANIFEST.MF │ └── WEB-INF │ │ └── web.xml ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── stackify │ ├── ApplicationInitializer.java │ ├── daos │ └── UserDAO.java │ ├── models │ └── User.java │ ├── services │ ├── CorsFilter.java │ └── UserService.java │ └── utils │ └── ConnectionUtil.java └── webservices ├── pom.xml ├── rest-client ├── WebContent │ └── META-INF │ │ └── MANIFEST.MF ├── pom.xml └── rest-client │ ├── .angular-cli.json │ ├── .editorconfig │ ├── .gitignore │ ├── README.md │ ├── e2e │ ├── app.e2e-spec.ts │ ├── app.po.ts │ └── tsconfig.e2e.json │ ├── karma.conf.js │ ├── package.json │ ├── protractor.conf.js │ ├── src │ ├── app │ │ ├── app.component.css │ │ ├── app.component.html │ │ ├── app.component.spec.ts │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── app.service.ts │ │ ├── users.component.html │ │ └── users.component.ts │ ├── assets │ │ └── .gitkeep │ ├── environments │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── favicon.ico │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── styles.css │ ├── test.ts │ ├── tsconfig.app.json │ ├── tsconfig.spec.json │ └── typings.d.ts │ ├── tsconfig.json │ └── tslint.json ├── rest-server ├── WebContent │ ├── META-INF │ │ └── MANIFEST.MF │ └── WEB-INF │ │ └── web.xml ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── stackify │ │ ├── ApplicationInitializer.java │ │ ├── models │ │ └── User.java │ │ └── services │ │ ├── CorsFilter.java │ │ └── UserService.java │ └── test │ └── java │ └── com │ └── stackify │ └── services │ └── UserServiceTest.java ├── soap_client └── src │ └── main │ └── java │ └── com │ └── stackify │ ├── JAXWSClient.java │ └── services │ ├── DefaultUserImplService.java │ ├── ObjectFactory.java │ ├── User.java │ ├── UserService.java │ ├── Users.java │ └── package-info.java ├── soap_example └── src │ └── main │ └── java │ └── com │ └── stackify │ ├── ServicePublisher.java │ ├── models │ ├── User.java │ └── Users.java │ └── services │ ├── DefaultUserImpl.java │ └── UserService.java └── spring-rest-service ├── WebContent └── META-INF │ └── MANIFEST.MF ├── pom.xml └── src └── main └── java └── com └── stackify ├── Application.java ├── config └── SwaggerConfig.java ├── controllers └── UserController.java └── models └── User.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | logs/ 7 | log.html 8 | 9 | # BlueJ files 10 | *.ctxt 11 | 12 | # Mobile Tools for Java (J2ME) 13 | .mtj.tmp/ 14 | 15 | *.iml 16 | .idea/ 17 | 18 | # Package Files # 19 | *.jar 20 | *.war 21 | *.ear 22 | *.zip 23 | *.tar.gz 24 | *.rar 25 | 26 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 27 | hs_err_pid* 28 | 29 | # Eclipse 30 | .settings/ 31 | *.project 32 | *.classpath 33 | .prefs 34 | *.prefs 35 | .metadata/ 36 | 37 | # Intellij 38 | .idea/ 39 | *.iml 40 | *.iws 41 | 42 | # Maven 43 | log/ 44 | target/ -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | before_install: 4 | - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:-UseGCOverheadLimit'" > ~/.mavenrc 5 | 6 | install: skip 7 | script: travis_wait 60 mvn -q test -fae 8 | 9 | sudo: required 10 | 11 | jdk: 12 | - oraclejdk9 13 | 14 | addons: 15 | apt: 16 | packages: 17 | - oracle-java9-installer 18 | 19 | cache: 20 | directories: 21 | - .autoconf 22 | - $HOME/.m2 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Relevant articles: 2 | -------------------------------------------------------------------------------- /core-java-9/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | com.stackify 4 | core-java-9 5 | 0.0.1-SNAPSHOT 6 | 7 | 8 | com.stackify 9 | parent-module 10 | 1.0.0-SNAPSHOT 11 | 12 | 13 | 14 | 15 | junit 16 | junit 17 | ${junit.version} 18 | 19 | 20 | 21 | 22 | 23 | 24 | maven-compiler-plugin 25 | ${maven-compiler-plugin.version} 26 | 27 | ${maven.compiler.source} 28 | ${maven.compiler.target} 29 | 30 | 31 | 32 | 33 | 34 | 35 | 1.9 36 | 1.9 37 | 38 | 39 | -------------------------------------------------------------------------------- /core-java-9/src/main/java/com/stackify/optional/User.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optional; 2 | 3 | public class User { 4 | private String email; 5 | private String password; 6 | 7 | public User(String email, String password) { 8 | super(); 9 | this.email = email; 10 | this.password = password; 11 | } 12 | 13 | public String getEmail() { 14 | return email; 15 | } 16 | 17 | public void setEmail(String email) { 18 | this.email = email; 19 | } 20 | 21 | public String getPassword() { 22 | return password; 23 | } 24 | 25 | public void setPassword(String password) { 26 | this.password = password; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /core-java-9/src/test/java/com/stackify/optional/OptionalTest.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optional; 2 | 3 | import org.junit.Test; 4 | import java.util.Optional; 5 | import java.util.List; 6 | 7 | import static org.junit.Assert.*; 8 | import java.util.stream.Collectors; 9 | 10 | public class OptionalTest { 11 | 12 | private User user; 13 | 14 | @Test 15 | public void whenEmptyOptional_thenGetValueFromOr() { 16 | User result = Optional.ofNullable(user) 17 | .or( () -> Optional.of(new User("default","1234"))).get(); 18 | 19 | assertEquals(result.getEmail(), "default"); 20 | } 21 | 22 | @Test 23 | public void whenIfPresentOrElse_thenOk() { 24 | Optional.ofNullable(user) 25 | .ifPresentOrElse( u -> System.out.println("User is:" + u.getEmail()), () -> System.out.println("User not found")); 26 | } 27 | 28 | @Test 29 | public void whenGetStream_thenOk() { 30 | User user = new User("john@gmail.com", "1234"); 31 | List emails = Optional.ofNullable(user) 32 | .stream() 33 | .filter(u -> u.getEmail() != null && u.getEmail().contains("@")) 34 | .map( u -> u.getEmail()) 35 | .collect(Collectors.toList()); 36 | 37 | assertTrue(emails.size() == 1); 38 | assertEquals(emails.get(0), user.getEmail()); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /core-java/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.stackify 5 | core-java 6 | 0.0.1-SNAPSHOT 7 | core-java 8 | 9 | 10 | com.stackify 11 | parent-module 12 | 1.0.0-SNAPSHOT 13 | 14 | 15 | 16 | 17 | junit 18 | junit 19 | ${junit.version} 20 | 21 | 22 | org.apache.logging.log4j 23 | log4j-core 24 | ${log4j2.version} 25 | 26 | 27 | org.hamcrest 28 | hamcrest-core 29 | ${org.hamcrest.version} 30 | test 31 | 32 | 33 | org.hamcrest 34 | hamcrest-library 35 | ${org.hamcrest.version} 36 | test 37 | 38 | 39 | org.hamcrest 40 | hamcrest-all 41 | ${org.hamcrest.version} 42 | test 43 | 44 | 45 | org.assertj 46 | assertj-core 47 | ${assertj.version} 48 | test 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.apache.maven.plugins 56 | maven-compiler-plugin 57 | ${maven-compiler-plugin.version} 58 | 59 | ${maven.compiler.source.version} 60 | ${maven.compiler.target.version} 61 | 62 | 63 | 64 | 65 | 66 | 67 | 2.8.2 68 | 1.3 69 | 3.6.1 70 | 1.8 71 | 1.8 72 | 73 | 74 | -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/optional/Address.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optional; 2 | 3 | public class Address { 4 | private String addressLine; 5 | private String city; 6 | private Country country; 7 | 8 | public Address(String addressLine, String city, Country country) { 9 | super(); 10 | this.addressLine = addressLine; 11 | this.city = city; 12 | this.country = country; 13 | } 14 | 15 | public String getAddressLine() { 16 | return addressLine; 17 | } 18 | 19 | public void setAddressLine(String addressLine) { 20 | this.addressLine = addressLine; 21 | } 22 | 23 | public String getCity() { 24 | return city; 25 | } 26 | 27 | public void setCity(String city) { 28 | this.city = city; 29 | } 30 | 31 | public Country getCountry() { 32 | return country; 33 | } 34 | 35 | public void setCountry(Country country) { 36 | this.country = country; 37 | } 38 | 39 | 40 | } 41 | -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/optional/Country.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optional; 2 | 3 | public class Country { 4 | private String name; 5 | private String isocode; 6 | 7 | public Country(String name, String isocode) { 8 | super(); 9 | this.name = name; 10 | this.isocode = isocode; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | 21 | public String getIsocode() { 22 | return isocode; 23 | } 24 | 25 | public void setIsocode(String isocode) { 26 | this.isocode = isocode; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/optional/User.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optional; 2 | 3 | import java.util.Optional; 4 | 5 | public class User { 6 | private String email; 7 | private String password; 8 | 9 | private Address address; 10 | 11 | private String position; 12 | 13 | public User(String email, String password) { 14 | super(); 15 | this.email = email; 16 | this.password = password; 17 | } 18 | 19 | public String getEmail() { 20 | return email; 21 | } 22 | 23 | public void setEmail(String email) { 24 | this.email = email; 25 | } 26 | 27 | public String getPassword() { 28 | return password; 29 | } 30 | 31 | public void setPassword(String password) { 32 | this.password = password; 33 | } 34 | 35 | public Address getAddress() { 36 | return address; 37 | } 38 | 39 | public void setAddress(Address address) { 40 | this.address = address; 41 | } 42 | 43 | public Optional getPosition() { 44 | return Optional.ofNullable(position); 45 | } 46 | 47 | public void setPosition(String position) { 48 | this.position = position; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/optional/chaining/Address.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optional.chaining; 2 | 3 | import java.util.Optional; 4 | 5 | public class Address { 6 | private String addressLine; 7 | private String city; 8 | private Country country; 9 | 10 | public Address(String addressLine, String city) { 11 | this.addressLine = addressLine; 12 | this.city = city; 13 | } 14 | 15 | public String getAddressLine() { 16 | return addressLine; 17 | } 18 | 19 | public void setAddressLine(String addressLine) { 20 | this.addressLine = addressLine; 21 | } 22 | 23 | public String getCity() { 24 | return city; 25 | } 26 | 27 | public void setCity(String city) { 28 | this.city = city; 29 | } 30 | 31 | public Optional getCountry() { 32 | return Optional.ofNullable(country); 33 | } 34 | 35 | public void setCountry(Country country) { 36 | this.country = country; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/optional/chaining/Country.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optional.chaining; 2 | 3 | public class Country { 4 | private String name; 5 | private String isocode; 6 | 7 | public Country(String name) { 8 | this.name = name; 9 | } 10 | 11 | public String getName() { 12 | return name; 13 | } 14 | 15 | public void setName(String name) { 16 | this.name = name; 17 | } 18 | 19 | public String getIsocode() { 20 | return isocode; 21 | } 22 | 23 | public void setIsocode(String isocode) { 24 | this.isocode = isocode; 25 | } 26 | 27 | 28 | } -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/optional/chaining/User.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optional.chaining; 2 | 3 | import java.util.Optional; 4 | 5 | public class User { 6 | private String email; 7 | private String password; 8 | 9 | private Address address; 10 | 11 | private String position; 12 | 13 | public User(String email, String password) { 14 | this.email = email; 15 | this.password = password; 16 | } 17 | 18 | public String getEmail() { 19 | return email; 20 | } 21 | 22 | public void setEmail(String email) { 23 | this.email = email; 24 | } 25 | 26 | public String getPassword() { 27 | return password; 28 | } 29 | 30 | public void setPassword(String password) { 31 | this.password = password; 32 | } 33 | 34 | public Optional
getAddress() { 35 | return Optional.ofNullable(address); 36 | } 37 | 38 | public void setAddress(Address address) { 39 | this.address = address; 40 | } 41 | 42 | public Optional getPosition() { 43 | return Optional.ofNullable(position); 44 | } 45 | 46 | public void setPosition(String position) { 47 | this.position = position; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/optionalparams/MultiVitamin.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optionalparams; 2 | 3 | public class MultiVitamin { 4 | 5 | private String name; // required 6 | private int vitaminA; // in mcg 7 | private int vitaminC; // in mg 8 | private int calcium; // in mg 9 | private int iron; // in mg 10 | 11 | public MultiVitamin(String name) { 12 | this.name = name; 13 | } 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public int getVitaminA() { 20 | return vitaminA; 21 | } 22 | 23 | public void setVitaminA(int vitaminA) { 24 | this.vitaminA = vitaminA; 25 | } 26 | 27 | public int getVitaminC() { 28 | return vitaminC; 29 | } 30 | 31 | public void setVitaminC(int vitaminC) { 32 | this.vitaminC = vitaminC; 33 | } 34 | 35 | public int getCalcium() { 36 | return calcium; 37 | } 38 | 39 | public void setCalcium(int calcium) { 40 | this.calcium = calcium; 41 | } 42 | 43 | public int getIron() { 44 | return iron; 45 | } 46 | 47 | public void setIron(int iron) { 48 | this.iron = iron; 49 | } 50 | } -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/optionalparams/MultiVitaminAllowingNulls.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optionalparams; 2 | 3 | public class MultiVitaminAllowingNulls { 4 | 5 | private String name; // required 6 | private Integer vitaminA; // in mcg 7 | private Integer vitaminC; // in mg 8 | private Integer calcium; // in mg 9 | private Integer iron; // in mg 10 | 11 | public MultiVitaminAllowingNulls(String name, Integer vitaminA, Integer vitaminC, Integer calcium, Integer iron) { 12 | this.name = name; 13 | this.vitaminA = vitaminA; 14 | this.vitaminC = vitaminC; 15 | this.calcium = calcium; 16 | this.iron = iron; 17 | } 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public Integer getVitaminA() { 24 | return vitaminA; 25 | } 26 | 27 | public Integer getVitaminC() { 28 | return vitaminC; 29 | } 30 | 31 | public Integer getCalcium() { 32 | return calcium; 33 | } 34 | 35 | public Integer getIron() { 36 | return iron; 37 | } 38 | } -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/optionalparams/MultiVitaminOverloading.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optionalparams; 2 | 3 | public class MultiVitaminOverloading { 4 | 5 | static final int DEFAULT_IRON_AMOUNT = 20; 6 | 7 | private final String name; // required 8 | private final int vitaminA; // in mcg 9 | private final int vitaminC; // in mg 10 | private final int calcium; // in mg 11 | private final int iron; // in mg 12 | 13 | public MultiVitaminOverloading(String name) { 14 | this(name, 0); 15 | } 16 | 17 | public MultiVitaminOverloading(String name, int vitaminA) { 18 | this(name, vitaminA, 0); 19 | } 20 | 21 | public MultiVitaminOverloading(String name, int vitaminA, int vitaminC) { 22 | this(name, vitaminA, vitaminC, 0); 23 | } 24 | 25 | public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium) { 26 | this(name, vitaminA, vitaminC, calcium, DEFAULT_IRON_AMOUNT); 27 | } 28 | 29 | public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium, int iron) { 30 | this.name = name; 31 | this.vitaminA = vitaminA; 32 | this.vitaminC = vitaminC; 33 | this.calcium = calcium; 34 | this.iron = iron; 35 | } 36 | 37 | public String getName() { 38 | return name; 39 | } 40 | 41 | public int getVitaminA() { 42 | return vitaminA; 43 | } 44 | 45 | public int getVitaminC() { 46 | return vitaminC; 47 | } 48 | 49 | public int getCalcium() { 50 | return calcium; 51 | } 52 | 53 | public int getIron() { 54 | return iron; 55 | } 56 | } -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/optionalparams/MultiVitaminStaticFactoryMethods.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optionalparams; 2 | 3 | public class MultiVitaminStaticFactoryMethods { 4 | 5 | static final int IRON_AMT_DEF = 20; 6 | static final int IRON_AMT_MEN = 30; 7 | 8 | static final int CALCIUM_AMT_DEF = 100; 9 | static final int CALCIUM_AMT_WOMEN = 120; 10 | 11 | private final String name; // required 12 | private final int vitaminA; // in mcg 13 | private final int vitaminC; // in mg 14 | private final int calcium; // in mg 15 | private final int iron; // in mg 16 | 17 | public static MultiVitaminStaticFactoryMethods forMen(String name) { 18 | return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_DEF, IRON_AMT_MEN); 19 | } 20 | 21 | public static MultiVitaminStaticFactoryMethods forWomen(String name) { 22 | return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_WOMEN, IRON_AMT_DEF); 23 | } 24 | 25 | private MultiVitaminStaticFactoryMethods(String name, int vitaminA, int vitaminC, int calcium, int iron) { 26 | this.name = name; 27 | this.vitaminA = vitaminA; 28 | this.vitaminC = vitaminC; 29 | this.calcium = calcium; 30 | this.iron = iron; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public int getVitaminA() { 38 | return vitaminA; 39 | } 40 | 41 | public int getVitaminC() { 42 | return vitaminC; 43 | } 44 | 45 | public int getCalcium() { 46 | return calcium; 47 | } 48 | 49 | public int getIron() { 50 | return iron; 51 | } 52 | } -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/optionalparams/MultiVitaminWithBuilder.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optionalparams; 2 | 3 | public class MultiVitaminWithBuilder { 4 | 5 | private final String name; // required 6 | private final int vitaminA; // in mcg 7 | private final int vitaminC; // in mg 8 | private final int calcium; // in mg 9 | private final int iron; // in mg 10 | 11 | private MultiVitaminWithBuilder(MultiVitaminBuilder builder) { 12 | this.name = builder.name; 13 | this.vitaminA = builder.vitaminA; 14 | this.vitaminC = builder.vitaminC; 15 | this.calcium = builder.calcium; 16 | this.iron = builder.iron; 17 | } 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public int getVitaminA() { 24 | return vitaminA; 25 | } 26 | 27 | public int getVitaminC() { 28 | return vitaminC; 29 | } 30 | 31 | public int getCalcium() { 32 | return calcium; 33 | } 34 | 35 | public int getIron() { 36 | return iron; 37 | } 38 | 39 | public static class MultiVitaminBuilder { 40 | 41 | private static final int ZERO = 0; 42 | 43 | private final String name; // required 44 | private int vitaminA = ZERO; 45 | private int vitaminC = ZERO; 46 | private int calcium = ZERO; 47 | private int iron = ZERO; 48 | 49 | public MultiVitaminBuilder(String name) { 50 | this.name = name; 51 | } 52 | 53 | public MultiVitaminBuilder withVitaminA(int vitaminA) { 54 | this.vitaminA = vitaminA; 55 | return this; 56 | } 57 | 58 | public MultiVitaminBuilder withVitaminC(int vitaminC) { 59 | this.vitaminC = vitaminC; 60 | return this; 61 | } 62 | 63 | public MultiVitaminBuilder withCalcium(int calcium) { 64 | this.calcium = calcium; 65 | return this; 66 | } 67 | 68 | public MultiVitaminBuilder withIron(int iron) { 69 | this.iron = iron; 70 | return this; 71 | } 72 | 73 | public MultiVitaminWithBuilder build() { 74 | return new MultiVitaminWithBuilder(this); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/stream/Employee.java: -------------------------------------------------------------------------------- 1 | package com.stackify.stream; 2 | 3 | public class Employee { 4 | private Integer id; 5 | private String name; 6 | private Double salary; 7 | 8 | public Employee(Integer id, String name, Double salary) { 9 | this.id = id; 10 | this.name = name; 11 | this.salary = salary; 12 | } 13 | 14 | public Integer getId() { 15 | return id; 16 | } 17 | 18 | public void setId(Integer id) { 19 | this.id = id; 20 | } 21 | 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public void setName(String name) { 27 | this.name = name; 28 | } 29 | 30 | public Double getSalary() { 31 | return salary; 32 | } 33 | 34 | public void setSalary(Double salary) { 35 | this.salary = salary; 36 | } 37 | 38 | public void salaryIncrement(Double percentage) { 39 | Double newSalary = salary + percentage * salary / 100; 40 | setSalary(newSalary); 41 | } 42 | 43 | public String toString() { 44 | return "Id: " + id + " Name:" + name + " Price:" + salary; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /core-java/src/main/java/com/stackify/stream/EmployeeRepository.java: -------------------------------------------------------------------------------- 1 | package com.stackify.stream; 2 | 3 | import java.util.List; 4 | 5 | public class EmployeeRepository { 6 | private List empList; 7 | 8 | public EmployeeRepository(List empList) { 9 | this.empList = empList; 10 | 11 | } 12 | public Employee findById(Integer id) { 13 | for (Employee emp : empList) { 14 | if (emp.getId() == id) { 15 | return emp; 16 | } 17 | } 18 | 19 | return null; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /core-java/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /core-java/src/test/java/com/stackify/optional/chaining/OptionalChainingTest.java: -------------------------------------------------------------------------------- 1 | package com.stackify.optional.chaining; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.Optional; 6 | 7 | import org.junit.Test; 8 | 9 | public class OptionalChainingTest { 10 | 11 | @Test 12 | public void whenChaining_thenOk() { 13 | User user = new User("anna@gmail.com", "1234"); 14 | 15 | String result = Optional.ofNullable(user) 16 | .flatMap(u -> u.getAddress()) 17 | .flatMap(a -> a.getCountry()) 18 | .map(c -> c.getIsocode()) 19 | .orElse("default"); 20 | 21 | assertEquals(result, "default"); 22 | } 23 | 24 | @Test 25 | public void whenChainingWithMethodReferences_thenOk() { 26 | User user = new User("anna@gmail.com", "1234"); 27 | 28 | String result = Optional.ofNullable(user) 29 | .flatMap(User::getAddress) 30 | .flatMap(Address::getCountry) 31 | .map(Country::getIsocode) 32 | .orElse("default"); 33 | 34 | assertEquals(result, "default"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /core-java/src/test/resources/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/stackify/8e84872a1d27a10d08b75fdbcceff092e74637dc/core-java/src/test/resources/.keep -------------------------------------------------------------------------------- /core-kotlin/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | 3 | #ignore gradle 4 | .gradle/ 5 | 6 | 7 | #ignore build and generated files 8 | build/ 9 | node/ 10 | out/ 11 | 12 | #ignore installed node modules and package lock file 13 | node_modules/ 14 | package-lock.json 15 | -------------------------------------------------------------------------------- /core-kotlin/src/test/kotlin/com/stackify/kotlinvsjava/CompanionObjectTest.kt: -------------------------------------------------------------------------------- 1 | package com.stackify.kotlinvsjava 2 | 3 | import org.junit.Test 4 | import kotlin.test.assertEquals 5 | 6 | class CompanionObjectTest { 7 | 8 | @Test 9 | fun givenAClassWithCompanionObject_whenCallingMethodTheSameAsStaticOne_thenWeGetAResult() { 10 | assertEquals("A", A.returnClassName()) 11 | } 12 | 13 | } 14 | 15 | class A { 16 | companion object { 17 | fun returnClassName(): String { 18 | return "A" 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /core-kotlin/src/test/kotlin/com/stackify/kotlinvsjava/ConstructorTest.kt: -------------------------------------------------------------------------------- 1 | package com.stackify.kotlinvsjava 2 | 3 | import org.junit.Test 4 | import kotlin.test.assertEquals 5 | 6 | class ConstructorTests { 7 | 8 | @Test 9 | fun givenAClassWithPrimaryConstructor_whenCreatingAnInstance_thenWeGetObject() { 10 | var example = Example(1, "Example") 11 | 12 | assertEquals(1, example.id) 13 | assertEquals("Example", example.name) 14 | } 15 | 16 | } 17 | 18 | class Example constructor(val id: Int, var name: String) -------------------------------------------------------------------------------- /core-kotlin/src/test/kotlin/com/stackify/kotlinvsjava/DataClassTest.kt: -------------------------------------------------------------------------------- 1 | package com.stackify.kotlinvsjava 2 | 3 | import org.junit.Test 4 | import kotlin.test.assertEquals 5 | import kotlin.test.assertFalse 6 | 7 | class DataClassTest { 8 | 9 | @Test 10 | fun givenASampleDataClass_whenCallingToStringMethod_thenItReturnsAllProperties() { 11 | val student = Student(1, "John", "Smith") 12 | 13 | assertEquals(1, student.id) 14 | assertEquals("John", student.name) 15 | assertEquals("Smith", student.lastName) 16 | assertEquals("Student(id=1, name=John, lastName=Smith)", student.toString()) 17 | } 18 | 19 | @Test 20 | fun givenASampleDataClass_whenCreatingACopyWithGeneratedFunction_thenItReturnsACopyWithRequestedChanges() { 21 | val student = Student(1, "John", "Smith") 22 | val student2 = student.copy(id = 2, name = "Anne") 23 | 24 | assertEquals(2, student2.id) 25 | assertEquals("Anne", student2.name) 26 | assertEquals("Smith", student2.lastName) 27 | assertEquals("Student(id=2, name=Anne, lastName=Smith)", student2.toString()) 28 | assertFalse(student.equals(student2)) 29 | } 30 | 31 | } 32 | 33 | data class Student(val id: Int, val name: String, val lastName: String) -------------------------------------------------------------------------------- /core-kotlin/src/test/kotlin/com/stackify/kotlinvsjava/DelegationTest.kt: -------------------------------------------------------------------------------- 1 | package com.stackify.kotlinvsjava 2 | 3 | import org.junit.Test 4 | import kotlin.test.assertEquals 5 | 6 | class DelegationTest { 7 | 8 | @Test 9 | fun givenAClassWithDelegation_whenCallDelegatedMethod_thenWeGetAResultDefinedInPassedObject() { 10 | val car = Car(V6Engine()) 11 | 12 | assertEquals("Vroom", car.makeSound()) 13 | } 14 | 15 | } 16 | 17 | interface Engine { 18 | fun makeSound(): String 19 | } 20 | 21 | class V6Engine: Engine { 22 | override fun makeSound(): String { 23 | return "Vroom" 24 | } 25 | } 26 | 27 | class Car(e: Engine) : Engine by e -------------------------------------------------------------------------------- /core-kotlin/src/test/kotlin/com/stackify/kotlinvsjava/ExceptionsTest.kt: -------------------------------------------------------------------------------- 1 | package com.stackify.kotlinvsjava 2 | 3 | import java.io.IOException 4 | import kotlin.test.Test 5 | import kotlin.test.assertEquals 6 | 7 | class ExceptionsTest { 8 | 9 | @Test 10 | fun givenATryExpression_whenReturning5InLastExpressionOfTryBlock_thenWeGet5() { 11 | val value: Int = try { 5 } catch (e: IOException) { 6 } 12 | 13 | assertEquals(5, value) 14 | } 15 | 16 | @Test 17 | fun givenATryExpression_whenReturning6InLastExpressionOfCatchBlock_thenWeGet6() { 18 | val value: Int = try { funThrowingException() } catch (e: IOException) { 6 } 19 | 20 | assertEquals(6, value) 21 | } 22 | 23 | @org.junit.Test(expected = IllegalArgumentException::class) 24 | fun givenANullString_whenUsingElvisOperator_thenExceptionIsThrown() { 25 | val sampleString: String? = null 26 | 27 | sampleString?.length ?: throw IllegalArgumentException("String must not be null") 28 | } 29 | 30 | private fun funThrowingException(): Nothing { 31 | throw IOException() 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /core-kotlin/src/test/kotlin/com/stackify/kotlinvsjava/ExtensionFunctionsTest.kt: -------------------------------------------------------------------------------- 1 | package com.stackify.kotlinvsjava 2 | 3 | import org.junit.Test 4 | import kotlin.test.assertEquals 5 | 6 | class ExtensionFunctionsTest { 7 | 8 | @Test 9 | fun givenAStringWithAnExtensionFunction_whenCallingThatFunction_thenItConcatenatesStrings() { 10 | val sampleString = "ABC" 11 | val concatenatedString = sampleString.appendString("DEF") 12 | 13 | assertEquals("ABCDEF", concatenatedString) 14 | } 15 | 16 | @Test 17 | fun givenAStringWithAnExtensionProperty_whenReadingProperty_thenItReturnsLengthOfString() { 18 | val sampleString = "ABC" 19 | 20 | assertEquals(3, sampleString.size) 21 | } 22 | 23 | fun String.appendString(str : String): String { 24 | return plus(str) 25 | } 26 | 27 | val String.size: Int 28 | get() = length 29 | 30 | } -------------------------------------------------------------------------------- /core-kotlin/src/test/kotlin/com/stackify/kotlinvsjava/FunctionsTest.kt: -------------------------------------------------------------------------------- 1 | package com.stackify.kotlinvsjava 2 | 3 | import org.junit.Test 4 | import kotlin.test.assertEquals 5 | 6 | class FunctionsTest { 7 | 8 | @Test 9 | fun givenALambdaExpressionConcatenatingString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() { 10 | val concat: (String, String) -> String = { a, b -> a + b } 11 | 12 | assertEquals("AB", concat("A","B")) 13 | } 14 | 15 | @Test 16 | fun givenAnAnonymousFunctionConcatenatingString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() { 17 | val concat: (String, String) -> String = fun(a: String, b: String): String { return a + b } 18 | 19 | assertEquals("AB", concat("A","B")) 20 | } 21 | 22 | @Test 23 | fun givenAnPlusMethodOfString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() { 24 | val concat = String::plus 25 | 26 | assertEquals("AB", concat("A","B")) 27 | } 28 | 29 | @Test 30 | fun givenAStringConstractorAssignedToFunction_whenUsingFunctionReference_thenWeGetNewString() { 31 | val concat = ::String 32 | 33 | assertEquals("A", concat().plus("A")) 34 | } 35 | 36 | @Test 37 | fun givenAClassImplementingAFunctionType_whenUsingTheFunctionWithAAndBString_thenWeGetAB() { 38 | val concat = StringConcatenation() 39 | 40 | assertEquals("AB", concat("A", "B")) 41 | } 42 | 43 | @Test 44 | fun givenALambdaExpressionWithReceiver_whenUsingTheFunctionWithReceiver_thenWeGetABC() { 45 | val concat: String.(String, String) -> String = { a, b -> plus(a).plus(b) } 46 | 47 | assertEquals("ABC", "A".concat("B", "C")) 48 | } 49 | 50 | @Test 51 | fun givenALambdaExpressionWithinLambdaExpression_whenUsingTheFunction_thenWeGetAB() { 52 | val concat: (String) -> ((String) -> String) = { a -> {b -> a + b} } 53 | 54 | assertEquals("AB", (concat("A")("B"))) 55 | } 56 | 57 | @Test 58 | fun given3NestedLambdaExpression_whenUsingTheFunction_thenWeGetABC() { 59 | val concat: (String) -> (String) -> (String) -> String = { a -> {b -> { c -> a + b + c} } } 60 | 61 | assertEquals("ABC", concat("A")("B")("C")) 62 | } 63 | 64 | } 65 | 66 | class StringConcatenation: (String, String) -> String { 67 | override fun invoke(p1: String, p2: String): String { 68 | return p1 + p2 69 | } 70 | } -------------------------------------------------------------------------------- /core-kotlin/src/test/kotlin/com/stackify/kotlinvsjava/IsOperatorTest.kt: -------------------------------------------------------------------------------- 1 | package com.stackify.kotlinvsjava 2 | 3 | import org.junit.Test 4 | import kotlin.math.absoluteValue 5 | import kotlin.test.assertEquals 6 | import kotlin.test.assertTrue 7 | 8 | class IsOperatorTest { 9 | 10 | @Test 11 | fun givenSampleValue_whenUsingIsOperatorInIfStatement_thenItCastsAutomaticallyToString() { 12 | val value: Any = "string" 13 | 14 | if(value is String) { 15 | assertEquals(6, value.length) 16 | } 17 | } 18 | 19 | @Test 20 | fun givenSampleValue_whenUsingIsOperatorWithAndOperator_thenItCastsAutomaticallyToString() { 21 | val value: Any = "string" 22 | 23 | assertTrue(value is String && value.length == 6) 24 | } 25 | 26 | @Test 27 | fun givenSampleValue_whenUsingWithWhenOperator_thenItCastsAutomaticallyToString() { 28 | val value: Any = "string" 29 | 30 | when(value) { 31 | is String -> assertEquals(6, value.length) 32 | is Int -> assertEquals(6, value.absoluteValue) 33 | } 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /core-kotlin/src/test/kotlin/com/stackify/kotlinvsjava/NullSafetyTest.kt: -------------------------------------------------------------------------------- 1 | package com.stackify.kotlinvsjava 2 | 3 | import kotlin.test.Test 4 | import java.lang.NullPointerException 5 | import kotlin.test.assertEquals 6 | import kotlin.test.assertNotNull 7 | import kotlin.test.assertNull 8 | 9 | class NullSafetyTest { 10 | 11 | @Test 12 | fun givenStringAndNull_whenUsingSafeCallOperatorWithLengthMethod_thenReturnsLengthForStringAndNullForNull() { 13 | val stringValue: String? = "string" 14 | val nullValue: String? = null 15 | 16 | assertNotNull(stringValue?.length) 17 | assertNull(nullValue?.length) 18 | } 19 | 20 | @Test(expected = NullPointerException::class) 21 | fun givenNullReference_whenUsingTheNotNullAssertionOperator_thenItThrowsNullPointerException() { 22 | val stringValue: String? = "string" 23 | val nullValue: String? = null 24 | 25 | assertNotNull(stringValue!!.length) 26 | nullValue!!.length 27 | } 28 | 29 | @Test 30 | fun givenStringAndNull_whenUsingElvisOperator_thenItTestsAgainstNullAndReturnsTheProperValue() { 31 | val stringValue: String? = "string" 32 | val nullValue: String? = null 33 | 34 | val shouldBeLength: Int = stringValue?.length ?: -1 35 | val souldBeMinusOne: Int = nullValue?.length ?: -1 36 | 37 | assertEquals(6, shouldBeLength) 38 | assertEquals(-1, souldBeMinusOne) 39 | } 40 | 41 | @Test 42 | fun givenString_whenCastingToInt_thenItReturnsNull() { 43 | val stringValue: String? = "string" 44 | 45 | val intValue: Int? = stringValue as? Int 46 | 47 | assertNull(intValue) 48 | } 49 | 50 | @Test 51 | fun givenCollectionWithNulls_whenFilterNonNull_thenItReturnsCollectionWithoutNulls() { 52 | val list: List = listOf("a", "b", null) 53 | val nonNullList = list.filterNotNull() 54 | 55 | assertEquals(2, nonNullList.size) 56 | assertEquals(nonNullList, listOf("a", "b")) 57 | } 58 | 59 | @Test 60 | fun givenCollectionWithNulls_whenLetWithSafeCallOperator_thenItOmitsNulls() { 61 | val list: List = listOf("a", "b", null) 62 | for(elem in list) { 63 | elem?.let { assertNotNull(it) } 64 | } 65 | } 66 | 67 | } -------------------------------------------------------------------------------- /core-kotlin/src/test/kotlin/com/stackify/kotlinvsjava/OperatorsOverloadingTest.kt: -------------------------------------------------------------------------------- 1 | package com.stackify.kotlinvsjava 2 | 3 | import org.junit.Test 4 | import kotlin.test.assertEquals 5 | import kotlin.test.assertTrue 6 | 7 | class OperatorsOverloadingTest { 8 | 9 | @Test 10 | fun givenThePlaneClassWithOverloadedIncrementationOperator_whenCallingTheOperator_thenItIncreasesSpeed(){ 11 | var plane = Plane(0.0) 12 | 13 | plane++ 14 | assertEquals(50.0, plane.currentSpeed) 15 | } 16 | 17 | @Test 18 | fun givenThePlaneClassWithOverloadedMinusOperator_whenCallingTheOperator_thenItDecreaseSpeed(){ 19 | var plane = Plane(1000.0) 20 | 21 | plane - 500.0 22 | assertEquals(500.0, plane.currentSpeed) 23 | } 24 | 25 | @Test 26 | fun givenThePlaneClassWithOverloadedInvokeOperator_whenCallingTheOperator_thenItSetSpeed(){ 27 | var plane = Plane(0.0) 28 | 29 | plane(150.0) 30 | assertEquals(150.0, plane.currentSpeed) 31 | } 32 | 33 | @Test 34 | fun given2PlaneObjectWithOverloadedComparisonOperator_whenCallingTheOperator_thenItComparesSpeedValues(){ 35 | var plane = Plane(0.0) 36 | var plane2 = Plane(150.0) 37 | 38 | assertTrue(plane < (plane2)) 39 | } 40 | 41 | } 42 | 43 | class Plane(var currentSpeed: Double) { 44 | 45 | operator fun inc(): Plane { 46 | currentSpeed += 50.0 47 | return this 48 | } 49 | 50 | operator fun minus(number: Double) { 51 | currentSpeed = if(currentSpeed < number) 0.0 else currentSpeed - number 52 | } 53 | 54 | operator fun invoke(speed: Double) { 55 | currentSpeed = speed 56 | } 57 | 58 | operator fun compareTo(plane: Plane): Int { 59 | return currentSpeed.compareTo(plane.currentSpeed) 60 | } 61 | } -------------------------------------------------------------------------------- /core-kotlin/src/test/kotlin/com/stackify/kotlinvsjava/PropertiesTest.kt: -------------------------------------------------------------------------------- 1 | package com.stackify.kotlinvsjava 2 | 3 | import org.junit.Test 4 | import java.math.BigDecimal 5 | import kotlin.test.assertEquals 6 | 7 | class PropertiesTest { 8 | 9 | @Test 10 | fun givenASampleClassWithValAndVarProperties_whenSettingPrice_thenWeGetZeroOrOne() { 11 | val product = Product() 12 | product.price = BigDecimal(10) 13 | 14 | val product2 = Product() 15 | product2.price = null 16 | 17 | assertEquals("empty", product.id) 18 | assertEquals("empty", product2.id) 19 | assertEquals(BigDecimal(10), product.price) 20 | assertEquals(BigDecimal(1), product2.price) 21 | } 22 | 23 | } 24 | 25 | class Product { 26 | 27 | val id: String? = "empty" 28 | 29 | var price: BigDecimal? = BigDecimal.ZERO 30 | set(value) = if(value == null) { field = BigDecimal.ONE} else { field = value } 31 | 32 | } -------------------------------------------------------------------------------- /deep-jsf/.settings/.jsdtscope: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /deep-jsf/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /deep-jsf/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /deep-jsf/.settings/org.eclipse.wst.common.component: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /deep-jsf/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /deep-jsf/.settings/org.eclipse.wst.common.project.facet.core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /deep-jsf/.settings/org.eclipse.wst.jsdt.ui.superType.container: -------------------------------------------------------------------------------- 1 | org.eclipse.wst.jsdt.launching.baseBrowserLibrary -------------------------------------------------------------------------------- /deep-jsf/.settings/org.eclipse.wst.jsdt.ui.superType.name: -------------------------------------------------------------------------------- 1 | Window -------------------------------------------------------------------------------- /deep-jsf/.settings/org.eclipse.wst.validation.prefs: -------------------------------------------------------------------------------- 1 | disabled=06target 2 | eclipse.preferences.version=1 3 | -------------------------------------------------------------------------------- /deep-jsf/README.md: -------------------------------------------------------------------------------- 1 | ## Building 2 | 3 | To build the module, use Maven's `package` goal: 4 | 5 | ``` 6 | mvn clean package 7 | ``` 8 | 9 | The `war` file will be available at `target/deep-jsf.war` 10 | 11 | ## Running 12 | 13 | The `war` application is deployed to a Java EE 7 compliant application server, for example, to GlassFish 4 or later. 14 | 15 | The example then will be accessible at http://localhost:8080/deep-jsf/index.xhtml -------------------------------------------------------------------------------- /deep-jsf/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.stackify 6 | deep-jsf 7 | 0.0.1-SNAPSHOT 8 | war 9 | 10 | 11 | com.stackify 12 | parent-module 13 | 1.0.0-SNAPSHOT 14 | 15 | 16 | 17 | 18 | javax 19 | javaee-api 20 | 7.0 21 | provided 22 | 23 | 24 | 25 | 26 | deep-jsf 27 | 28 | 29 | org.apache.maven.plugins 30 | maven-compiler-plugin 31 | ${maven-compiler-plugin.version} 32 | 33 | ${maven.compiler.source.version} 34 | ${maven.compiler.target.version} 35 | 36 | 37 | 38 | 39 | 40 | 41 | false 42 | 1.8 43 | 1.8 44 | 45 | 46 | -------------------------------------------------------------------------------- /deep-jsf/src/main/java/com/stackify/deepjsf/GreetControllerBean.java: -------------------------------------------------------------------------------- 1 | package com.stackify.deepjsf; 2 | 3 | import javax.faces.bean.ManagedBean; 4 | import javax.faces.bean.RequestScoped; 5 | 6 | @ManagedBean 7 | @RequestScoped 8 | public class GreetControllerBean { 9 | 10 | public String greet() { 11 | return "greet"; 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /deep-jsf/src/main/java/com/stackify/deepjsf/PhaseListenerBean.java: -------------------------------------------------------------------------------- 1 | package com.stackify.deepjsf; 2 | 3 | import javax.faces.bean.ManagedBean; 4 | import javax.faces.bean.RequestScoped; 5 | import javax.faces.component.UIComponent; 6 | import javax.faces.component.UIViewRoot; 7 | import javax.faces.component.visit.VisitContext; 8 | import javax.faces.component.visit.VisitResult; 9 | import javax.faces.event.PhaseEvent; 10 | import javax.faces.event.PhaseId; 11 | import javax.servlet.http.HttpServletRequest; 12 | 13 | @ManagedBean 14 | @RequestScoped 15 | public class PhaseListenerBean { 16 | 17 | public void beforeListener(PhaseEvent event) { 18 | if (!event.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) { 19 | return; 20 | } 21 | UIViewRoot root = event.getFacesContext().getViewRoot(); 22 | 23 | boolean showNewFeature = showNewFeatureForIp(event); 24 | 25 | processComponentTree(root, event, showNewFeature); 26 | } 27 | 28 | private boolean showNewFeatureForIp(PhaseEvent event) { 29 | HttpServletRequest request = (HttpServletRequest) event.getFacesContext() 30 | .getExternalContext().getRequest(); 31 | String ip = request.getRemoteAddr(); 32 | return !ip.startsWith("127.0"); 33 | } 34 | 35 | private void processComponentTree(UIComponent component, PhaseEvent event, boolean show) { 36 | component.visitTree(VisitContext.createVisitContext(event.getFacesContext()), 37 | (context, target) -> { 38 | if (target.getId() != null 39 | && target.getId().startsWith("new-feature-") 40 | && !show) { 41 | target.setRendered(false); 42 | } 43 | return VisitResult.ACCEPT; 44 | }); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /deep-jsf/src/main/java/com/stackify/deepjsf/UserBean.java: -------------------------------------------------------------------------------- 1 | package com.stackify.deepjsf; 2 | 3 | import javax.faces.bean.ManagedBean; 4 | import javax.faces.bean.SessionScoped; 5 | import javax.faces.event.ValueChangeEvent; 6 | 7 | @ManagedBean 8 | @SessionScoped 9 | public class UserBean { 10 | 11 | private String name = ""; 12 | 13 | private String lastName = ""; 14 | 15 | private String proposedLogin = ""; 16 | 17 | public void nameChanged(ValueChangeEvent event) { 18 | this.proposedLogin = event.getNewValue() + "-" + lastName; 19 | } 20 | 21 | public void lastNameChanged(ValueChangeEvent event) { 22 | this.proposedLogin = name + "-" + event.getNewValue(); 23 | } 24 | 25 | public String getName() { 26 | return name; 27 | } 28 | 29 | public void setName(String name) { 30 | this.name = name; 31 | } 32 | 33 | public String getLastName() { 34 | return lastName; 35 | } 36 | 37 | public void setLastName(String lastName) { 38 | this.lastName = lastName; 39 | } 40 | 41 | public String getProposedLogin() { 42 | return proposedLogin; 43 | } 44 | 45 | public void setProposedLogin(String proposedLogin) { 46 | this.proposedLogin = proposedLogin; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /deep-jsf/src/main/java/com/stackify/deepjsf/UserControllerBean.java: -------------------------------------------------------------------------------- 1 | package com.stackify.deepjsf; 2 | 3 | import javax.faces.bean.ManagedBean; 4 | import javax.faces.bean.RequestScoped; 5 | 6 | @ManagedBean 7 | @RequestScoped 8 | public class UserControllerBean { 9 | 10 | public String register() { 11 | return "register-success"; 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /deep-jsf/src/main/webapp/WEB-INF/faces-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | /register.xhtml 9 | 10 | register-success 11 | /hello.xhtml 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /deep-jsf/src/main/webapp/greet.xhtml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /deep-jsf/src/main/webapp/hello.xhtml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /deep-jsf/src/main/webapp/index.xhtml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /deep-jsf/src/main/webapp/register.xhtml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 18 | 19 | 20 | 21 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /junit5-example/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | .settings/ 3 | .classpath 4 | .project 5 | -------------------------------------------------------------------------------- /junit5-example/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | junit5-example 5 | junit5-example 6 | 0.0.1-SNAPSHOT 7 | 8 | 9 | com.stackify 10 | parent-module 11 | 1.0.0-SNAPSHOT 12 | 13 | 14 | 15 | 16 | org.junit.jupiter 17 | junit-jupiter-engine 18 | 5.0.0-M4 19 | 20 | 21 | org.junit.jupiter 22 | junit-jupiter-params 23 | 5.0.0-M4 24 | 25 | 26 | 27 | org.junit.vintage 28 | junit-vintage-engine 29 | 4.12.0-M4 30 | 31 | 32 | 33 | com.h2database 34 | h2 35 | 1.4.195 36 | 37 | 38 | 39 | org.apache.logging.log4j 40 | log4j-core 41 | 2.8.2 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | maven-surefire-plugin 50 | 2.19.1 51 | 52 | 53 | org.junit.platform 54 | junit-platform-surefire-provider 55 | 1.0.0-M4 56 | 57 | 58 | 59 | 60 | math 61 | 62 | 63 | 64 | 65 | org.apache.maven.plugins 66 | maven-compiler-plugin 67 | ${maven-compiler-plugin.version} 68 | 69 | ${maven.compiler.source.version} 70 | ${maven.compiler.target.version} 71 | 72 | 73 | 74 | 75 | 76 | 77 | 1.8 78 | 1.8 79 | 80 | 81 | -------------------------------------------------------------------------------- /junit5-example/src/main/java/com/stackify/models/User.java: -------------------------------------------------------------------------------- 1 | package com.stackify.models; 2 | 3 | public class User { 4 | private String email; 5 | private String name; 6 | 7 | public User() { 8 | } 9 | 10 | public User(String email, String name) { 11 | super(); 12 | this.email = email; 13 | this.name = name; 14 | } 15 | 16 | public String getEmail() { 17 | return email; 18 | } 19 | 20 | public void setEmail(String email) { 21 | this.email = email; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | @Override 33 | public int hashCode() { 34 | final int prime = 31; 35 | int result = 1; 36 | result = prime * result + ((email == null) ? 0 : email.hashCode()); 37 | result = prime * result + ((name == null) ? 0 : name.hashCode()); 38 | return result; 39 | } 40 | 41 | @Override 42 | public boolean equals(Object obj) { 43 | if (this == obj) 44 | return true; 45 | if (obj == null) 46 | return false; 47 | if (getClass() != obj.getClass()) 48 | return false; 49 | User other = (User) obj; 50 | if (email == null) { 51 | if (other.email != null) 52 | return false; 53 | } else if (!email.equals(other.email)) 54 | return false; 55 | if (name == null) { 56 | if (other.name != null) 57 | return false; 58 | } else if (!name.equals(other.name)) 59 | return false; 60 | return true; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /junit5-example/src/main/java/com/stackify/test/conditions/DisabledOnEnvironment.java: -------------------------------------------------------------------------------- 1 | package com.stackify.test.conditions; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | import org.junit.jupiter.api.extension.ExtendWith; 9 | 10 | @Target({ ElementType.METHOD }) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @ExtendWith(DisabledOnEnvironmentCondition.class) 13 | public @interface DisabledOnEnvironment { 14 | String[] value(); 15 | } -------------------------------------------------------------------------------- /junit5-example/src/main/java/com/stackify/test/conditions/DisabledOnEnvironmentCondition.java: -------------------------------------------------------------------------------- 1 | package com.stackify.test.conditions; 2 | 3 | import java.io.IOException; 4 | import java.util.Arrays; 5 | import java.util.Optional; 6 | import java.util.Properties; 7 | 8 | import org.junit.jupiter.api.extension.ConditionEvaluationResult; 9 | import org.junit.jupiter.api.extension.TestExecutionCondition; 10 | import org.junit.jupiter.api.extension.TestExtensionContext; 11 | import org.junit.platform.commons.support.AnnotationSupport; 12 | 13 | import com.stackify.utils.ConnectionUtil; 14 | 15 | public class DisabledOnEnvironmentCondition implements TestExecutionCondition { 16 | 17 | @Override 18 | public ConditionEvaluationResult evaluate(TestExtensionContext context) { 19 | Properties props = new Properties(); 20 | String env = ""; 21 | try { 22 | props.load(ConnectionUtil.class.getResourceAsStream("/application.properties")); 23 | env = props.getProperty("env"); 24 | } catch (IOException e) { 25 | e.printStackTrace(); 26 | } 27 | Optional disabled = AnnotationSupport.findAnnotation(context.getElement().get(), DisabledOnEnvironment.class); 28 | if (disabled.isPresent()) { 29 | String[] envs = disabled.get().value(); 30 | if (Arrays.asList(envs).contains(env)) { 31 | return ConditionEvaluationResult.disabled("Disabled on environment " + env); 32 | } 33 | } 34 | 35 | return ConditionEvaluationResult.enabled("Enabled on environment "+env); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /junit5-example/src/main/java/com/stackify/utils/ConnectionUtil.java: -------------------------------------------------------------------------------- 1 | package com.stackify.utils; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.IOException; 5 | import java.sql.Connection; 6 | import java.sql.DriverManager; 7 | import java.sql.SQLException; 8 | import java.util.Properties; 9 | 10 | import org.apache.logging.log4j.LogManager; 11 | import org.apache.logging.log4j.Logger; 12 | 13 | public class ConnectionUtil { 14 | 15 | private static Logger logger = LogManager.getLogger(ConnectionUtil.class); 16 | 17 | public static Connection getConnection() { 18 | try { 19 | Properties props = new Properties(); 20 | props.load(ConnectionUtil.class.getResourceAsStream("jdbc.properties")); 21 | Class.forName(props.getProperty("jdbc.driver")); 22 | Connection con = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.user"), props.getProperty("jdbc.password")); 23 | return con; 24 | } 25 | 26 | catch (FileNotFoundException exc) { 27 | logger.error(exc.getMessage()); 28 | } catch (IOException exc) { 29 | logger.error(exc.getMessage()); 30 | } catch (ClassNotFoundException exc) { 31 | logger.error(exc.getMessage()); 32 | } catch (SQLException exc) { 33 | logger.error(exc.getMessage()); 34 | } 35 | return null; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /junit5-example/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | env=dev -------------------------------------------------------------------------------- /junit5-example/src/main/resources/com/stackify/utils/jdbc.properties: -------------------------------------------------------------------------------- 1 | jdbc.driver=org.h2.Driver 2 | jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1 3 | jdbc.user= 4 | jdbc.password= -------------------------------------------------------------------------------- /junit5-example/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /junit5-example/src/test/java/com/stackify/test/DatabaseConnectionTest.java: -------------------------------------------------------------------------------- 1 | package com.stackify.test; 2 | 3 | import java.sql.Connection; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | import com.stackify.utils.ConnectionUtil; 8 | 9 | import static org.junit.jupiter.api.Assertions.*; 10 | 11 | public interface DatabaseConnectionTest { 12 | 13 | @Test 14 | default void testDatabaseConnection() { 15 | Connection con = ConnectionUtil.getConnection(); 16 | assertNotNull(con); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /junit5-example/src/test/java/com/stackify/test/DynamicTests.java: -------------------------------------------------------------------------------- 1 | package com.stackify.test; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collection; 5 | import java.util.List; 6 | import java.util.function.Function; 7 | import java.util.stream.Stream; 8 | 9 | import static org.junit.jupiter.api.Assertions.*; 10 | import org.junit.jupiter.api.DynamicTest; 11 | import org.junit.jupiter.api.TestFactory; 12 | import org.junit.jupiter.api.function.ThrowingConsumer; 13 | 14 | import com.stackify.daos.UserDAO; 15 | import com.stackify.models.User; 16 | 17 | public class DynamicTests { 18 | 19 | @TestFactory 20 | public Collection dynamicTestCollection() { 21 | return Arrays.asList(DynamicTest.dynamicTest("Dynamic Test", () -> assertTrue(1 == 1))); 22 | } 23 | 24 | @TestFactory 25 | public Stream dynamicUserTestCollection() { 26 | List inputList = Arrays.asList(new User("john@yahoo.com", "John"), new User("ana@yahoo.com", "Ana")); 27 | 28 | Function displayNameGenerator = (input) -> "Saving user: " + input; 29 | 30 | UserDAO userDAO = new UserDAO(); 31 | ThrowingConsumer testExecutor = (input) -> { 32 | userDAO.add(input); 33 | assertNotNull(userDAO.findOne(input.getEmail())); 34 | }; 35 | 36 | return DynamicTest.stream(inputList.iterator(), displayNameGenerator, testExecutor); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /junit5-example/src/test/java/com/stackify/test/IncrementTest.java: -------------------------------------------------------------------------------- 1 | package com.stackify.test; 2 | 3 | import static org.junit.jupiter.api.Assertions.*; 4 | 5 | import org.apache.logging.log4j.LogManager; 6 | import org.apache.logging.log4j.Logger; 7 | import org.junit.jupiter.api.BeforeEach; 8 | import org.junit.jupiter.api.RepeatedTest; 9 | import org.junit.jupiter.api.RepetitionInfo; 10 | 11 | public class IncrementTest { 12 | 13 | private static Logger logger = LogManager.getLogger(IncrementTest.class); 14 | 15 | @BeforeEach 16 | public void increment() { 17 | logger.info("Before Each Test"); 18 | } 19 | 20 | @RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME) 21 | public void test(RepetitionInfo info) { 22 | assertTrue(1 == 1); 23 | logger.info("Repetition #" + info.getCurrentRepetition()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /junit5-example/src/test/java/com/stackify/test/TaggedTest.java: -------------------------------------------------------------------------------- 1 | package com.stackify.test; 2 | 3 | import static org.junit.jupiter.api.Assertions.*; 4 | import org.junit.jupiter.api.Tag; 5 | import org.junit.jupiter.api.Test; 6 | 7 | @Tag("math") 8 | public class TaggedTest { 9 | 10 | @Test 11 | @Tag("arithmetic") 12 | public void testEquals() { 13 | assertTrue(1 == 1); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /log4j2-example/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | .settings/ 3 | .classpath 4 | .project 5 | -------------------------------------------------------------------------------- /log4j2-example/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | log4j2-example 5 | log4j2-example 6 | 0.0.1-SNAPSHOT 7 | 8 | 9 | com.stackify 10 | parent-module 11 | 1.0.0-SNAPSHOT 12 | 13 | 14 | 15 | 16 | 17 | org.apache.logging.log4j 18 | log4j-core 19 | ${log4j-core.version} 20 | 21 | 22 | 23 | 24 | com.fasterxml.jackson.core 25 | jackson-databind 26 | ${jackson.version} 27 | 28 | 29 | 30 | junit 31 | junit 32 | ${junit.version} 33 | 34 | 35 | 36 | 37 | 38 | 39 | src/main/resources/ 40 | 41 | **/*.java 42 | 43 | 44 | 45 | 46 | 47 | org.apache.maven.plugins 48 | maven-compiler-plugin 49 | ${maven-compiler-plugin.version} 50 | 51 | ${maven.compiler.source.version} 52 | ${maven.compiler.target.version} 53 | 54 | 55 | 56 | 57 | 58 | 59 | 2.8.8.1 60 | 2.8.2 61 | 1.8 62 | 1.8 63 | 64 | 65 | -------------------------------------------------------------------------------- /log4j2-example/src/main/java/com/stackify/models/User.java: -------------------------------------------------------------------------------- 1 | package com.stackify.models; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class User { 6 | private String name; 7 | private String email; 8 | private LocalDate dateOfBirth; 9 | 10 | public User() { 11 | } 12 | 13 | public User(String name, String email) { 14 | super(); 15 | this.name = name; 16 | this.email = email; 17 | } 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public void setName(String name) { 24 | this.name = name; 25 | } 26 | 27 | public String getEmail() { 28 | return email; 29 | } 30 | 31 | public void setEmail(String email) { 32 | this.email = email; 33 | } 34 | 35 | public LocalDate getDateOfBirth() { 36 | return dateOfBirth; 37 | } 38 | 39 | public void setDateOfBirth(LocalDate dateOfBirth) { 40 | this.dateOfBirth = dateOfBirth; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /log4j2-example/src/main/java/com/stackify/services/MyService.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import java.time.LocalDate; 4 | import java.time.Period; 5 | 6 | import com.stackify.models.User; 7 | 8 | public class MyService { 9 | 10 | public int calculateUserAge(User user) { 11 | return Period.between(user.getDateOfBirth(), LocalDate.now()).getYears(); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /log4j2-example/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 16 | 17 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 61 | 62 | -------------------------------------------------------------------------------- /log4j2-example/src/test/java/com/stackify/services/MyServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import java.time.LocalDate; 4 | import java.time.Month; 5 | 6 | import org.apache.logging.log4j.Level; 7 | import org.apache.logging.log4j.LogManager; 8 | import org.apache.logging.log4j.Logger; 9 | import org.apache.logging.log4j.core.Appender; 10 | import org.apache.logging.log4j.core.LoggerContext; 11 | import org.apache.logging.log4j.core.appender.FileAppender; 12 | import org.apache.logging.log4j.core.config.AppenderRef; 13 | import org.apache.logging.log4j.core.config.Configuration; 14 | import org.apache.logging.log4j.core.config.LoggerConfig; 15 | import org.apache.logging.log4j.core.layout.PatternLayout; 16 | import org.junit.Test; 17 | 18 | import com.stackify.models.User; 19 | import com.stackify.services.MyService; 20 | 21 | public class MyServiceTest { 22 | 23 | private static final Logger logger = LogManager.getLogger(MyServiceTest.class); 24 | 25 | @Test 26 | public void testService() { 27 | MyService myService = new MyService(); 28 | User user = new User("John", "john@yahoo.com"); 29 | user.setDateOfBirth(LocalDate.of(1980, Month.APRIL, 20)); 30 | logger.info("Age of user {} is {}", () -> user.getName(), () -> myService.calculateUserAge(user)); 31 | } 32 | 33 | @Test 34 | public void testColoredLogger() { 35 | logger.fatal("Fatal level message"); 36 | logger.error("Error level message"); 37 | logger.warn("Warn level message"); 38 | logger.info("Info level message"); 39 | logger.debug("Debug level message"); 40 | } 41 | 42 | @Test 43 | public void testRollingFileAppender() { 44 | Logger rfLogger = LogManager.getLogger("RollingFileLogger"); 45 | rfLogger.info("Json Message 1"); 46 | rfLogger.info("Json Message 2"); 47 | } 48 | 49 | @Test 50 | public void testProgrammaticConfig() { 51 | LoggerContext ctx = (LoggerContext) LogManager.getContext(false); 52 | Configuration config = ctx.getConfiguration(); 53 | 54 | PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern("%d{HH:mm:ss.SSS} %level %msg%n").build(); 55 | 56 | Appender appender = FileAppender.newBuilder().setConfiguration(config).withName("programmaticFileAppender").withLayout(layout).withFileName("java.log").build(); 57 | appender.start(); 58 | config.addAppender(appender); 59 | AppenderRef ref = AppenderRef.createAppenderRef("programmaticFileAppender", null, null); 60 | AppenderRef[] refs = new AppenderRef[] { ref }; 61 | 62 | LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "programmaticLogger", "true", refs, null, config, null); 63 | 64 | loggerConfig.addAppender(appender, null, null); 65 | config.addLogger("programmaticLogger", loggerConfig); 66 | ctx.updateLoggers(); 67 | 68 | Logger pLogger = LogManager.getLogger("programmaticLogger"); 69 | pLogger.info("Programmatic Logger Message"); 70 | } 71 | 72 | @Test 73 | public void testCustomLevel() { 74 | Level myLevel = Level.forName("NEW_LEVEL", 350); 75 | logger.log(myLevel, "Custom Level Message"); 76 | 77 | logger.log(Level.getLevel("NEW_XML_LEVEL"), "Custom XML Level Message"); 78 | 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /logback-example/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.stackify 5 | logback-example 6 | 0.0.1-SNAPSHOT 7 | 8 | 9 | com.stackify 10 | parent-module 11 | 1.0.0-SNAPSHOT 12 | 13 | 14 | 15 | 16 | ch.qos.logback 17 | logback-classic 18 | 1.2.3 19 | 20 | 21 | 22 | junit 23 | junit 24 | 4.12 25 | 26 | 27 | 28 | org.codehaus.janino 29 | janino 30 | 3.0.7 31 | 32 | 33 | 34 | 35 | 1.8 36 | 1.8 37 | 38 | -------------------------------------------------------------------------------- /logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java: -------------------------------------------------------------------------------- 1 | package com.stackify.logging; 2 | 3 | import org.slf4j.Marker; 4 | 5 | import ch.qos.logback.classic.Level; 6 | import ch.qos.logback.classic.Logger; 7 | import ch.qos.logback.classic.turbo.TurboFilter; 8 | import ch.qos.logback.core.spi.FilterReply; 9 | 10 | public class IgnoreLoggerFilter extends TurboFilter { 11 | 12 | private String loggerName; 13 | 14 | @Override 15 | public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { 16 | if (loggerName == null) { 17 | return FilterReply.NEUTRAL; 18 | } else if (loggerName.equals(logger.getName())) { 19 | return FilterReply.DENY; 20 | } else 21 | return FilterReply.NEUTRAL; 22 | } 23 | 24 | public void setLoggerName(String loggerName) { 25 | this.loggerName = loggerName; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /logback-example/src/main/java/com/stackify/models/Employee.java: -------------------------------------------------------------------------------- 1 | package com.stackify.models; 2 | 3 | public class Employee { 4 | 5 | private String email; 6 | private String name; 7 | 8 | private double salary; 9 | 10 | public Employee() { 11 | } 12 | 13 | public Employee(String email, String name, double salary) { 14 | this.email = email; 15 | this.name = name; 16 | this.salary = salary; 17 | } 18 | 19 | public String getEmail() { 20 | return email; 21 | } 22 | 23 | public void setEmail(String email) { 24 | this.email = email; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public double getSalary() { 36 | return salary; 37 | } 38 | 39 | public void setSalary(double salary) { 40 | this.salary = salary; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /logback-example/src/main/java/com/stackify/services/EmployeeService.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import com.stackify.models.Employee; 4 | 5 | public class EmployeeService { 6 | 7 | public double calculateBonus(Employee user) { 8 | return 0.1 * user.getSalary(); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /logback-example/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | env=dev -------------------------------------------------------------------------------- /logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import org.junit.Test; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.slf4j.MDC; 7 | 8 | import com.stackify.models.Employee; 9 | 10 | import ch.qos.logback.classic.Level; 11 | 12 | public class EmployeeServiceTest { 13 | private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); 14 | 15 | private EmployeeService employeeService = new EmployeeService(); 16 | 17 | @Test 18 | public void testAppenders() { 19 | Logger rollingFileLogger = LoggerFactory.getLogger("rollingFileLogger"); 20 | rollingFileLogger.info("Testing rolling file logger"); 21 | 22 | MDC.put("userRole", "ADMIN"); 23 | Logger siftingLogger = LoggerFactory.getLogger("roleSiftingLogger"); 24 | siftingLogger.info("Admin Action"); 25 | } 26 | 27 | @Test 28 | public void testLayouts() { 29 | Logger htmlLogger = LoggerFactory.getLogger("htmlLogger"); 30 | htmlLogger.error("Employee Information Update Failed"); 31 | htmlLogger.info("New Account Created"); 32 | 33 | Logger colorLogger = LoggerFactory.getLogger("colorLogger"); 34 | colorLogger.error("Employee Information Update Failed"); 35 | colorLogger.info("New Account Created"); 36 | } 37 | 38 | @Test 39 | public void testLogLevel() { 40 | ch.qos.logback.classic.Logger rollingFileLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("rollingFileLogger"); 41 | rollingFileLogger.setLevel(Level.DEBUG); 42 | rollingFileLogger.debug("Testing Log Level"); 43 | } 44 | 45 | @Test 46 | public void testParameter() { 47 | Employee employee = new Employee("john@gmail.com", "John", 2000); 48 | if (logger.isDebugEnabled()) { 49 | logger.debug("The bonus for employee: " + employee.getName() + " is " + employeeService.calculateBonus(employee)); 50 | } 51 | logger.debug("The bonus for employee {} is {}", employee.getName(), employeeService.calculateBonus(employee)); 52 | } 53 | 54 | @Test 55 | public void testFilters() { 56 | Logger levelFilterLogger = LoggerFactory.getLogger("levelFilterLogger"); 57 | levelFilterLogger.error("Employee Information Update Failed"); 58 | Logger thresholdFilterLogger = LoggerFactory.getLogger("thresholdFilterLogger"); 59 | thresholdFilterLogger.trace("Employee record inserted"); 60 | Logger evaluatorFilterLogger = LoggerFactory.getLogger("evaluatorFilterLogger"); 61 | evaluatorFilterLogger.debug("Employee account deactivated"); 62 | } 63 | 64 | @Test 65 | public void testIgnoredLogger() { 66 | Logger colorLogger = LoggerFactory.getLogger("ignoredColorLogger"); 67 | colorLogger.info("Ignored Log Message"); 68 | } 69 | 70 | @Test 71 | public void testConditionalConfiguration() { 72 | logger.trace("Employee record updated"); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /memory-leaks/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.baeldung 5 | memory-leaks 6 | 0.0.1-SNAPSHOT 7 | 8 | 9 | com.stackify 10 | parent-module 11 | 1.0.0-SNAPSHOT 12 | 13 | 14 | 15 | 16 | junit 17 | junit 18 | ${junit.version} 19 | 20 | 21 | 22 | 23 | 24 | 25 | src/main/resources/ 26 | 27 | **/*.java 28 | 29 | 30 | 31 | src/test/resources/ 32 | 33 | 34 | 35 | 36 | 1.8 37 | 1.8 38 | 39 | -------------------------------------------------------------------------------- /memory-leaks/src/test/java/com/baeldung/Key.java: -------------------------------------------------------------------------------- 1 | package com.baeldung; 2 | 3 | public class Key { 4 | 5 | public static String key; 6 | 7 | public Key(String key) { 8 | Key.key = key; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.stackify 5 | parent-module 6 | 1.0.0-SNAPSHOT 7 | 8 | parent-module 9 | pom 10 | 11 | 12 | core-java 13 | core-java-9 14 | deep-jsf 15 | junit5-example 16 | log4j2-example 17 | logback-example 18 | memory-leaks 19 | remote-debugging 20 | spring-boot-app 21 | spring-mvc 22 | spring-security 23 | thread-pools 24 | tomcat-app 25 | webservices 26 | 27 | 28 | 29 | refs/remotes/origin/master 30 | 4.12 31 | 3.7.0 32 | 2.19.1 33 | 2.21.0 34 | 35 | 36 | -------------------------------------------------------------------------------- /remote-debugging/README.md: -------------------------------------------------------------------------------- 1 | ## Building 2 | 3 | To build the module, use Maven's `package` goal: 4 | 5 | ``` 6 | mvn clean package 7 | ``` 8 | 9 | The `war` file will be available at `target/remote-debugging.war` 10 | 11 | ## Running 12 | 13 | The `war` application is deployed to Apache Tomcat 8 or any other Java Web or Application server. 14 | To deploy it to the Apache Tomcat 8 server, drop it in the `tomcat/webapps` directory. 15 | 16 | The service then will be accessible at http://localhost:8080/remote-debugging/hello?name=John -------------------------------------------------------------------------------- /remote-debugging/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | com.stackify 6 | java-remote-debugging 7 | 0.0.1-SNAPSHOT 8 | war 9 | 10 | 11 | org.springframework.boot 12 | spring-boot-starter-parent 13 | 1.5.8.RELEASE 14 | 15 | 16 | 17 | 18 | 19 | org.springframework.boot 20 | spring-boot-starter-web 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-tomcat 25 | 26 | 27 | 28 | 29 | remote-debugging 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-maven-plugin 34 | 35 | 36 | 37 | 38 | 39 | UTF-8 40 | UTF-8 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /remote-debugging/src/main/java/com/stackify/debug/JavaRemoteDebuggingApplication.java: -------------------------------------------------------------------------------- 1 | package com.stackify.debug; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class JavaRemoteDebuggingApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(JavaRemoteDebuggingApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /remote-debugging/src/main/java/com/stackify/debug/config/WebInitializer.java: -------------------------------------------------------------------------------- 1 | package com.stackify.debug.config; 2 | 3 | import com.stackify.debug.JavaRemoteDebuggingApplication; 4 | import org.springframework.boot.builder.SpringApplicationBuilder; 5 | import org.springframework.boot.web.support.SpringBootServletInitializer; 6 | 7 | public class WebInitializer extends SpringBootServletInitializer { 8 | @Override 9 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 10 | return application.sources(JavaRemoteDebuggingApplication.class); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /remote-debugging/src/main/java/com/stackify/debug/rest/HelloController.java: -------------------------------------------------------------------------------- 1 | package com.stackify.debug.rest; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestParam; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController("/hello") 8 | public class HelloController { 9 | 10 | @GetMapping 11 | public String hello(@RequestParam("name") String name) { 12 | String message = "Hello, " + name; 13 | return message; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /slf4j/guide/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.stackify.slf4j.guide 7 | slf4j-parent-module 8 | 1.0.0-SNAPSHOT 9 | pom 10 | 11 | 12 | 13 | org.springframework.boot 14 | spring-boot-starter-parent 15 | 2.0.6.RELEASE 16 | 17 | 18 | 19 | slf4j-logback 20 | slf4j-log4j2 21 | slf4j-log4j 22 | 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-web 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-test 32 | test 33 | 34 | 35 | org.powermock 36 | powermock-module-junit4 37 | ${powermock.version} 38 | test 39 | 40 | 41 | org.powermock 42 | powermock-api-mockito2 43 | ${powermock.version} 44 | test 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-maven-plugin 54 | 55 | 56 | 57 | 58 | 59 | UTF-8 60 | UTF-8 61 | 1.8 62 | 2.0.0-beta.5 63 | 64 | 65 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | slf4j-log4j 7 | 0.0.1-SNAPSHOT 8 | jar 9 | 10 | 11 | com.stackify.slf4j.guide 12 | slf4j-parent-module 13 | 1.0.0-SNAPSHOT 14 | .. 15 | 16 | 17 | 18 | 19 | org.springframework.boot 20 | spring-boot-starter-web 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-logging 25 | 26 | 27 | 28 | 29 | org.slf4j 30 | slf4j-log4j12 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-test 35 | test 36 | 37 | 38 | 39 | 1.7.25 40 | 41 | 42 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j/src/main/java/com/stackify/slf4j/guide/Application.java: -------------------------------------------------------------------------------- 1 | package com.stackify.slf4j.guide; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Application.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j/src/main/java/com/stackify/slf4j/guide/controllers/SimpleController.java: -------------------------------------------------------------------------------- 1 | package com.stackify.slf4j.guide.controllers; 2 | 3 | import java.util.List; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.slf4j.MDC; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RequestHeader; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | @RestController 13 | public class SimpleController { 14 | 15 | Logger logger = LoggerFactory.getLogger(SimpleController.class); 16 | 17 | @GetMapping("/slf4j-guide-request") 18 | public String processList(List list) { 19 | logger.info("Client requested process the following list: {}", list); 20 | try { 21 | logger.debug("Starting process"); 22 | // ...processing list here... 23 | Thread.sleep(500); 24 | } catch (RuntimeException | InterruptedException e) { 25 | logger.error("There was an issue processing the list.", e); 26 | } finally { 27 | logger.info("Finished processing"); 28 | } 29 | return "done"; 30 | } 31 | 32 | @GetMapping("/slf4j-guide-mdc-request") 33 | public String clientMDCRequest(@RequestHeader String clientId) throws InterruptedException { 34 | MDC.put("clientId", clientId); 35 | logger.info("Client {} has made a request", clientId); 36 | logger.info("Starting request"); 37 | Thread.sleep(500); 38 | logger.info("Finished request"); 39 | MDC.clear(); 40 | return "finished"; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/stackify/8e84872a1d27a10d08b75fdbcceff092e74637dc/slf4j/guide/slf4j-log4j/src/main/resources/application.properties -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j/src/main/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j/src/test/java/com/stackify/slf4j/guide/utils/ListAppender.java: -------------------------------------------------------------------------------- 1 | package com.stackify.slf4j.guide.utils; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.apache.log4j.AppenderSkeleton; 7 | import org.apache.log4j.spi.LoggingEvent; 8 | 9 | public class ListAppender extends AppenderSkeleton { 10 | public static List events = new ArrayList(); 11 | 12 | @Override 13 | public void close() { 14 | } 15 | 16 | @Override 17 | public boolean requiresLayout() { 18 | return false; 19 | } 20 | 21 | @Override 22 | protected void append(LoggingEvent event) { 23 | events.add(event); 24 | } 25 | 26 | public static List getEvents() { 27 | return events; 28 | } 29 | 30 | public static void clearEventList() { 31 | events.clear(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j/src/test/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j2/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | slf4j-log4j2 7 | 0.0.1-SNAPSHOT 8 | jar 9 | 10 | 11 | com.stackify.slf4j.guide 12 | slf4j-parent-module 13 | 1.0.0-SNAPSHOT 14 | .. 15 | 16 | 17 | 18 | 19 | org.springframework.boot 20 | spring-boot-starter-web 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-logging 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-log4j2 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-test 35 | test 36 | 37 | 38 | org.apache.logging.log4j 39 | log4j-core 40 | ${log4j.version} 41 | test-jar 42 | 43 | 44 | org.apache.logging.log4j 45 | log4j-api 46 | ${log4j.version} 47 | test-jar 48 | 49 | 50 | 51 | 52 | 2.11.0 53 | 54 | 55 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j2/src/main/java/com/stackify/slf4j/guide/Application.java: -------------------------------------------------------------------------------- 1 | package com.stackify.slf4j.guide; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Application.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j2/src/main/java/com/stackify/slf4j/guide/controllers/SimpleController.java: -------------------------------------------------------------------------------- 1 | package com.stackify.slf4j.guide.controllers; 2 | 3 | import java.util.List; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.slf4j.MDC; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RequestHeader; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | @RestController 13 | public class SimpleController { 14 | 15 | Logger logger = LoggerFactory.getLogger(SimpleController.class); 16 | 17 | @GetMapping("/slf4j-guide-request") 18 | public String processList(List list) { 19 | logger.info("Client requested process the following list: {}", list); 20 | try { 21 | logger.debug("Starting process"); 22 | // ...processing list here... 23 | Thread.sleep(500); 24 | } catch (RuntimeException | InterruptedException e) { 25 | logger.error("There was an issue processing the list.", e); 26 | } finally { 27 | logger.info("Finished processing"); 28 | } 29 | return "done"; 30 | } 31 | 32 | @GetMapping("/slf4j-guide-mdc-request") 33 | public String clientMDCRequest(@RequestHeader String clientId) throws InterruptedException { 34 | MDC.put("clientId", clientId); 35 | logger.info("Client {} has made a request", clientId); 36 | logger.info("Starting request"); 37 | Thread.sleep(500); 38 | logger.info("Finished request"); 39 | MDC.clear(); 40 | return "finished"; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j2/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/stackify/8e84872a1d27a10d08b75fdbcceff092e74637dc/slf4j/guide/slf4j-log4j2/src/main/resources/application.properties -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j2/src/main/resources/log4j2-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | ???? 4 | %5p 5 | yyyy-MM-dd HH:mm:ss.SSS 6 | %clr{%d{${LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${LOG_LEVEL_PATTERN}} %clr{${sys:PID}}{magenta} 7 | %clr{---}{faint} %clr{%X{clientId}}{red}%clr{@%15.15t}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j2/src/test/java/com/stackify/slf4j/guide/controllers/SimpleControllerIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.stackify.slf4j.guide.controllers; 2 | 3 | import java.util.Collections; 4 | 5 | import org.apache.logging.log4j.Level; 6 | import org.apache.logging.log4j.core.LogEvent; 7 | import org.apache.logging.log4j.junit.LoggerContextRule; 8 | import org.apache.logging.log4j.test.appender.ListAppender; 9 | import org.assertj.core.api.Condition; 10 | import org.assertj.core.api.SoftAssertions; 11 | import org.junit.Before; 12 | import org.junit.BeforeClass; 13 | import org.junit.ClassRule; 14 | import org.junit.Test; 15 | 16 | public class SimpleControllerIntegrationTest { 17 | 18 | private static ListAppender appender; 19 | private SimpleController controller = new SimpleController(); 20 | 21 | @ClassRule 22 | public static LoggerContextRule init = new LoggerContextRule("log4j2-test.xml"); 23 | 24 | @BeforeClass 25 | public static void setupLogging() { 26 | appender = init.getListAppender("ListAppender"); 27 | } 28 | 29 | @Before 30 | public void clearAppender() { 31 | appender.clear(); 32 | } 33 | 34 | @Test 35 | public void whenSimpleRequestMade_thenAllRegularMessagesLogged() { 36 | String output = controller.processList(Collections.emptyList()); 37 | 38 | SoftAssertions errorCollector = new SoftAssertions(); 39 | errorCollector.assertThat(appender.getEvents()) 40 | .haveAtLeastOne(eventContains("Client requested process the following list: []", Level.INFO)) 41 | .haveAtLeastOne(eventContains("Starting process", Level.DEBUG)) 42 | .haveAtLeastOne(eventContains("Finished processing", Level.INFO)) 43 | .haveExactly(0, eventOfLevel(Level.ERROR)); 44 | errorCollector.assertThat(output) 45 | .isEqualTo("done"); 46 | errorCollector.assertAll(); 47 | } 48 | 49 | @Test 50 | public void givenClientId_whenMDCRequestMade_thenMessagesWithClientIdLogged() throws Exception { 51 | String clientId = "id-1234"; 52 | 53 | String output = controller.clientMDCRequest(clientId); 54 | 55 | SoftAssertions errorCollector = new SoftAssertions(); 56 | errorCollector.assertThat(appender.getEvents()) 57 | .allMatch(entry -> { 58 | return clientId.equals(entry.getContextData() 59 | .getValue("clientId")); 60 | }) 61 | .haveAtLeastOne(eventContains("Client id-1234 has made a request", Level.INFO)) 62 | .haveAtLeastOne(eventContains("Starting request", Level.INFO)) 63 | .haveAtLeastOne(eventContains("Finished request", Level.INFO)); 64 | errorCollector.assertThat(output) 65 | .isEqualTo("finished"); 66 | errorCollector.assertAll(); 67 | } 68 | 69 | private Condition eventOfLevel(Level level) { 70 | return eventContains(null, level); 71 | } 72 | 73 | private Condition eventContains(String substring, Level level) { 74 | 75 | return new Condition(entry -> (substring == null || (entry.getMessage() 76 | .getFormattedMessage() != null && entry.getMessage() 77 | .getFormattedMessage() 78 | .contains(substring))) 79 | && (level == null || level.equals(entry.getLevel())), String.format("entry with message '%s', level %s", substring, level)); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-log4j2/src/test/resources/log4j2-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-logback/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /slf4j/guide/slf4j-logback/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | slf4j-logback 7 | 0.0.1-SNAPSHOT 8 | jar 9 | 10 | 11 | com.stackify.slf4j.guide 12 | slf4j-parent-module 13 | 1.0.0-SNAPSHOT 14 | .. 15 | 16 | 17 | 18 | 19 | org.slf4j 20 | slf4j-ext 21 | 22 | 23 | ch.qos.cal10n 24 | cal10n-api 25 | ${cal10n.version} 26 | 27 | 28 | 29 | 30 | 0.8.1 31 | 32 | 33 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/Application.java: -------------------------------------------------------------------------------- 1 | package com.stackify.slf4j.guide; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Application.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/l10n/Messages.java: -------------------------------------------------------------------------------- 1 | package com.stackify.slf4j.guide.l10n; 2 | 3 | import ch.qos.cal10n.BaseName; 4 | import ch.qos.cal10n.Locale; 5 | import ch.qos.cal10n.LocaleData; 6 | 7 | @BaseName("messages") 8 | @LocaleData({ @Locale("en_US"), @Locale("es_ES") }) 9 | public enum Messages { 10 | CLIENT_REQUEST, REQUEST_STARTED, REQUEST_FINISHED 11 | } 12 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/xlogger/XLoggerController.java: -------------------------------------------------------------------------------- 1 | package com.stackify.slf4j.guide.xlogger; 2 | 3 | import org.slf4j.ext.XLogger; 4 | import org.slf4j.ext.XLoggerFactory; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RequestParam; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | public class XLoggerController { 11 | 12 | private XLogger logger = XLoggerFactory.getXLogger(XLoggerController.class); 13 | 14 | @GetMapping("/slf4j-guide-xlogger-request") 15 | public Integer clientXLoggerRequest(@RequestParam("queryParam") Integer queryParam) { 16 | logger.info("Starting process"); 17 | logger.entry(queryParam); 18 | Integer rest = 0; 19 | try { 20 | rest = queryParam % 3; 21 | } catch (RuntimeException anyException) { 22 | logger.catching(anyException); 23 | } 24 | logger.exit(rest); 25 | return rest; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-logback/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/stackify/8e84872a1d27a10d08b75fdbcceff092e74637dc/slf4j/guide/slf4j-logback/src/main/resources/application.properties -------------------------------------------------------------------------------- /slf4j/guide/slf4j-logback/src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | %marker %d{yyyy-MM-dd HH:mm:ss.SSS} -%5p %X{clientId}@%15.15t %-40.40logger{39} : %m%n 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-logback/src/main/resources/messages_en_US.properties: -------------------------------------------------------------------------------- 1 | CLIENT_REQUEST=Client {0} has made a request using locale {1} 2 | REQUEST_STARTED=Request started 3 | REQUEST_FINISHED=Request finished -------------------------------------------------------------------------------- /slf4j/guide/slf4j-logback/src/main/resources/messages_es_ES.properties: -------------------------------------------------------------------------------- 1 | CLIENT_REQUEST=El cliente {0} ha realizado una solicitud usando locale {1} 2 | REQUEST_STARTED=Solicitud iniciada 3 | REQUEST_FINISHED=Solicitud finalizada -------------------------------------------------------------------------------- /slf4j/guide/slf4j-logback/src/test/java/com/stackify/slf4j/guide/utils/ListAppender.java: -------------------------------------------------------------------------------- 1 | package com.stackify.slf4j.guide.utils; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import ch.qos.logback.classic.spi.ILoggingEvent; 7 | import ch.qos.logback.core.AppenderBase; 8 | 9 | public class ListAppender extends AppenderBase { 10 | 11 | static private List events = new ArrayList<>(); 12 | 13 | @Override 14 | protected void append(ILoggingEvent eventObject) { 15 | events.add(eventObject); 16 | } 17 | 18 | public static List getEvents() { 19 | return events; 20 | } 21 | 22 | public static void clearEventList() { 23 | events.clear(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /slf4j/guide/slf4j-logback/src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /spring-boot-app/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | .settings/ 3 | .classpath 4 | .project 5 | -------------------------------------------------------------------------------- /spring-boot-app/README.md: -------------------------------------------------------------------------------- 1 | # Building and running the application 2 | 3 | ## Option 1 4 | ``mvn clean install``\ 5 | ``mvn spring-boot:run`` 6 | 7 | ## Option 2 8 | ``mvn package spring-boot:repackage``\ 9 | ``java -Dspring.profiles.active=default -jar target/spring-boot-app-0.0.1-SNAPSHOT.war`` 10 | 11 | # Accessing the application 12 | http://localhost:8081/springbootapp/employees -------------------------------------------------------------------------------- /spring-boot-app/WebContent/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /spring-boot-app/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | spring-boot-app 4 | spring-boot-app 5 | 0.0.1-SNAPSHOT 6 | war 7 | 8 | 9 | org.springframework.boot 10 | spring-boot-starter-parent 11 | 1.5.3.RELEASE 12 | 13 | 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-web 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-data-jpa 23 | 24 | 25 | com.h2database 26 | h2 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-actuator 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-test 35 | 36 | 37 | javax.xml.bind 38 | jaxb-api 39 | 2.2.11 40 | 41 | 42 | com.sun.xml.bind 43 | jaxb-core 44 | 2.2.11 45 | 46 | 47 | com.sun.xml.bind 48 | jaxb-impl 49 | 2.2.11 50 | 51 | 52 | 53 | 54 | 55 | 56 | maven-compiler-plugin 57 | 3.7.0 58 | 59 | 1.8 60 | 1.8 61 | 62 | 63 | 64 | maven-war-plugin 65 | 3.1.0 66 | 67 | WebContent 68 | 69 | 70 | 71 | 72 | 73 | 74 | 8.0.43 75 | 76 | 77 | -------------------------------------------------------------------------------- /spring-boot-app/src/main/java/com/stackify/Application.java: -------------------------------------------------------------------------------- 1 | package com.stackify; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Application.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /spring-boot-app/src/main/java/com/stackify/config/PersistenceConfig.java: -------------------------------------------------------------------------------- 1 | package com.stackify.config; 2 | 3 | import javax.sql.DataSource; 4 | 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; 8 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; 9 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; 10 | 11 | @Configuration 12 | public class PersistenceConfig { 13 | 14 | @Bean 15 | public DataSource dataSource() { 16 | EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); 17 | EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2).addScript("mySchema.sql").addScript("myData.sql").build(); 18 | return db; 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /spring-boot-app/src/main/java/com/stackify/controller/EmployeeController.java: -------------------------------------------------------------------------------- 1 | package com.stackify.controller; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.PostMapping; 7 | import org.springframework.web.bind.annotation.RequestBody; 8 | import org.springframework.web.bind.annotation.ResponseStatus; 9 | import org.springframework.web.bind.annotation.RestController; 10 | import org.springframework.http.HttpStatus; 11 | 12 | import com.stackify.model.Employee; 13 | import com.stackify.repository.EmployeeRepository; 14 | 15 | @RestController 16 | public class EmployeeController { 17 | 18 | private EmployeeRepository employeeRepository; 19 | 20 | public EmployeeController(EmployeeRepository employeeRepository) { 21 | this.employeeRepository = employeeRepository; 22 | } 23 | 24 | @PostMapping("/employees") 25 | @ResponseStatus(HttpStatus.CREATED) 26 | public void addEmployee(@RequestBody Employee employee) { 27 | employeeRepository.save(employee); 28 | } 29 | 30 | @GetMapping("/employees") 31 | public List getEmployees() { 32 | return employeeRepository.findAll(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /spring-boot-app/src/main/java/com/stackify/model/Employee.java: -------------------------------------------------------------------------------- 1 | package com.stackify.model; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | 8 | @Entity 9 | public class Employee { 10 | @Id 11 | @GeneratedValue(strategy = GenerationType.IDENTITY) 12 | private long id; 13 | 14 | private String name; 15 | 16 | public Employee() { 17 | } 18 | 19 | public Employee(long id, String name) { 20 | super(); 21 | this.id = id; 22 | this.name = name; 23 | } 24 | 25 | public long getId() { 26 | return id; 27 | } 28 | 29 | public void setId(long id) { 30 | this.id = id; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public void setName(String name) { 38 | this.name = name; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /spring-boot-app/src/main/java/com/stackify/repository/EmployeeRepository.java: -------------------------------------------------------------------------------- 1 | package com.stackify.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | import com.stackify.model.Employee; 6 | 7 | public interface EmployeeRepository extends JpaRepository { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /spring-boot-app/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8081 2 | server.contextPath=/springbootapp 3 | logging.level.org.springframework.web: INFO 4 | 5 | spring.jpa.hibernate.ddl-auto=update -------------------------------------------------------------------------------- /spring-boot-app/src/main/resources/myData.sql: -------------------------------------------------------------------------------- 1 | insert into employee(name) values ('ana'); -------------------------------------------------------------------------------- /spring-boot-app/src/main/resources/mySchema.sql: -------------------------------------------------------------------------------- 1 | create table employee(id int identity primary key, name varchar(30)); -------------------------------------------------------------------------------- /spring-boot-app/src/test/java/com/stackify/test/EmployeeControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.stackify.test; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | import org.springframework.test.context.web.WebAppConfiguration; 10 | import org.springframework.test.web.servlet.MockMvc; 11 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 12 | import org.springframework.web.context.WebApplicationContext; 13 | 14 | import static org.hamcrest.Matchers.*; 15 | 16 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; 17 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 18 | 19 | import com.stackify.Application; 20 | 21 | @RunWith(SpringRunner.class) 22 | @SpringBootTest(classes = Application.class) 23 | @WebAppConfiguration 24 | public class EmployeeControllerTest { 25 | 26 | private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; 27 | 28 | private MockMvc mockMvc; 29 | 30 | @Autowired 31 | private WebApplicationContext webApplicationContext; 32 | 33 | @Before 34 | public void setup() throws Exception { 35 | this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); 36 | } 37 | 38 | @Test 39 | public void whenCreateGetEmployee_thenOk() throws Exception { 40 | String employeeJson = "{\"name\":\"john\"}"; 41 | 42 | this.mockMvc.perform(post("/employees").contentType(CONTENT_TYPE).content(employeeJson)).andExpect(status().isCreated()); 43 | 44 | this.mockMvc.perform(get("/employees")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$", hasSize(2))).andExpect(jsonPath("$[0].name", is("ana"))).andExpect(jsonPath("$[1].name", is("john"))); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /spring-mvc/.gitignore: -------------------------------------------------------------------------------- 1 | */bin/* 2 | 3 | *.class 4 | 5 | # Package Files # 6 | *.war 7 | *.ear 8 | 9 | 10 | # Eclipse 11 | .settings/ 12 | *.project 13 | *.classpath 14 | .prefs 15 | *.prefs 16 | .metadata/ 17 | 18 | # Intellij 19 | .idea/ 20 | *.iml 21 | *.iws 22 | 23 | # Mac 24 | .DS_Store 25 | 26 | # Maven 27 | log/ 28 | target/ 29 | 30 | spring-openid/src/main/resources/application.properties 31 | .recommenders/ 32 | /spring-hibernate4/nbproject/ 33 | spring-security-openid/src/main/resources/application.properties 34 | 35 | spring-all/*.log 36 | 37 | *.jar 38 | 39 | SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties 40 | 41 | spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties 42 | 43 | spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties 44 | *.springBeans 45 | 46 | -------------------------------------------------------------------------------- /spring-mvc/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/main/resources=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /spring-mvc/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 3 | org.eclipse.jdt.core.compiler.compliance=1.8 4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 5 | org.eclipse.jdt.core.compiler.source=1.8 6 | -------------------------------------------------------------------------------- /spring-mvc/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /spring-mvc/.settings/org.eclipse.wst.common.project.facet.core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /spring-mvc/.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | java:com.stackify.guest.springmvc.Spring5Application 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /spring-mvc/README.md: -------------------------------------------------------------------------------- 1 | ## Building 2 | 3 | To build the module, use Maven's `package` goal: 4 | 5 | ``` 6 | mvn clean package 7 | ``` 8 | 9 | ## Running 10 | 11 | To run the application, use Spring Boot's `run` goal: 12 | 13 | ``` 14 | mvn spring-boot:run 15 | ``` 16 | 17 | The application will be accessible at [http://localhost:8080/](http://localhost:8080/) 18 | -------------------------------------------------------------------------------- /spring-mvc/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | com.stackify.guest 6 | spring-mvc 7 | 0.0.1-SNAPSHOT 8 | jar 9 | spring-mvc 10 | Spring MVC sample project 11 | 12 | 13 | org.springframework.boot 14 | spring-boot-starter-parent 15 | 2.0.1.RELEASE 16 | 17 | 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-thymeleaf 27 | 28 | 29 | 30 | 31 | 32 | spring-milestones 33 | Spring Milestones 34 | https://repo.spring.io/milestone 35 | 36 | false 37 | 38 | 39 | 40 | 41 | 42 | 43 | spring-milestones 44 | Spring Milestones 45 | https://repo.spring.io/milestone 46 | 47 | false 48 | 49 | 50 | 51 | 52 | 53 | UTF-8 54 | UTF-8 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /spring-mvc/src/main/java/com/stackify/guest/springmvc/Spring5Application.java: -------------------------------------------------------------------------------- 1 | package com.stackify.guest.springmvc; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.context.annotation.ComponentScan; 5 | import org.springframework.boot.SpringApplication; 6 | 7 | @SpringBootApplication 8 | @ComponentScan(basePackages = {"com.stackify.guest.springmvc"}) 9 | public class Spring5Application { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(Spring5Application.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /spring-mvc/src/main/java/com/stackify/guest/springmvc/model/LoginData.java: -------------------------------------------------------------------------------- 1 | package com.stackify.guest.springmvc.model; 2 | 3 | public class LoginData { 4 | 5 | private String login; 6 | 7 | private String password; 8 | 9 | public LoginData() { 10 | } 11 | 12 | public String getLogin() { 13 | return login; 14 | } 15 | 16 | public void setLogin(String login) { 17 | this.login = login; 18 | } 19 | 20 | public String getPassword() { 21 | return password; 22 | } 23 | 24 | public void setPassword(String password) { 25 | this.password = password; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /spring-mvc/src/main/java/com/stackify/guest/springmvc/web/InternalsController.java: -------------------------------------------------------------------------------- 1 | package com.stackify.guest.springmvc.web; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.PostMapping; 6 | import org.springframework.web.bind.annotation.RequestBody; 7 | import org.springframework.web.bind.annotation.ResponseBody; 8 | import org.springframework.web.servlet.ModelAndView; 9 | 10 | import com.stackify.guest.springmvc.model.LoginData; 11 | 12 | import java.util.Collections; 13 | 14 | @Controller 15 | public class InternalsController { 16 | 17 | private static final String LOGIN = "jack"; 18 | private static final String PASSWORD = "halloween"; 19 | 20 | @GetMapping("/") 21 | public String hello() { 22 | return "login"; 23 | } 24 | 25 | @PostMapping("/login") 26 | public ModelAndView login(LoginData loginData) { 27 | if (LOGIN.equals(loginData.getLogin()) && PASSWORD.equals(loginData.getPassword())) { 28 | return new ModelAndView("success", Collections.singletonMap("login", loginData.getLogin())); 29 | } else { 30 | return new ModelAndView("failure", Collections.singletonMap("login", loginData.getLogin())); 31 | } 32 | } 33 | 34 | @ResponseBody 35 | @PostMapping("/message") 36 | public MyOutputResource sendMessage(@RequestBody MyInputResource inputResource) { 37 | return new MyOutputResource("Received: " + inputResource.getRequestMessage()); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyInputResource.java: -------------------------------------------------------------------------------- 1 | package com.stackify.guest.springmvc.web; 2 | 3 | public class MyInputResource { 4 | 5 | private String requestMessage; 6 | 7 | public String getRequestMessage() { 8 | return requestMessage; 9 | } 10 | 11 | public void setRequestMessage(String requestMessage) { 12 | this.requestMessage = requestMessage; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-mvc/src/main/java/com/stackify/guest/springmvc/web/MyOutputResource.java: -------------------------------------------------------------------------------- 1 | package com.stackify.guest.springmvc.web; 2 | 3 | public class MyOutputResource { 4 | 5 | private String responseMessage; 6 | 7 | public MyOutputResource(String responseMessage) { 8 | this.responseMessage = responseMessage; 9 | } 10 | 11 | public String getResponseMessage() { 12 | return responseMessage; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /spring-mvc/src/main/java/com/stackify/guest/springmvc/web/RestfulWebServiceController.java: -------------------------------------------------------------------------------- 1 | package com.stackify.guest.springmvc.web; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | @RestController 7 | public class RestfulWebServiceController { 8 | 9 | @GetMapping("/message") 10 | public MyOutputResource getMessage() { 11 | return new MyOutputResource("Hello!"); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /spring-mvc/src/main/resources/templates/failure.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Login Failure 6 | 7 |

8 | User with login not found, please try again. 9 |

10 | -------------------------------------------------------------------------------- /spring-mvc/src/main/resources/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Login Form 4 | 5 | 6 |
7 | 8 | 9 | 10 |
11 | 12 | 13 | -------------------------------------------------------------------------------- /spring-mvc/src/main/resources/templates/success.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Login Success 6 | 7 |

8 | Hello, ! 9 |

10 | -------------------------------------------------------------------------------- /spring-security/README.md: -------------------------------------------------------------------------------- 1 | ## Building 2 | 3 | To build the module, use Maven's `package` goal: 4 | 5 | ``` 6 | mvn clean package 7 | ``` 8 | 9 | ## Running 10 | 11 | To run the application, use Spring Boot's `run` goal: 12 | 13 | ``` 14 | mvn spring-boot:run 15 | ``` 16 | 17 | The application will be accessible at [http://localhost:8080/](http://localhost:8080/) 18 | -------------------------------------------------------------------------------- /spring-security/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | com.stackify.guest 7 | spring-security 8 | 1.0-SNAPSHOT 9 | spring-security 10 | Spring Security Sample Project 11 | 12 | 13 | org.springframework.boot 14 | spring-boot-starter-parent 15 | 2.0.1.RELEASE 16 | 17 | 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-thymeleaf 27 | 28 | 29 | org.thymeleaf 30 | thymeleaf-spring5 31 | ${thymeleaf-spring5.version} 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-security 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-jdbc 40 | 41 | 42 | com.h2database 43 | h2 44 | runtime 45 | 46 | 47 | 48 | 49 | 50 | spring-milestones 51 | Spring Milestones 52 | https://repo.spring.io/milestone 53 | 54 | false 55 | 56 | 57 | 58 | 59 | 60 | 61 | spring-milestones 62 | Spring Milestones 63 | https://repo.spring.io/milestone 64 | 65 | false 66 | 67 | 68 | 69 | 70 | 71 | UTF-8 72 | UTF-8 73 | 3.0.8.RELEASE 74 | 75 | 76 | -------------------------------------------------------------------------------- /spring-security/src/main/java/com/stackify/guest/springsecurity/Application.java: -------------------------------------------------------------------------------- 1 | package com.stackify.guest.springsecurity; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.ComponentScan; 6 | 7 | @SpringBootApplication 8 | @ComponentScan(basePackages = {"com.stackify.guest.springsecurity"}) 9 | public class Application { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(Application.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebMvcConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.stackify.guest.springsecurity.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 6 | 7 | @Configuration 8 | public class WebMvcConfiguration implements WebMvcConfigurer { 9 | 10 | @Override 11 | public void addViewControllers(ViewControllerRegistry registry) { 12 | registry.addViewController("/customLogin").setViewName("customLogin"); 13 | registry.addViewController("/loginSuccess").setViewName("index"); 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.stackify.guest.springsecurity.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 6 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 7 | import org.springframework.security.core.userdetails.UserDetailsService; 8 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 9 | import org.springframework.security.crypto.password.PasswordEncoder; 10 | import org.springframework.security.provisioning.JdbcUserDetailsManager; 11 | 12 | import javax.sql.DataSource; 13 | 14 | @EnableWebSecurity 15 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 16 | 17 | @Bean 18 | public UserDetailsService jdbcUserDetailsService(DataSource dataSource) { 19 | JdbcUserDetailsManager manager = new JdbcUserDetailsManager(); 20 | manager.setDataSource(dataSource); 21 | return manager; 22 | } 23 | 24 | @Bean 25 | public PasswordEncoder passwordEncoder() { 26 | return new BCryptPasswordEncoder(); 27 | } 28 | 29 | @Override 30 | protected void configure(HttpSecurity http) throws Exception { 31 | http.authorizeRequests() 32 | .antMatchers("/css/**").permitAll() 33 | .anyRequest().authenticated() 34 | .and().formLogin() 35 | .loginPage("/customLogin") 36 | .defaultSuccessUrl("/loginSuccess", true) 37 | .permitAll(); 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /spring-security/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO users VALUES ('jill', '$2a$04$qUlqAEEYF1YvrpJMosodoewgL6aO.qgHytl2k5L7kdXEWnJsFdxvq', TRUE); 2 | INSERT INTO authorities VALUES ('jill', 'USERS'); 3 | -------------------------------------------------------------------------------- /spring-security/src/main/resources/schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE users ( 2 | username VARCHAR(256) PRIMARY KEY, 3 | password VARCHAR(256), 4 | enabled BOOLEAN 5 | ); 6 | 7 | CREATE TABLE authorities ( 8 | username VARCHAR(256) REFERENCES users (username), 9 | authority VARCHAR(256) 10 | ); 11 | -------------------------------------------------------------------------------- /spring-security/src/main/resources/static/css/styles.css: -------------------------------------------------------------------------------- 1 | .bad-login { 2 | color: red; 3 | } -------------------------------------------------------------------------------- /spring-security/src/main/resources/templates/customLogin.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 |
9 |
10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 |
Log out successful.
19 |
20 | 21 | -------------------------------------------------------------------------------- /spring-security/src/main/resources/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 4 |

Hello, !

7 |
8 | 9 | 10 |
11 | -------------------------------------------------------------------------------- /thread-pools/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.stackify 5 | thread-pools 6 | 0.0.1-SNAPSHOT 7 | 8 | 9 | com.stackify 10 | parent-module 11 | 1.0.0-SNAPSHOT 12 | 13 | 14 | 15 | 16 | ch.qos.logback 17 | logback-classic 18 | ${logback-classic.version} 19 | 20 | 21 | 22 | 23 | 24 | 25 | org.apache.maven.plugins 26 | maven-compiler-plugin 27 | ${maven-compiler-plugin.version} 28 | 29 | ${maven.compiler.source.version} 30 | ${maven.compiler.target.version} 31 | 32 | 33 | 34 | 35 | 36 | 37 | 1.2.3 38 | 1.8 39 | 1.8 40 | 41 | 42 | -------------------------------------------------------------------------------- /thread-pools/src/main/java/com/stackify/models/Employee.java: -------------------------------------------------------------------------------- 1 | package com.stackify.models; 2 | 3 | public class Employee { 4 | private String name; 5 | private double salary; 6 | 7 | public String getName() { 8 | return name; 9 | } 10 | 11 | public void setName(String name) { 12 | this.name = name; 13 | } 14 | 15 | public double getSalary() { 16 | return salary; 17 | } 18 | 19 | public void setSalary(double salary) { 20 | this.salary = salary; 21 | } 22 | 23 | public Employee(String name, double salary) { 24 | super(); 25 | this.name = name; 26 | this.salary = salary; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /thread-pools/src/main/java/com/stackify/services/EmployeeService.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import com.stackify.models.Employee; 4 | 5 | public class EmployeeService { 6 | public double calculateBonus(Employee employee) { 7 | return 0.1 * employee.getSalary(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java: -------------------------------------------------------------------------------- 1 | package com.stackify.threadpools; 2 | 3 | import java.math.BigInteger; 4 | import java.util.ArrayList; 5 | import java.util.Collection; 6 | import java.util.List; 7 | import java.util.concurrent.ForkJoinTask; 8 | import java.util.concurrent.RecursiveTask; 9 | import java.util.stream.IntStream; 10 | 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | 14 | public class FactorialTask extends RecursiveTask { 15 | 16 | private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); 17 | 18 | private static final long serialVersionUID = 1L; 19 | 20 | private int start = 1; 21 | private int n; 22 | 23 | private static final int THRESHOLD = 20; 24 | 25 | public FactorialTask(int n) { 26 | this.n = n; 27 | } 28 | 29 | public FactorialTask(int start, int n) { 30 | logger.info("New FactorialTask Created"); 31 | this.start = start; 32 | this.n = n; 33 | } 34 | 35 | @Override 36 | protected BigInteger compute() { 37 | if ((n - start) >= THRESHOLD) { 38 | return ForkJoinTask.invokeAll(createSubtasks()) 39 | .stream() 40 | .map(ForkJoinTask::join) 41 | .reduce(BigInteger.ONE, BigInteger::multiply); 42 | } else { 43 | return calculate(start, n); 44 | } 45 | } 46 | 47 | private Collection createSubtasks() { 48 | List dividedTasks = new ArrayList<>(); 49 | 50 | int mid = (start + n) / 2; 51 | 52 | dividedTasks.add(new FactorialTask(start, mid)); 53 | dividedTasks.add(new FactorialTask(mid + 1, n)); 54 | return dividedTasks; 55 | } 56 | 57 | private BigInteger calculate(int start, int n) { 58 | logger.info("Calculate factorial from " + start + " to " + n); 59 | return IntStream.rangeClosed(start, n) 60 | .mapToObj(BigInteger::valueOf) 61 | .reduce(BigInteger.ONE, BigInteger::multiply); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /tomcat-app/WebContent/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /tomcat-app/WebContent/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | tomcat-app 7 | 8 | tomcat-app 9 | org.glassfish.jersey.servlet.ServletContainer 10 | 11 | javax.ws.rs.Application 12 | com.stackify.ApplicationInitializer 13 | 14 | 1 15 | 16 | 17 | tomcat-app 18 | /* 19 | 20 | 21 | javamelody 22 | net.bull.javamelody.MonitoringFilter 23 | 24 | gzip-compression-disabled 25 | true 26 | 27 | 28 | -------------------------------------------------------------------------------- /tomcat-app/src/main/java/com/stackify/ApplicationInitializer.java: -------------------------------------------------------------------------------- 1 | package com.stackify; 2 | 3 | import org.glassfish.jersey.server.ResourceConfig; 4 | 5 | public class ApplicationInitializer extends ResourceConfig { 6 | public ApplicationInitializer() { 7 | packages("com.stackify.services"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tomcat-app/src/main/java/com/stackify/daos/UserDAO.java: -------------------------------------------------------------------------------- 1 | package com.stackify.daos; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import org.apache.logging.log4j.LogManager; 11 | import org.apache.logging.log4j.Logger; 12 | 13 | import com.stackify.models.User; 14 | import com.stackify.utils.ConnectionUtil; 15 | 16 | public class UserDAO { 17 | 18 | private Logger logger = LogManager.getLogger(UserDAO.class); 19 | 20 | public void createTable() { 21 | try (Connection con = ConnectionUtil.getConnection()) { 22 | String createQuery = "CREATE TABLE IF NOT EXISTS users(email varchar(50) primary key, name varchar(50))"; 23 | PreparedStatement pstmt = con.prepareStatement(createQuery); 24 | 25 | pstmt.execute(); 26 | } catch (SQLException exc) { 27 | logger.error(exc.getMessage()); 28 | } 29 | 30 | } 31 | 32 | public void add(User user) { 33 | try (Connection con = ConnectionUtil.getConnection()) { 34 | 35 | String insertQuery = "INSERT INTO users(email,name) VALUES(?,?)"; 36 | PreparedStatement pstmt = con.prepareStatement(insertQuery); 37 | pstmt.setString(1, user.getEmail()); 38 | pstmt.setString(2, user.getName()); 39 | 40 | pstmt.executeUpdate(); 41 | } catch (SQLException exc) { 42 | logger.error(exc.getMessage()); 43 | } 44 | } 45 | 46 | public List findAll() { 47 | List users = new ArrayList<>(); 48 | 49 | try (Connection con = ConnectionUtil.getConnection()) { 50 | String query = "SELECT * FROM users"; 51 | PreparedStatement pstmt = con.prepareStatement(query); 52 | 53 | ResultSet rs = pstmt.executeQuery(); 54 | while (rs.next()) { 55 | User user = new User(); 56 | user.setEmail(rs.getString("email")); 57 | user.setName(rs.getString("name")); 58 | users.add(user); 59 | } 60 | } catch (SQLException exc) { 61 | logger.error(exc.getMessage()); 62 | } 63 | 64 | return users; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /tomcat-app/src/main/java/com/stackify/models/User.java: -------------------------------------------------------------------------------- 1 | package com.stackify.models; 2 | 3 | import javax.ws.rs.core.Link; 4 | 5 | public class User { 6 | private String email; 7 | private String name; 8 | private Link link; 9 | 10 | public User() { 11 | } 12 | 13 | public User(String email, String name) { 14 | super(); 15 | this.email = email; 16 | this.name = name; 17 | } 18 | 19 | public String getEmail() { 20 | return email; 21 | } 22 | 23 | public void setEmail(String email) { 24 | this.email = email; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public Link getLink() { 36 | return link; 37 | } 38 | 39 | public void setLink(Link link) { 40 | this.link = link; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /tomcat-app/src/main/java/com/stackify/services/CorsFilter.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.ws.rs.container.ContainerRequestContext; 6 | import javax.ws.rs.container.ContainerResponseContext; 7 | import javax.ws.rs.container.ContainerResponseFilter; 8 | import javax.ws.rs.ext.Provider; 9 | 10 | @Provider 11 | public class CorsFilter implements ContainerResponseFilter { 12 | 13 | @Override 14 | public void filter(final ContainerRequestContext requestContext, 15 | final ContainerResponseContext response) throws IOException { 16 | response.getHeaders().add("Access-Control-Allow-Origin", "*"); 17 | response.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tomcat-app/src/main/java/com/stackify/services/UserService.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import java.util.List; 4 | 5 | import javax.ws.rs.Consumes; 6 | import javax.ws.rs.GET; 7 | import javax.ws.rs.POST; 8 | import javax.ws.rs.Path; 9 | import javax.ws.rs.Produces; 10 | import javax.ws.rs.core.MediaType; 11 | import javax.ws.rs.core.Response; 12 | 13 | import com.stackify.daos.UserDAO; 14 | import com.stackify.models.User; 15 | 16 | @Path("/users") 17 | public class UserService { 18 | private UserDAO userDao = new UserDAO(); 19 | 20 | public UserService (){ 21 | userDao.createTable(); 22 | } 23 | 24 | @POST 25 | @Consumes(MediaType.APPLICATION_JSON) 26 | public Response addUser(User user) { 27 | userDao.add(user); 28 | return Response.ok() 29 | .build(); 30 | } 31 | 32 | @GET 33 | @Produces(MediaType.APPLICATION_JSON) 34 | public List getUsers() { 35 | return userDao.findAll(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /tomcat-app/src/main/java/com/stackify/utils/ConnectionUtil.java: -------------------------------------------------------------------------------- 1 | package com.stackify.utils; 2 | 3 | import java.sql.Connection; 4 | import java.sql.SQLException; 5 | 6 | import javax.naming.Context; 7 | import javax.naming.InitialContext; 8 | import javax.naming.NamingException; 9 | import javax.sql.DataSource; 10 | 11 | import org.apache.logging.log4j.LogManager; 12 | import org.apache.logging.log4j.Logger; 13 | 14 | public class ConnectionUtil { 15 | 16 | private static Logger logger = LogManager.getLogger(ConnectionUtil.class); 17 | 18 | public static Connection getConnection() { 19 | try { 20 | String jndiName = "java:/comp/env/jdbc/MyDataSource"; 21 | 22 | Context initialContext = new InitialContext(); 23 | DataSource datasource = (DataSource)initialContext.lookup(jndiName); 24 | if (datasource != null) { 25 | return datasource.getConnection(); 26 | } 27 | else { 28 | logger.error("Failed to lookup datasource."); 29 | } 30 | } 31 | 32 | catch (NamingException | SQLException exc) { 33 | logger.error(exc.getMessage()); 34 | } 35 | return null; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /webservices/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.stackify 5 | webservices 6 | 1.0.0-SNAPSHOT 7 | 8 | webservices 9 | pom 10 | 11 | 12 | rest-client 13 | rest-server 14 | spring-rest-service 15 | 16 | 17 | -------------------------------------------------------------------------------- /webservices/rest-client/WebContent/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /webservices/rest-client/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | com.stackify 4 | rest-client 5 | 0.0.1-SNAPSHOT 6 | war 7 | 8 | 9 | com.stackify 10 | parent-module 11 | 1.0.0-SNAPSHOT 12 | ../../ 13 | 14 | 15 | 16 | 17 | 18 | maven-war-plugin 19 | ${maven-war-plugin.version} 20 | 21 | WebContent 22 | false 23 | 24 | 25 | 26 | 27 | 28 | 29 | 2.6 30 | 31 | 32 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/.angular-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "project": { 4 | "name": "rest-client" 5 | }, 6 | "apps": [ 7 | { 8 | "root": "src", 9 | "outDir": "dist", 10 | "assets": [ 11 | "assets", 12 | "favicon.ico" 13 | ], 14 | "index": "index.html", 15 | "main": "main.ts", 16 | "polyfills": "polyfills.ts", 17 | "test": "test.ts", 18 | "tsconfig": "tsconfig.app.json", 19 | "testTsconfig": "tsconfig.spec.json", 20 | "prefix": "app", 21 | "styles": [ 22 | "styles.css" 23 | ], 24 | "scripts": [], 25 | "environmentSource": "environments/environment.ts", 26 | "environments": { 27 | "dev": "environments/environment.ts", 28 | "prod": "environments/environment.prod.ts" 29 | } 30 | } 31 | ], 32 | "e2e": { 33 | "protractor": { 34 | "config": "./protractor.conf.js" 35 | } 36 | }, 37 | "lint": [ 38 | { 39 | "project": "src/tsconfig.app.json" 40 | }, 41 | { 42 | "project": "src/tsconfig.spec.json" 43 | }, 44 | { 45 | "project": "e2e/tsconfig.e2e.json" 46 | } 47 | ], 48 | "test": { 49 | "karma": { 50 | "config": "./karma.conf.js" 51 | } 52 | }, 53 | "defaults": { 54 | "styleExt": "css", 55 | "component": {} 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | 8 | # dependencies 9 | /node_modules 10 | 11 | # IDEs and editors 12 | /.idea 13 | .project 14 | .classpath 15 | .c9/ 16 | *.launch 17 | .settings/ 18 | *.sublime-workspace 19 | 20 | # IDE - VSCode 21 | .vscode/* 22 | !.vscode/settings.json 23 | !.vscode/tasks.json 24 | !.vscode/launch.json 25 | !.vscode/extensions.json 26 | 27 | # misc 28 | /.sass-cache 29 | /connect.lock 30 | /coverage 31 | /libpeerconnection.log 32 | npm-debug.log 33 | testem.log 34 | /typings 35 | 36 | # e2e 37 | /e2e/*.js 38 | /e2e/*.map 39 | 40 | # System Files 41 | .DS_Store 42 | Thumbs.db 43 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/README.md: -------------------------------------------------------------------------------- 1 | # RestClient 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.1.3. 4 | 5 | ## Development server 6 | 7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 8 | 9 | ## Code scaffolding 10 | 11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|module`. 12 | 13 | ## Build 14 | 15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | Before running the tests make sure you are serving the app via `ng serve`. 25 | 26 | ## Further help 27 | 28 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 29 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { RestClientPage } from './app.po'; 2 | 3 | describe('rest-client App', () => { 4 | let page: RestClientPage; 5 | 6 | beforeEach(() => { 7 | page = new RestClientPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('Welcome to app!!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class RestClientPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "node" 10 | ] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/0.13/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular/cli'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular/cli/plugins/karma') 14 | ], 15 | client:{ 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | reports: [ 'html', 'lcovonly' ], 20 | fixWebpackSourcePaths: true 21 | }, 22 | angularCli: { 23 | environment: 'dev' 24 | }, 25 | reporters: ['progress', 'kjhtml'], 26 | port: 9876, 27 | colors: true, 28 | logLevel: config.LOG_INFO, 29 | autoWatch: true, 30 | browsers: ['Chrome'], 31 | singleRun: false 32 | }); 33 | }; 34 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rest-client", 3 | "version": "0.0.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "ng": "ng", 7 | "start": "ng serve", 8 | "build": "ng build", 9 | "test": "ng test", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/animations": "^4.0.0", 16 | "@angular/common": "^4.0.0", 17 | "@angular/compiler": "^4.0.0", 18 | "@angular/core": "^4.0.0", 19 | "@angular/forms": "^4.0.0", 20 | "@angular/http": "^4.0.0", 21 | "@angular/platform-browser": "^4.0.0", 22 | "@angular/platform-browser-dynamic": "^4.0.0", 23 | "@angular/router": "^4.0.0", 24 | "core-js": "^2.4.1", 25 | "rxjs": "^5.1.0", 26 | "zone.js": "^0.8.4" 27 | }, 28 | "devDependencies": { 29 | "@angular/cli": "1.1.3", 30 | "@angular/compiler-cli": "^4.0.0", 31 | "@angular/language-service": "^4.0.0", 32 | "@types/jasmine": "2.5.45", 33 | "@types/node": "~6.0.60", 34 | "codelyzer": "~3.0.1", 35 | "jasmine-core": "~2.6.2", 36 | "jasmine-spec-reporter": "~4.1.0", 37 | "karma": "~1.7.0", 38 | "karma-chrome-launcher": "~2.1.1", 39 | "karma-cli": "~1.0.1", 40 | "karma-coverage-istanbul-reporter": "^1.2.1", 41 | "karma-jasmine": "~1.1.0", 42 | "karma-jasmine-html-reporter": "^0.2.2", 43 | "protractor": "~5.1.2", 44 | "ts-node": "~3.0.4", 45 | "tslint": "~5.3.2", 46 | "typescript": "~2.3.3" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './e2e/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: 'e2e/tsconfig.e2e.json' 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/stackify/8e84872a1d27a10d08b75fdbcceff092e74637dc/webservices/rest-client/rest-client/src/app/app.component.css -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Angular QuickStart 5 | 6 | 7 | 8 | 9 | 10 | 11 | loading users component 12 | 13 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(async(() => { 7 | TestBed.configureTestingModule({ 8 | declarations: [ 9 | AppComponent 10 | ], 11 | }).compileComponents(); 12 | })); 13 | 14 | it('should create the app', async(() => { 15 | const fixture = TestBed.createComponent(AppComponent); 16 | const app = fixture.debugElement.componentInstance; 17 | expect(app).toBeTruthy(); 18 | })); 19 | 20 | it(`should have as title 'app'`, async(() => { 21 | const fixture = TestBed.createComponent(AppComponent); 22 | const app = fixture.debugElement.componentInstance; 23 | expect(app.title).toEqual('app'); 24 | })); 25 | 26 | it('should render title in a h1 tag', async(() => { 27 | const fixture = TestBed.createComponent(AppComponent); 28 | fixture.detectChanges(); 29 | const compiled = fixture.debugElement.nativeElement; 30 | expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!!'); 31 | })); 32 | }); 33 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | templateUrl: './app.component.html', 6 | styleUrls: ['./app.component.css'] 7 | }) 8 | export class AppComponent { 9 | title = 'app'; 10 | } 11 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | import { HttpModule } from '@angular/http'; 4 | import { FormsModule } from '@angular/forms'; 5 | 6 | import { AppComponent } from './app.component'; 7 | import { UsersComponent } from './users.component'; 8 | import { RouterModule } from '@angular/router'; 9 | 10 | @NgModule({ 11 | declarations: [ 12 | AppComponent, 13 | UsersComponent 14 | ], 15 | imports: [ 16 | BrowserModule, 17 | HttpModule, 18 | FormsModule, 19 | RouterModule.forRoot([ 20 | { path: '', component: AppComponent }, 21 | { path: 'users', component: UsersComponent }])], 22 | providers: [], 23 | bootstrap: [AppComponent] 24 | }) 25 | export class AppModule { } 26 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/app/app.service.ts: -------------------------------------------------------------------------------- 1 | import {Injectable} from '@angular/core'; 2 | import { Http, Response, Headers, RequestOptions } from '@angular/http'; 3 | import 'rxjs/add/operator/map'; 4 | 5 | export class User { 6 | constructor( 7 | public email: string, 8 | public name: string) { } 9 | } 10 | 11 | @Injectable() 12 | export class UserService { 13 | constructor( 14 | private _http: Http){} 15 | 16 | url = 'http://localhost:8080/rest-server/users'; 17 | 18 | addUser(user){ 19 | let headers = new Headers({'Content-Type': 'application/json'}); 20 | let options = new RequestOptions({ headers: headers}); 21 | 22 | return this._http.post(this.url, JSON.stringify(user), options) 23 | .map( 24 | (_response: Response) => { 25 | return _response; 26 | }, 27 | err => alert('Error adding user')); 28 | } 29 | 30 | getUsers() { 31 | return this._http.get(this.url) 32 | .map((_response: Response) => { 33 | return _response.json(); 34 | }); 35 | } 36 | } -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/app/users.component.html: -------------------------------------------------------------------------------- 1 |
2 | Email:
3 | Name:
4 | 5 |
6 | 7 |
8 | 9 | 10 | 12 | 13 | 14 |
{{user.email}} 11 | {{user.name}}
15 | 16 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/app/users.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import {UserService, User} from './app.service'; 3 | 4 | @Component({ 5 | selector: 'users-page', 6 | providers: [UserService], 7 | templateUrl: './users.component.html', 8 | styleUrls: ['./app.component.css'] 9 | }) 10 | export class UsersComponent { 11 | title = 'Users'; 12 | 13 | constructor( 14 | private _service:UserService){} 15 | 16 | public user = {email: "", name: ""}; 17 | public res=[]; 18 | 19 | addUser() { 20 | this._service.addUser(this.user) 21 | .subscribe( () => this.getUsers()); 22 | } 23 | 24 | getUsers() { 25 | this._service.getUsers() 26 | .subscribe( 27 | users => { 28 | this.res=[]; 29 | users.forEach(usr => { 30 | this.res.push( 31 | new User( 32 | usr.email, 33 | usr.name 34 | ) 35 | ) 36 | }); 37 | }); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/stackify/8e84872a1d27a10d08b75fdbcceff092e74637dc/webservices/rest-client/rest-client/src/assets/.gitkeep -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `.angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false 8 | }; 9 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Baeldung/stackify/8e84872a1d27a10d08b75fdbcceff092e74637dc/webservices/rest-client/rest-client/src/favicon.ico -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | RestClient 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule); 12 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/weak-map'; 35 | // import 'core-js/es6/set'; 36 | 37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 38 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 39 | 40 | /** IE10 and IE11 requires the following to support `@angular/animation`. */ 41 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 42 | 43 | 44 | /** Evergreen browsers require these. **/ 45 | import 'core-js/es6/reflect'; 46 | import 'core-js/es7/reflect'; 47 | 48 | 49 | /** ALL Firefox browsers require the following to support `@angular/animation`. **/ 50 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 51 | 52 | 53 | 54 | /*************************************************************************************************** 55 | * Zone JS is required by Angular itself. 56 | */ 57 | import 'zone.js/dist/zone'; // Included with Angular CLI. 58 | 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | 65 | /** 66 | * Date, currency, decimal and percent pipes. 67 | * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 68 | */ 69 | // import 'intl'; // Run `npm install --save intl`. 70 | /** 71 | * Need to import at least one locale-data with intl. 72 | */ 73 | // import 'intl/locale-data/jsonp/en'; 74 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/long-stack-trace-zone'; 4 | import 'zone.js/dist/proxy.js'; 5 | import 'zone.js/dist/sync-test'; 6 | import 'zone.js/dist/jasmine-patch'; 7 | import 'zone.js/dist/async-test'; 8 | import 'zone.js/dist/fake-async-test'; 9 | import { getTestBed } from '@angular/core/testing'; 10 | import { 11 | BrowserDynamicTestingModule, 12 | platformBrowserDynamicTesting 13 | } from '@angular/platform-browser-dynamic/testing'; 14 | 15 | // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. 16 | declare const __karma__: any; 17 | declare const require: any; 18 | 19 | // Prevent Karma from running prematurely. 20 | __karma__.loaded = function () {}; 21 | 22 | // First, initialize the Angular testing environment. 23 | getTestBed().initTestEnvironment( 24 | BrowserDynamicTestingModule, 25 | platformBrowserDynamicTesting() 26 | ); 27 | // Then we find all the tests. 28 | const context = require.context('./', true, /\.spec\.ts$/); 29 | // And load the modules. 30 | context.keys().map(context); 31 | // Finally, start Karma to run the tests. 32 | __karma__.start(); 33 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "es2015", 6 | "baseUrl": "", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "**/*.spec.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "baseUrl": "", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | }, 13 | "files": [ 14 | "test.ts" 15 | ], 16 | "include": [ 17 | "**/*.spec.ts", 18 | "**/*.d.ts" 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/src/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule; 3 | interface NodeModule { 4 | id: string; 5 | } 6 | -------------------------------------------------------------------------------- /webservices/rest-client/rest-client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "baseUrl": "src", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "moduleResolution": "node", 9 | "emitDecoratorMetadata": true, 10 | "experimentalDecorators": true, 11 | "target": "es5", 12 | "typeRoots": [ 13 | "node_modules/@types" 14 | ], 15 | "lib": [ 16 | "es2016", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /webservices/rest-server/WebContent/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /webservices/rest-server/WebContent/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | rest-server 7 | 8 | rest-server 9 | org.glassfish.jersey.servlet.ServletContainer 10 | 11 | javax.ws.rs.Application 12 | com.stackify.ApplicationInitializer 13 | 14 | 1 15 | 16 | 17 | rest-server 18 | /* 19 | 20 | -------------------------------------------------------------------------------- /webservices/rest-server/src/main/java/com/stackify/ApplicationInitializer.java: -------------------------------------------------------------------------------- 1 | package com.stackify; 2 | 3 | import org.glassfish.jersey.server.ResourceConfig; 4 | 5 | public class ApplicationInitializer extends ResourceConfig { 6 | public ApplicationInitializer() { 7 | packages("com.stackify.services"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /webservices/rest-server/src/main/java/com/stackify/models/User.java: -------------------------------------------------------------------------------- 1 | package com.stackify.models; 2 | 3 | import javax.ws.rs.core.Link; 4 | 5 | public class User { 6 | private String email; 7 | private String name; 8 | private Link link; 9 | 10 | public User() { 11 | } 12 | 13 | public User(String email, String name) { 14 | super(); 15 | this.email = email; 16 | this.name = name; 17 | } 18 | 19 | public String getEmail() { 20 | return email; 21 | } 22 | 23 | public void setEmail(String email) { 24 | this.email = email; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public Link getLink() { 36 | return link; 37 | } 38 | 39 | public void setLink(Link link) { 40 | this.link = link; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /webservices/rest-server/src/main/java/com/stackify/services/CorsFilter.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.ws.rs.container.ContainerRequestContext; 6 | import javax.ws.rs.container.ContainerResponseContext; 7 | import javax.ws.rs.container.ContainerResponseFilter; 8 | import javax.ws.rs.ext.Provider; 9 | 10 | @Provider 11 | public class CorsFilter implements ContainerResponseFilter { 12 | 13 | @Override 14 | public void filter(final ContainerRequestContext requestContext, 15 | final ContainerResponseContext response) throws IOException { 16 | response.getHeaders().add("Access-Control-Allow-Origin", "*"); 17 | response.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /webservices/rest-server/src/main/java/com/stackify/services/UserService.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import javax.ws.rs.Consumes; 7 | import javax.ws.rs.GET; 8 | import javax.ws.rs.POST; 9 | import javax.ws.rs.Path; 10 | import javax.ws.rs.Produces; 11 | import javax.ws.rs.core.MediaType; 12 | import javax.ws.rs.core.Response; 13 | 14 | import com.stackify.models.User; 15 | 16 | @Path("/users") 17 | public class UserService { 18 | private static List users = new ArrayList<>(); 19 | 20 | @POST 21 | @Consumes(MediaType.APPLICATION_JSON) 22 | public Response addUser(User user) { 23 | users.add(user); 24 | return Response.ok() 25 | .build(); 26 | } 27 | 28 | @GET 29 | @Produces(MediaType.APPLICATION_JSON) 30 | public List getUsers() { 31 | return users; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /webservices/rest-server/src/test/java/com/stackify/services/UserServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import org.junit.Test; 4 | 5 | import io.restassured.RestAssured; 6 | import static io.restassured.RestAssured.*; 7 | import static org.hamcrest.CoreMatchers.*; 8 | 9 | public class UserServiceTest { 10 | @Test 11 | public void whenAddUser_thenGetUserOk() { 12 | RestAssured.baseURI = "http://localhost:8080/rest-server"; 13 | 14 | //@formatter:off 15 | 16 | String json = "{\"email\":\"john@gmail.com\",\"name\":\"John\"}"; 17 | given() 18 | .contentType("application/json") 19 | .body(json) 20 | .when() 21 | .post("/users") 22 | .then() 23 | .statusCode(200); 24 | 25 | when() 26 | .get("/users") 27 | .then() 28 | .contentType("application/json") 29 | .body("name", hasItem("John")) 30 | .body("email", hasItem("john@gmail.com")); 31 | 32 | //@formatter:on 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /webservices/soap_client/src/main/java/com/stackify/JAXWSClient.java: -------------------------------------------------------------------------------- 1 | package com.stackify; 2 | 3 | import com.stackify.services.DefaultUserImplService; 4 | import com.stackify.services.User; 5 | import com.stackify.services.UserService; 6 | import com.stackify.services.Users; 7 | 8 | public class JAXWSClient { 9 | public static void main(String[] args) { 10 | DefaultUserImplService service = new DefaultUserImplService(); 11 | User user = new User(); 12 | user.setEmail("john@gmail.com"); 13 | user.setName("John"); 14 | UserService port = service.getDefaultUserImplPort(); 15 | port.addUser(user); 16 | Users users = port.getUsers(); 17 | System.out.println(users.getUsers().iterator().next().getName()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /webservices/soap_client/src/main/java/com/stackify/services/ObjectFactory.java: -------------------------------------------------------------------------------- 1 | 2 | package com.stackify.services; 3 | 4 | import javax.xml.bind.annotation.XmlRegistry; 5 | 6 | 7 | /** 8 | * This object contains factory methods for each 9 | * Java content interface and Java element interface 10 | * generated in the com.stackify.services package. 11 | *

An ObjectFactory allows you to programatically 12 | * construct new instances of the Java representation 13 | * for XML content. The Java representation of XML 14 | * content can consist of schema derived interfaces 15 | * and classes representing the binding of schema 16 | * type definitions, element declarations and model 17 | * groups. Factory methods for each of these are 18 | * provided in this class. 19 | * 20 | */ 21 | @XmlRegistry 22 | public class ObjectFactory { 23 | 24 | 25 | /** 26 | * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.stackify.services 27 | * 28 | */ 29 | public ObjectFactory() { 30 | } 31 | 32 | /** 33 | * Create an instance of {@link User } 34 | * 35 | */ 36 | public User createUser() { 37 | return new User(); 38 | } 39 | 40 | /** 41 | * Create an instance of {@link Users } 42 | * 43 | */ 44 | public Users createUsers() { 45 | return new Users(); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /webservices/soap_client/src/main/java/com/stackify/services/User.java: -------------------------------------------------------------------------------- 1 | 2 | package com.stackify.services; 3 | 4 | import javax.xml.bind.annotation.XmlAccessType; 5 | import javax.xml.bind.annotation.XmlAccessorType; 6 | import javax.xml.bind.annotation.XmlType; 7 | 8 | 9 | /** 10 | *

Java class for user complex type. 11 | * 12 | *

The following schema fragment specifies the expected content contained within this class. 13 | * 14 | *

15 |  * <complexType name="user">
16 |  *   <complexContent>
17 |  *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
18 |  *       <sequence>
19 |  *         <element name="email" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
20 |  *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
21 |  *       </sequence>
22 |  *     </restriction>
23 |  *   </complexContent>
24 |  * </complexType>
25 |  * 
26 | * 27 | * 28 | */ 29 | @XmlAccessorType(XmlAccessType.FIELD) 30 | @XmlType(name = "user", propOrder = { 31 | "email", 32 | "name" 33 | }) 34 | public class User { 35 | 36 | protected String email; 37 | protected String name; 38 | 39 | /** 40 | * Gets the value of the email property. 41 | * 42 | * @return 43 | * possible object is 44 | * {@link String } 45 | * 46 | */ 47 | public String getEmail() { 48 | return email; 49 | } 50 | 51 | /** 52 | * Sets the value of the email property. 53 | * 54 | * @param value 55 | * allowed object is 56 | * {@link String } 57 | * 58 | */ 59 | public void setEmail(String value) { 60 | this.email = value; 61 | } 62 | 63 | /** 64 | * Gets the value of the name property. 65 | * 66 | * @return 67 | * possible object is 68 | * {@link String } 69 | * 70 | */ 71 | public String getName() { 72 | return name; 73 | } 74 | 75 | /** 76 | * Sets the value of the name property. 77 | * 78 | * @param value 79 | * allowed object is 80 | * {@link String } 81 | * 82 | */ 83 | public void setName(String value) { 84 | this.name = value; 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /webservices/soap_client/src/main/java/com/stackify/services/UserService.java: -------------------------------------------------------------------------------- 1 | 2 | package com.stackify.services; 3 | 4 | import javax.jws.WebMethod; 5 | import javax.jws.WebParam; 6 | import javax.jws.WebResult; 7 | import javax.jws.WebService; 8 | import javax.jws.soap.SOAPBinding; 9 | import javax.xml.bind.annotation.XmlSeeAlso; 10 | import javax.xml.ws.Action; 11 | 12 | 13 | /** 14 | * This class was generated by the JAX-WS RI. 15 | * JAX-WS RI 2.2.9-b130926.1035 16 | * Generated source version: 2.2 17 | * 18 | */ 19 | @WebService(name = "UserService", targetNamespace = "http://services.stackify.com/") 20 | @SOAPBinding(style = SOAPBinding.Style.RPC) 21 | @XmlSeeAlso({ 22 | ObjectFactory.class 23 | }) 24 | public interface UserService { 25 | 26 | 27 | /** 28 | * 29 | * @param arg0 30 | */ 31 | @WebMethod 32 | @Action(input = "http://services.stackify.com/UserService/addUserRequest", output = "http://services.stackify.com/UserService/addUserResponse") 33 | public void addUser( 34 | @WebParam(name = "arg0", partName = "arg0") 35 | User arg0); 36 | 37 | /** 38 | * 39 | * @return 40 | * returns com.stackify.services.Users 41 | */ 42 | @WebMethod 43 | @WebResult(partName = "return") 44 | @Action(input = "http://services.stackify.com/UserService/getUsersRequest", output = "http://services.stackify.com/UserService/getUsersResponse") 45 | public Users getUsers(); 46 | 47 | } 48 | -------------------------------------------------------------------------------- /webservices/soap_client/src/main/java/com/stackify/services/Users.java: -------------------------------------------------------------------------------- 1 | 2 | package com.stackify.services; 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import javax.xml.bind.annotation.XmlAccessType; 7 | import javax.xml.bind.annotation.XmlAccessorType; 8 | import javax.xml.bind.annotation.XmlElement; 9 | import javax.xml.bind.annotation.XmlType; 10 | 11 | 12 | /** 13 | *

Java class for users complex type. 14 | * 15 | *

The following schema fragment specifies the expected content contained within this class. 16 | * 17 | *

18 |  * <complexType name="users">
19 |  *   <complexContent>
20 |  *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
21 |  *       <sequence>
22 |  *         <element name="users" type="{http://services.stackify.com/}user" maxOccurs="unbounded" minOccurs="0"/>
23 |  *       </sequence>
24 |  *     </restriction>
25 |  *   </complexContent>
26 |  * </complexType>
27 |  * 
28 | * 29 | * 30 | */ 31 | @XmlAccessorType(XmlAccessType.FIELD) 32 | @XmlType(name = "users", propOrder = { 33 | "users" 34 | }) 35 | public class Users { 36 | 37 | @XmlElement(nillable = true) 38 | protected List users; 39 | 40 | /** 41 | * Gets the value of the users property. 42 | * 43 | *

44 | * This accessor method returns a reference to the live list, 45 | * not a snapshot. Therefore any modification you make to the 46 | * returned list will be present inside the JAXB object. 47 | * This is why there is not a set method for the users property. 48 | * 49 | *

50 | * For example, to add a new item, do as follows: 51 | *

52 |      *    getUsers().add(newItem);
53 |      * 
54 | * 55 | * 56 | *

57 | * Objects of the following type(s) are allowed in the list 58 | * {@link User } 59 | * 60 | * 61 | */ 62 | public List getUsers() { 63 | if (users == null) { 64 | users = new ArrayList(); 65 | } 66 | return this.users; 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /webservices/soap_client/src/main/java/com/stackify/services/package-info.java: -------------------------------------------------------------------------------- 1 | @javax.xml.bind.annotation.XmlSchema(namespace = "http://services.stackify.com/") 2 | package com.stackify.services; 3 | -------------------------------------------------------------------------------- /webservices/soap_example/src/main/java/com/stackify/ServicePublisher.java: -------------------------------------------------------------------------------- 1 | package com.stackify; 2 | 3 | import javax.xml.ws.Endpoint; 4 | 5 | import com.stackify.services.DefaultUserImpl; 6 | 7 | public class ServicePublisher { 8 | public static void main(String[] args) { 9 | Endpoint.publish("http://localhost:8080/users", new DefaultUserImpl()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /webservices/soap_example/src/main/java/com/stackify/models/User.java: -------------------------------------------------------------------------------- 1 | package com.stackify.models; 2 | 3 | public class User { 4 | private String email; 5 | private String name; 6 | 7 | public User() { 8 | } 9 | 10 | public User(String email, String name) { 11 | super(); 12 | this.email = email; 13 | this.name = name; 14 | } 15 | 16 | public String getEmail() { 17 | return email; 18 | } 19 | 20 | public void setEmail(String email) { 21 | this.email = email; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /webservices/soap_example/src/main/java/com/stackify/models/Users.java: -------------------------------------------------------------------------------- 1 | package com.stackify.models; 2 | 3 | import java.util.List; 4 | 5 | public class Users { 6 | List users; 7 | 8 | public List getUsers() { 9 | return users; 10 | } 11 | 12 | public void setUsers(List users) { 13 | this.users = users; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /webservices/soap_example/src/main/java/com/stackify/services/DefaultUserImpl.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import java.util.ArrayList; 4 | 5 | import javax.jws.WebService; 6 | 7 | import com.stackify.models.User; 8 | import com.stackify.models.Users; 9 | 10 | @WebService(endpointInterface = "com.stackify.services.UserService") 11 | public class DefaultUserImpl implements UserService { 12 | 13 | ArrayList usersList = new ArrayList<>(); 14 | 15 | @Override 16 | public void addUser(User user) { 17 | usersList.add(user); 18 | } 19 | 20 | @Override 21 | public Users getUsers() { 22 | Users users = new Users(); 23 | users.setUsers(usersList); 24 | return users; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /webservices/soap_example/src/main/java/com/stackify/services/UserService.java: -------------------------------------------------------------------------------- 1 | package com.stackify.services; 2 | 3 | import javax.jws.WebMethod; 4 | import javax.jws.WebService; 5 | import javax.jws.soap.SOAPBinding; 6 | 7 | import com.stackify.models.User; 8 | import com.stackify.models.Users; 9 | 10 | @WebService 11 | @SOAPBinding(style = SOAPBinding.Style.RPC) 12 | public interface UserService { 13 | 14 | @WebMethod 15 | public void addUser(User user); 16 | 17 | @WebMethod 18 | public Users getUsers(); 19 | } 20 | -------------------------------------------------------------------------------- /webservices/spring-rest-service/WebContent/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /webservices/spring-rest-service/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.stackify 5 | spring-rest-service 6 | 0.0.1-SNAPSHOT 7 | war 8 | 9 | 10 | org.springframework.boot 11 | spring-boot-starter-parent 12 | 1.5.4.RELEASE 13 | 14 | 15 | 16 | 17 | 18 | org.springframework.boot 19 | spring-boot-starter-web 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-hateoas 24 | 25 | 26 | io.springfox 27 | springfox-swagger2 28 | ${springfox-swagger2.version} 29 | 30 | 31 | io.springfox 32 | springfox-swagger-ui 33 | ${springfox-swagger-ui.version} 34 | 35 | 36 | 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-maven-plugin 42 | 43 | ${maven.compiler.source} 44 | ${maven.compiler.target} 45 | 46 | 47 | 48 | 49 | 50 | 51 | UTF-8 52 | UTF-8 53 | 1.5.4.RELEASE 54 | 2.7.0 55 | 2.7.0 56 | 1.8 57 | 1.8 58 | 59 | 60 | -------------------------------------------------------------------------------- /webservices/spring-rest-service/src/main/java/com/stackify/Application.java: -------------------------------------------------------------------------------- 1 | package com.stackify; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Application.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /webservices/spring-rest-service/src/main/java/com/stackify/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.stackify.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import springfox.documentation.builders.PathSelectors; 7 | import springfox.documentation.builders.RequestHandlerSelectors; 8 | import springfox.documentation.spi.DocumentationType; 9 | import springfox.documentation.spring.web.plugins.Docket; 10 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 11 | 12 | @Configuration 13 | @EnableSwagger2 14 | public class SwaggerConfig { 15 | @Bean 16 | public Docket api() { 17 | return new Docket(DocumentationType.SWAGGER_2).select() 18 | .apis(RequestHandlerSelectors.basePackage("com.stackify.controllers")) 19 | .paths(PathSelectors.any()) 20 | .build(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /webservices/spring-rest-service/src/main/java/com/stackify/controllers/UserController.java: -------------------------------------------------------------------------------- 1 | package com.stackify.controllers; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.springframework.hateoas.Link; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.MediaType; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.PostMapping; 12 | import org.springframework.web.bind.annotation.RequestBody; 13 | import org.springframework.web.bind.annotation.ResponseStatus; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | import com.stackify.models.User; 17 | import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; 18 | import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; 19 | 20 | @RestController 21 | public class UserController { 22 | 23 | private static List users = new ArrayList<>(); 24 | 25 | @PostMapping(value = "/users", consumes = MediaType.APPLICATION_JSON_VALUE) 26 | @ResponseStatus(HttpStatus.CREATED) 27 | public void addUser(@RequestBody User user) { 28 | users.add(user); 29 | } 30 | 31 | @GetMapping("/users") 32 | public List getUsers() { 33 | users.forEach(user -> { 34 | Link selfLink = linkTo(methodOn(UserController.class).getUsers()).slash(user.getEmail()) 35 | .withSelfRel(); 36 | user.getLinks().clear(); 37 | user.add(selfLink); 38 | }); 39 | return users; 40 | } 41 | 42 | @GetMapping("/users/{email}") 43 | public User getUser(@PathVariable String email) { 44 | User us = users.stream() 45 | .filter(user -> !user.getEmail() 46 | .equals(email)) 47 | .findAny() 48 | .orElse(null); 49 | return us; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /webservices/spring-rest-service/src/main/java/com/stackify/models/User.java: -------------------------------------------------------------------------------- 1 | package com.stackify.models; 2 | 3 | import org.springframework.hateoas.ResourceSupport; 4 | 5 | public class User extends ResourceSupport { 6 | private String email; 7 | private String name; 8 | 9 | public User() { 10 | } 11 | 12 | public User(String email, String name) { 13 | super(); 14 | this.email = email; 15 | this.name = name; 16 | } 17 | 18 | public String getEmail() { 19 | return email; 20 | } 21 | 22 | public void setEmail(String email) { 23 | this.email = email; 24 | } 25 | 26 | public String getName() { 27 | return name; 28 | } 29 | 30 | public void setName(String name) { 31 | this.name = name; 32 | } 33 | 34 | } 35 | --------------------------------------------------------------------------------