diff --git a/apache-meecrowave/README.md b/apache-meecrowave/README.md new file mode 100644 index 0000000000..42b93a383e --- /dev/null +++ b/apache-meecrowave/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +================================ +- [Building a Microservice with Apache Meecrowave](http://www.baeldung.com/apache-meecrowave) diff --git a/core-java-8/README.md b/core-java-8/README.md index dcf7b24ef8..8e4e5f95b5 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -46,7 +46,6 @@ - [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations) - [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max) - [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization) -- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection) - [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) - [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) - [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) @@ -55,3 +54,5 @@ - [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic) - [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) - [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference) +- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) +- [Calculate Age in Java](http://www.baeldung.com/java-get-age) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index dee0634951..7e3b8cb280 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -99,6 +99,16 @@ joda-time ${joda.version} + + org.aspectj + aspectjrt + ${asspectj.version} + + + org.aspectj + aspectjweaver + ${asspectj.version} + @@ -170,6 +180,7 @@ 2.10 3.6.1 + 1.8.9 1.7.0 1.19 1.19 diff --git a/core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj b/core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj new file mode 100644 index 0000000000..b28bebfdaf --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj @@ -0,0 +1,9 @@ +package com.baeldung.aspect; + +public aspect ChangeCallsToCurrentTimeInMillisMethod { + long around(): + call(public static native long java.lang.System.currentTimeMillis()) + && within(user.code.base.pckg.*) { + return 0; + } +} diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java index 3ad3deb548..1689a5054d 100644 --- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.util; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.time.Clock; import java.time.Instant; @@ -9,6 +10,8 @@ import java.time.LocalTime; import java.time.ZoneId; import java.time.temporal.ChronoField; +import org.joda.time.DateTime; +import org.joda.time.DateTimeUtils; import org.junit.Test; public class CurrentDateTimeUnitTest { @@ -39,5 +42,4 @@ public class CurrentDateTimeUnitTest { assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond()); } - } diff --git a/core-java-collections/README.md b/core-java-collections/README.md index 510eac9dbc..7b3745b486 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -30,3 +30,4 @@ - [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list) - [How to Store Duplicate Keys in a Map in Java?](http://www.baeldung.com/java-map-duplicate-keys) - [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size) +- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards) diff --git a/core-java-8/src/main/java/com/baeldung/convertlisttomap/Animal.java b/core-java-collections/src/main/java/com/baeldung/convertlisttomap/Animal.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/convertlisttomap/Animal.java rename to core-java-collections/src/main/java/com/baeldung/convertlisttomap/Animal.java diff --git a/core-java-8/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java b/core-java-collections/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java rename to core-java-collections/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java index 88fc175f38..6527d35742 100644 --- a/core-java-8/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java +++ b/core-java-collections/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java @@ -1,13 +1,13 @@ package com.baeldung.convertlisttomap; +import com.google.common.collect.Maps; +import org.apache.commons.collections4.MapUtils; + import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import org.apache.commons.collections4.MapUtils; -import com.google.common.collect.Maps; - public class ConvertListToMapService { public Map convertListBeforeJava8(List list) { diff --git a/core-java-8/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java b/core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java index a4234d2af4..4d783f4525 100644 --- a/core-java-8/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListToMapServiceUnitTest.java @@ -1,13 +1,14 @@ package com.baeldung.convertlisttomap; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import org.junit.Before; +import org.junit.Test; + import java.util.ArrayList; import java.util.List; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; public class ConvertListToMapServiceUnitTest { List list; diff --git a/core-java-8/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java b/core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java index 6d3ad9e76e..6e766433d1 100644 --- a/core-java-8/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java @@ -1,15 +1,15 @@ package com.baeldung.convertlisttomap; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasSize; +import org.junit.Before; +import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; public class ConvertListWithDiplicatedIdToMapServiceUnitTest { List duplicatedIdList; diff --git a/core-java-io/README.md b/core-java-io/README.md index 011282af12..5e5ddf42b4 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -28,3 +28,5 @@ - [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels) - [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel) - [Download a File From an URL in Java](http://www.baeldung.com/java-download-file) +- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink) +- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter) diff --git a/core-java/README.md b/core-java/README.md index 185b3e4eb7..e22ee505ba 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -163,3 +163,8 @@ - [Console I/O in Java](http://www.baeldung.com/java-console-input-output) - [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays) - [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception) +- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar) +- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) +- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream) +- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object) +- [Exception Handling in Java](http://www.baeldung.com/java-exceptions) diff --git a/core-java/pom.xml b/core-java/pom.xml index 42e3219ac3..0b69685e14 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -173,6 +173,19 @@ c3p0 ${c3p0.version} + + + org.javassist + javassist + ${javaassist.version} + + + com.sun + tools + 1.8.0 + system + ${java.home}/../lib/tools.jar + @@ -400,6 +413,111 @@ + + + + buildAgentLoader + + + + org.apache.maven.plugins + maven-jar-plugin + + + package + + jar + + + agentLoader + target/classes + + + true + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + com/baeldung/instrumentation/application/AgentLoader.class + com/baeldung/instrumentation/application/Launcher.class + + + + + + + + + + buildApplication + + + + org.apache.maven.plugins + maven-jar-plugin + + + package + + jar + + + application + target/classes + + + true + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + com/baeldung/instrumentation/application/MyAtm.class + com/baeldung/instrumentation/application/MyAtmApplication.class + com/baeldung/instrumentation/application/Launcher.class + + + + + + + + + + buildAgent + + + + org.apache.maven.plugins + maven-jar-plugin + + + package + + jar + + + agent + target/classes + + + true + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + com/baeldung/instrumentation/agent/AtmTransformer.class + com/baeldung/instrumentation/agent/MyInstrumentationAgent.class + + + + + + + + @@ -453,6 +571,8 @@ 1.18 0.1.5 + + 3.21.0-GA diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java index 243ec88eb5..1934d0cfc2 100644 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java +++ b/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java @@ -33,7 +33,7 @@ public class BasicConnectionPool implements ConnectionPool { @Override public Connection getConnection() throws SQLException { - if (connectionPool.size() == 0) { + if (connectionPool.isEmpty()) { if (usedConnections.size() < MAX_POOL_SIZE) { connectionPool.add(createConnection(url, user, password)); } else { @@ -76,9 +76,7 @@ public class BasicConnectionPool implements ConnectionPool { } public void shutdown() throws SQLException { - for (Connection c : usedConnections) { - this.releaseConnection(c); - } + usedConnections.forEach(this::releaseConnection); for (Connection c : connectionPool) { c.close(); } diff --git a/core-java/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java b/core-java/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java new file mode 100644 index 0000000000..3c83912f54 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java @@ -0,0 +1,70 @@ +package com.baeldung.instrumentation.agent; + +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtMethod; +import javassist.NotFoundException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.IllegalClassFormatException; +import java.security.ProtectionDomain; + +public class AtmTransformer implements ClassFileTransformer { + + private static Logger LOGGER = LoggerFactory.getLogger(AtmTransformer.class); + + private static final String WITHDRAW_MONEY_METHOD = "withdrawMoney"; + + /** The internal form class name of the class to transform */ + private String targetClassName; + /** The class loader of the class we want to transform */ + private ClassLoader targetClassLoader; + + public AtmTransformer(String targetClassName, ClassLoader targetClassLoader) { + this.targetClassName = targetClassName; + this.targetClassLoader = targetClassLoader; + } + + @Override + public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, + ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { + byte[] byteCode = classfileBuffer; + + String finalTargetClassName = this.targetClassName.replaceAll("\\.", "/"); //replace . with / + if (!className.equals(finalTargetClassName)) { + return byteCode; + } + + if (className.equals(finalTargetClassName) && loader.equals(targetClassLoader)) { + LOGGER.info("[Agent] Transforming class MyAtm"); + try { + ClassPool cp = ClassPool.getDefault(); + CtClass cc = cp.get(targetClassName); + CtMethod m = cc.getDeclaredMethod(WITHDRAW_MONEY_METHOD); + m.addLocalVariable("startTime", CtClass.longType); + m.insertBefore("startTime = System.currentTimeMillis();"); + + StringBuilder endBlock = new StringBuilder(); + + m.addLocalVariable("endTime", CtClass.longType); + m.addLocalVariable("opTime", CtClass.longType); + endBlock.append("endTime = System.currentTimeMillis();"); + endBlock.append("opTime = (endTime-startTime)/1000;"); + + endBlock.append("LOGGER.info(\"[Application] Withdrawal operation completed in:\" + opTime + \" seconds!\");"); + + m.insertAfter(endBlock.toString()); + + byteCode = cc.toBytecode(); + cc.detach(); + } catch (NotFoundException | CannotCompileException | IOException e) { + LOGGER.error("Exception", e); + } + } + return byteCode; + } +} diff --git a/core-java/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java b/core-java/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java new file mode 100644 index 0000000000..685520276e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java @@ -0,0 +1,59 @@ +package com.baeldung.instrumentation.agent; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.instrument.Instrumentation; + +public class MyInstrumentationAgent { + private static Logger LOGGER = LoggerFactory.getLogger(MyInstrumentationAgent.class); + + public static void premain(String agentArgs, Instrumentation inst) { + LOGGER.info("[Agent] In premain method"); + + String className = "com.baeldung.instrumentation.application.MyAtm"; + transformClass(className,inst); + } + + public static void agentmain(String agentArgs, Instrumentation inst) { + LOGGER.info("[Agent] In agentmain method"); + + String className = "com.baeldung.instrumentation.application.MyAtm"; + transformClass(className,inst); + } + + private static void transformClass(String className, Instrumentation instrumentation) { + Class targetCls = null; + ClassLoader targetClassLoader = null; + // see if we can get the class using forName + try { + targetCls = Class.forName(className); + targetClassLoader = targetCls.getClassLoader(); + transform(targetCls, targetClassLoader, instrumentation); + return; + } catch (Exception ex) { + LOGGER.error("Class [{}] not found with Class.forName"); + } + // otherwise iterate all loaded classes and find what we want + for(Class clazz: instrumentation.getAllLoadedClasses()) { + if(clazz.getName().equals(className)) { + targetCls = clazz; + targetClassLoader = targetCls.getClassLoader(); + transform(targetCls, targetClassLoader, instrumentation); + return; + } + } + throw new RuntimeException("Failed to find class [" + className + "]"); + } + + private static void transform(Class clazz, ClassLoader classLoader, Instrumentation instrumentation) { + AtmTransformer dt = new AtmTransformer(clazz.getName(), classLoader); + instrumentation.addTransformer(dt, true); + try { + instrumentation.retransformClasses(clazz); + } catch (Exception ex) { + throw new RuntimeException("Transform failed for class: [" + clazz.getName() + "]", ex); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java b/core-java/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java new file mode 100644 index 0000000000..2c1cd759a5 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java @@ -0,0 +1,46 @@ +package com.baeldung.instrumentation.application; + +import com.sun.tools.attach.VirtualMachine; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.Optional; + +/** + * Created by adi on 6/10/18. + */ +public class AgentLoader { + private static Logger LOGGER = LoggerFactory.getLogger(AgentLoader.class); + + public static void run(String[] args) { + String agentFilePath = "/home/adi/Desktop/agent-1.0.0-jar-with-dependencies.jar"; + String applicationName = "MyAtmApplication"; + + //iterate all jvms and get the first one that matches our application name + Optional jvmProcessOpt = Optional.ofNullable(VirtualMachine.list() + .stream() + .filter(jvm -> { + LOGGER.info("jvm:{}", jvm.displayName()); + return jvm.displayName().contains(applicationName); + }) + .findFirst().get().id()); + + if(!jvmProcessOpt.isPresent()) { + LOGGER.error("Target Application not found"); + return; + } + File agentFile = new File(agentFilePath); + try { + String jvmPid = jvmProcessOpt.get(); + LOGGER.info("Attaching to target JVM with PID: " + jvmPid); + VirtualMachine jvm = VirtualMachine.attach(jvmPid); + jvm.loadAgent(agentFile.getAbsolutePath()); + jvm.detach(); + LOGGER.info("Attached to target JVM and loaded Java agent successfully"); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/instrumentation/application/Launcher.java b/core-java/src/main/java/com/baeldung/instrumentation/application/Launcher.java new file mode 100644 index 0000000000..87e494baab --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/application/Launcher.java @@ -0,0 +1,14 @@ +package com.baeldung.instrumentation.application; + +/** + * Created by adi on 6/14/18. + */ +public class Launcher { + public static void main(String[] args) throws Exception { + if(args[0].equals("StartMyAtmApplication")) { + new MyAtmApplication().run(args); + } else if(args[0].equals("LoadAgent")) { + new AgentLoader().run(args); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtm.java b/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtm.java new file mode 100644 index 0000000000..f826e82975 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtm.java @@ -0,0 +1,19 @@ +package com.baeldung.instrumentation.application; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by adi on 6/11/18. + */ +public class MyAtm { + private static Logger LOGGER = LoggerFactory.getLogger(MyAtm.class); + + private static final int account = 10; + + public static void withdrawMoney(int amount) throws InterruptedException { + Thread.sleep(2000l); //processing going on here + LOGGER.info("[Application] Successful Withdrawal of [{}] units!", amount); + + } +} diff --git a/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java b/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java new file mode 100644 index 0000000000..425511285e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.instrumentation.application; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MyAtmApplication { + + private static Logger LOGGER = LoggerFactory.getLogger(MyAtmApplication.class); + + public static void run(String[] args) throws Exception { + LOGGER.info("[Application] Starting ATM application"); + MyAtm.withdrawMoney(Integer.parseInt(args[2])); + + Thread.sleep(Long.valueOf(args[1])); + + MyAtm.withdrawMoney(Integer.parseInt(args[3])); + } + +} diff --git a/core-java/src/main/resources/META-INF/MANIFEST.MF b/core-java/src/main/resources/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..988de3193d --- /dev/null +++ b/core-java/src/main/resources/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Agent-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent +Can-Redefine-Classes: true +Can-Retransform-Classes: true +Premain-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent +Main-Class: com.baeldung.instrumentation.application.Launcher diff --git a/core-java/src/main/resources/log4j2.xml b/core-java/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..a824bef9b0 --- /dev/null +++ b/core-java/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 83f37dda85..51a99ea20c 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -34,3 +34,5 @@ - [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security) - [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor) - [Working with Enums in Kotlin](http://www.baeldung.com/kotlin-enum) +- [Create a Java and Kotlin Project with Maven](http://www.baeldung.com/kotlin-maven-java-project) +- [Reflection with Kotlin](http://www.baeldung.com/kotlin-reflection) diff --git a/google-web-toolkit/README.md b/google-web-toolkit/README.md new file mode 100644 index 0000000000..3526fe9962 --- /dev/null +++ b/google-web-toolkit/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to GWT](http://www.baeldung.com/gwt) diff --git a/libraries/README.md b/libraries/README.md index 09ad4ffcdf..3d06442bae 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -85,7 +85,7 @@ - [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) - [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date) - [Histograms with Apache Commons Frequency](http://www.baeldung.com/apache-commons-frequency) - +- [Guide to Resilience4j](http://www.baeldung.com/resilience4j) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/patterns/README.md b/patterns/README.md index 7d58260cf0..221cba6456 100644 --- a/patterns/README.md +++ b/patterns/README.md @@ -1,4 +1,4 @@ -###Relevant Articles: +### Relevant Articles: - [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) - [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) - [Implementing the Template Method Pattern in Java](http://www.baeldung.com/java-template-method-pattern) diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index 8b9d7a8193..5fb8f735ab 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -10,3 +10,4 @@ - [Composite Design Pattern in Java](http://www.baeldung.com/java-composite-pattern) - [Visitor Design Pattern in Java](http://www.baeldung.com/java-visitor-pattern) - [The DAO Pattern in Java](http://www.baeldung.com/java-dao-pattern) +- [Interpreter Design Pattern in Java](http://www.baeldung.com/java-interpreter-pattern) diff --git a/pom.xml b/pom.xml index 38812f09bf..06ec82e5f0 100644 --- a/pom.xml +++ b/pom.xml @@ -422,6 +422,7 @@ spring-boot-persistence spring-boot-security spring-boot-mvc + spring-boot-vue spring-boot-logging-log4j2 spring-cloud-data-flow spring-cloud @@ -433,6 +434,7 @@ spring-data-couchbase-2 persistence-modules/spring-data-dynamodb spring-data-elasticsearch + spring-data-jpa spring-data-keyvalue spring-data-mongodb persistence-modules/spring-data-neo4j @@ -1222,4 +1224,5 @@ 3.8 - \ No newline at end of file + + diff --git a/rxjava/README.md b/rxjava/README.md index 3376c49426..5c60e3bbce 100644 --- a/rxjava/README.md +++ b/rxjava/README.md @@ -15,3 +15,4 @@ - [RxJava Maybe](http://www.baeldung.com/rxjava-maybe) - [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) - [Filtering Observables in RxJava](http://www.baeldung.com/rxjava-filtering) +- [RxJava One Observable, Multiple Subscribers](http://www.baeldung.com/rxjava-multiple-subscribers-observable) diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 7925aa9d2b..8a67b4d86d 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -11,4 +11,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) - [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) - [Reactive WebSockets with Spring 5](http://www.baeldung.com/spring-5-reactive-websockets) -- [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) \ No newline at end of file +- [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) +- [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) diff --git a/spring-boot-compare-embedded/.mvn/wrapper/maven-wrapper.jar b/spring-boot-compare-embedded/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 9cc84ea9b4..0000000000 Binary files a/spring-boot-compare-embedded/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/spring-boot-compare-embedded/.mvn/wrapper/maven-wrapper.properties b/spring-boot-compare-embedded/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 9dda3b659b..0000000000 --- a/spring-boot-compare-embedded/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip diff --git a/spring-boot-compare-embedded/mvnw b/spring-boot-compare-embedded/mvnw deleted file mode 100644 index 5bf251c077..0000000000 --- a/spring-boot-compare-embedded/mvnw +++ /dev/null @@ -1,225 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -echo $MAVEN_PROJECTBASEDIR -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/spring-boot-compare-embedded/mvnw.cmd b/spring-boot-compare-embedded/mvnw.cmd deleted file mode 100644 index 019bd74d76..0000000000 --- a/spring-boot-compare-embedded/mvnw.cmd +++ /dev/null @@ -1,143 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/spring-boot-compare-embedded/pom.xml b/spring-boot-compare-embedded/pom.xml deleted file mode 100644 index af2c4ad5c6..0000000000 --- a/spring-boot-compare-embedded/pom.xml +++ /dev/null @@ -1,107 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-boot-compare-embedded - 0.0.1 - jar - spring-boot-compare-embedded - This is a simple application with used to compare embedded servlet containers. - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter - - - - - org.springframework.boot - spring-boot-starter-web - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - org.springframework.boot - spring-boot-starter-actuator - - - - org.openjdk.jmh - jmh-core - 1.21 - test - - - org.openjdk.jmh - jmh-generator-annprocess - 1.21 - test - - - com.jayway.jsonpath - json-path - test - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - UTF-8 - UTF-8 - - - diff --git a/spring-boot-compare-embedded/src/main/resources/META-INF/BenchmarkList b/spring-boot-compare-embedded/src/main/resources/META-INF/BenchmarkList deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-boot-compare-embedded/src/test/java/com/baeldung/embedded/ComparisonBenchmarkTest.java b/spring-boot-compare-embedded/src/test/java/com/baeldung/embedded/ComparisonBenchmarkTest.java deleted file mode 100644 index 23d51a5c94..0000000000 --- a/spring-boot-compare-embedded/src/test/java/com/baeldung/embedded/ComparisonBenchmarkTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.baeldung.embedded; - -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.assertj.core.util.Lists; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.runner.Runner; -import org.openjdk.jmh.runner.options.Options; -import org.openjdk.jmh.runner.options.OptionsBuilder; -import org.openjdk.jmh.runner.options.TimeValue; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; - -import com.jayway.jsonpath.JsonPath; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) -public class ComparisonBenchmarkTest { - - private static final String BASE_URL = "http://localhost:8080/actuator/metrics"; - - @Before - public void getAndPrintActuatorMetrics() { - RestTemplate restTemplate = new RestTemplate(); - for (MetricConfiguration c : getMetricConfigs()) { - getAndPrintActuatorMetric(restTemplate, c); - } - System.out.println(""); - } - - @Test - public void launchBenchmark() throws Exception { - Options opt = new OptionsBuilder() - .include(this.getClass().getName() + ".*") - .mode(Mode.Throughput) - .timeUnit(TimeUnit.SECONDS) - .warmupIterations(3) - .warmupTime(TimeValue.seconds(10)) - .measurementIterations(3) - .measurementTime(TimeValue.minutes(1)) - .threads(5) - .forks(1) - .shouldFailOnError(true) - .shouldDoGC(true) - .build(); - new Runner(opt).run(); - } - - @Benchmark - public void benchmark() throws Exception { - RestTemplate template = new RestTemplate(); - for (int i = 0; i < 10; i++) { - MetricNames metricNames = template.getForObject(BASE_URL, MetricNames.class); - metricNames.getNames().stream().forEach(n -> { - template.getForObject(BASE_URL + "/" + n, String.class); - }); - } - } - - static class MetricNames { - private String[] names; - - public List getNames() { - return Arrays.asList(this.names); - } - } - - static class MetricConfiguration { - - private String label; - private String metric; - private Class type; - private String jsonPath; - - public MetricConfiguration(String label, String metric, Class type, String path) { - this.label = label; - this.metric = metric; - this.type = type; - this.jsonPath = path; - } - - public String getLabel() { - return label; - } - - public Class getType() { - return type; - } - - public String getJsonPath() { - return jsonPath; - } - - public String getMetric() { - return metric; - } - } - - private List getMetricConfigs() { - return Lists.newArrayList( - new MetricConfiguration("jvm.memory.used", "jvm.memory.used", Integer.class, "$.measurements[0].value"), - new MetricConfiguration("jvm.classes.loaded", "jvm.classes.loaded", Integer.class, "$.measurements[0].value"), - new MetricConfiguration("jvm.threads.live", "jvm.threads.live", Integer.class, "$.measurements[0].value")); - } - - private void getAndPrintActuatorMetric(RestTemplate restTemplate, MetricConfiguration c) { - String response = restTemplate.getForObject(BASE_URL + "/" + c.getMetric(), String.class); - String value = (JsonPath.parse(response).read(c.getJsonPath(), c.getType())).toString(); - System.out.println("Startup Metric >>> " + c.getLabel() + "=" + value); - } -} diff --git a/spring-boot-compare-embedded/src/test/resources/logback-test.xml b/spring-boot-compare-embedded/src/test/resources/logback-test.xml deleted file mode 100644 index ca894df791..0000000000 --- a/spring-boot-compare-embedded/src/test/resources/logback-test.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md index e5e03e4d63..9760e73576 100644 --- a/spring-boot-ops/README.md +++ b/spring-boot-ops/README.md @@ -1,4 +1,11 @@ -### Relevant Articles: -================================ - -- [Spring Boot Console Application](http://www.baeldung.com/spring-boot-console-app) +### Relevant Articles: + - [Deploy a Spring Boot WAR into a Tomcat Server](http://www.baeldung.com/spring-boot-war-tomcat-deploy) + - [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) + - [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) + - [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) + - [Introduction to WebJars](http://www.baeldung.com/maven-webjars) + - [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) + - [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) + - [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) + - [Spring Boot Console Application](http://www.baeldung.com/spring-boot-console-app) + diff --git a/spring-boot-compare-embedded/src/main/java/com/baeldung/embedded/ComparisonApplication.java b/spring-boot-ops/src/main/java/com/baeldung/compare/ComparisonApplication.java similarity index 90% rename from spring-boot-compare-embedded/src/main/java/com/baeldung/embedded/ComparisonApplication.java rename to spring-boot-ops/src/main/java/com/baeldung/compare/ComparisonApplication.java index b7c5d81388..eb9d5ec4d0 100644 --- a/spring-boot-compare-embedded/src/main/java/com/baeldung/embedded/ComparisonApplication.java +++ b/spring-boot-ops/src/main/java/com/baeldung/compare/ComparisonApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.embedded; +package com.baeldung.compare; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-ops/src/main/java/com/baeldung/compare/StartupEventHandler.java b/spring-boot-ops/src/main/java/com/baeldung/compare/StartupEventHandler.java new file mode 100644 index 0000000000..e0756f704e --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/compare/StartupEventHandler.java @@ -0,0 +1,65 @@ +package com.baeldung.compare; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.BiFunction; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +import io.micrometer.core.instrument.Meter; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.Statistic; + +@Component +public class StartupEventHandler { + + // logger, constructor + private static Logger logger = LoggerFactory.getLogger(StartupEventHandler.class); + + public StartupEventHandler(MeterRegistry registry) { + this.meterRegistry = registry; + } + + private String[] METRICS = { + "jvm.memory.used", + "jvm.classes.loaded", + "jvm.threads.live"}; + + private String METRIC_MSG_FORMAT = "Startup Metric >> {}={}"; + + private MeterRegistry meterRegistry; + + @EventListener + public void getAndLogStartupMetrics( + ApplicationReadyEvent event) { + Arrays.asList(METRICS) + .forEach(this::getAndLogActuatorMetric); + } + + private void getAndLogActuatorMetric(String metric) { + Meter meter = meterRegistry.find(metric).meter(); + Map stats = getSamples(meter); + + logger.info(METRIC_MSG_FORMAT, metric, stats.get(Statistic.VALUE).longValue()); + } + + private Map getSamples(Meter meter) { + Map samples = new LinkedHashMap<>(); + mergeMeasurements(samples, meter); + return samples; + } + + private void mergeMeasurements(Map samples, Meter meter) { + meter.measure().forEach((measurement) -> samples.merge(measurement.getStatistic(), + measurement.getValue(), mergeFunction(measurement.getStatistic()))); + } + + private BiFunction mergeFunction(Statistic statistic) { + return Statistic.MAX.equals(statistic) ? Double::max : Double::sum; + } +} diff --git a/spring-boot-compare-embedded/src/main/resources/application.properties b/spring-boot-ops/src/main/resources/application.properties similarity index 100% rename from spring-boot-compare-embedded/src/main/resources/application.properties rename to spring-boot-ops/src/main/resources/application.properties diff --git a/spring-boot-compare-embedded/.gitignore b/spring-boot-vue/.gitignore similarity index 67% rename from spring-boot-compare-embedded/.gitignore rename to spring-boot-vue/.gitignore index 2af7cefb0a..82eca336e3 100644 --- a/spring-boot-compare-embedded/.gitignore +++ b/spring-boot-vue/.gitignore @@ -1,4 +1,4 @@ -target/ +/target/ !.mvn/wrapper/maven-wrapper.jar ### STS ### @@ -8,6 +8,7 @@ target/ .project .settings .springBeans +.sts4-cache ### IntelliJ IDEA ### .idea @@ -16,9 +17,9 @@ target/ *.ipr ### NetBeans ### -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -.nb-gradle/ \ No newline at end of file +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-vue/pom.xml b/spring-boot-vue/pom.xml new file mode 100644 index 0000000000..151fd293bb --- /dev/null +++ b/spring-boot-vue/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + com.baeldung + spring-boot-vue + 0.0.1-SNAPSHOT + jar + + spring-boot-vue + Demo project for Spring Boot Vue project + + + org.springframework.boot + spring-boot-starter-parent + 2.0.2.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java b/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java new file mode 100644 index 0000000000..c4213af0a3 --- /dev/null +++ b/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.springbootmvc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@SpringBootApplication +public class SpringBootMvcApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootMvcApplication.class, args); + } +} diff --git a/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/controllers/MainController.java b/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/controllers/MainController.java new file mode 100644 index 0000000000..37b74876cf --- /dev/null +++ b/spring-boot-vue/src/main/java/com/baeldung/springbootmvc/controllers/MainController.java @@ -0,0 +1,18 @@ +package com.baeldung.springbootmvc.controllers; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class MainController { + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String index(Model model) { + // this attribute will be available in the view index.html as a thymeleaf variable + model.addAttribute("eventName", "FIFA 2018"); + // this just means render index.html from static/ area + return "index"; + } +} diff --git a/spring-boot-compare-embedded/README.MD b/spring-boot-vue/src/main/resources/application.properties similarity index 100% rename from spring-boot-compare-embedded/README.MD rename to spring-boot-vue/src/main/resources/application.properties diff --git a/spring-boot-vue/src/main/resources/static/favicon.ico b/spring-boot-vue/src/main/resources/static/favicon.ico new file mode 100644 index 0000000000..64105ac11c Binary files /dev/null and b/spring-boot-vue/src/main/resources/static/favicon.ico differ diff --git a/spring-boot-vue/src/main/resources/templates/index.html b/spring-boot-vue/src/main/resources/templates/index.html new file mode 100644 index 0000000000..9fa374282a --- /dev/null +++ b/spring-boot-vue/src/main/resources/templates/index.html @@ -0,0 +1,98 @@ + + + + + + + + + + + + + +
+

This is an example Vue.js application developed with Spring Boot

+

This file is rendered by a Spring built-in default controller for index.html (/) using + Spring's built-in + Thymeleaf templating engine. + Although we don't need it per se, we customized the information passed to this + view from thymeleaf by adding a controller method for "/" route to demonstrate how to pass information from + Thymeleaf to this page. + The combination of template engine and frontend framework like Vue can make this a powerful approach to build + more complex applications while leveraging the benefits of a framework like Vue.js. + You can use thymeleaf features too but this project focuses mainly on using Vue.js on the + frontend as the framework and makes minimal use of Thymeleaf. + Also we don't use any routing and multiple components in this example, so what you see is technically a + Single Page Application (SPA) without any routes configured. +

+ +
+
+ Name of Event: + +
+
+ +
    +
  • + + +
  • +
+
+
+
+ + + + + + + + \ No newline at end of file diff --git a/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java b/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java new file mode 100644 index 0000000000..6364351eb3 --- /dev/null +++ b/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java @@ -0,0 +1,35 @@ +package com.baeldung.springbootmvc; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class SpringBootMvcApplicationTests { + + @Autowired + private MockMvc mockMvc; + + /** + * If this test passes, we got a page with the thymeleaf provided variable + * value for eventName + */ + @Test + public void shouldLoadCorrectIndexPage() throws Exception { + mockMvc.perform(get("/")).andExpect(status().isOk()). + andExpect(MockMvcResultMatchers.content() + .string(containsString("FIFA 2018"))); + } + +} diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 66e7c923c9..a572a16b67 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -34,3 +34,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Boot Exit Codes](http://www.baeldung.com/spring-boot-exit-codes) - [Guide to the Favicon in Spring Boot](http://www.baeldung.com/spring-boot-favicon) - [Spring Shutdown Callbacks](http://www.baeldung.com/spring-shutdown-callbacks) +- [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb) diff --git a/spring-data-jpa/pom.xml b/spring-data-jpa/pom.xml new file mode 100644 index 0000000000..517d43bd0e --- /dev/null +++ b/spring-data-jpa/pom.xml @@ -0,0 +1,26 @@ + + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + 4.0.0 + + spring-data-jpa + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + \ No newline at end of file diff --git a/spring-data-jpa/src/main/java/com/baeldung/Application.java b/spring-data-jpa/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..43888c2d67 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/Application.java @@ -0,0 +1,14 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +@SpringBootApplication +public class Application { + private static ApplicationContext applicationContext; + + public static void main(String[] args) { + applicationContext = SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java b/spring-data-jpa/src/main/java/com/baeldung/domain/Article.java similarity index 100% rename from spring-boot-persistence/src/main/java/com/baeldung/domain/Article.java rename to spring-data-jpa/src/main/java/com/baeldung/domain/Article.java diff --git a/spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java b/spring-data-jpa/src/main/java/com/baeldung/repository/ArticleRepository.java similarity index 100% rename from spring-boot-persistence/src/main/java/com/baeldung/repository/ArticleRepository.java rename to spring-data-jpa/src/main/java/com/baeldung/repository/ArticleRepository.java diff --git a/spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java b/spring-data-jpa/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java similarity index 97% rename from spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java rename to spring-data-jpa/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java index 7d531d1461..dd1fe66a0d 100644 --- a/spring-boot-persistence/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java +++ b/spring-data-jpa/src/test/java/com/baeldung/repository/ArticleRepositoryIntegrationTest.java @@ -1,6 +1,7 @@ package com.baeldung.repository; import com.baeldung.domain.Article; +import com.baeldung.repository.ArticleRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-data-jpa/src/test/resources/application.properties b/spring-data-jpa/src/test/resources/application.properties new file mode 100644 index 0000000000..de6ee2e6b5 --- /dev/null +++ b/spring-data-jpa/src/test/resources/application.properties @@ -0,0 +1,15 @@ +# spring.datasource.x +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +spring.datasource.username=sa +spring.datasource.password=sa + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=true +hibernate.cache.use_query_cache=true +hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory + +spring.datasource.data=import_articles.sql \ No newline at end of file diff --git a/spring-boot-persistence/src/test/resources/import_articles.sql b/spring-data-jpa/src/test/resources/import_articles.sql similarity index 100% rename from spring-boot-persistence/src/test/resources/import_articles.sql rename to spring-data-jpa/src/test/resources/import_articles.sql diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index b97b961e60..6b05ef569c 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -32,3 +32,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Scheduling Annotations](http://www.baeldung.com/spring-scheduling-annotations) - [Spring Web Annotations](http://www.baeldung.com/spring-mvc-annotations) - [Spring Core Annotations](http://www.baeldung.com/spring-core-annotations) +- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) +- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) diff --git a/spring-rest/README.md b/spring-rest/README.md index b717a5001d..6ef86ad015 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -24,3 +24,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Using the Spring RestTemplate Interceptor](http://www.baeldung.com/spring-rest-template-interceptor) - [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) - [Get and Post Lists of Objects with RestTemplate](http://www.baeldung.com/spring-rest-template-list) +- [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index d5162e78ba..aac6fe9843 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -37,6 +37,7 @@ com.baeldung spring-swagger-codegen 0.0.1-SNAPSHOT + ../../spring-swagger-codegen diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml index dca3832438..ece534dc74 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml @@ -5,11 +5,12 @@ com.baeldung spring-swagger-codegen-app 0.0.1-SNAPSHOT - + - org.springframework.boot - spring-boot-starter-parent - 1.5.10.RELEASE + com.baeldung + spring-swagger-codegen + 0.0.1-SNAPSHOT + ../../spring-swagger-codegen @@ -21,6 +22,7 @@ org.springframework.boot spring-boot-starter-web + ${spring.version} @@ -36,6 +38,7 @@ 1.8 0.0.1-SNAPSHOT + 1.5.10.RELEASE \ No newline at end of file diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md new file mode 100644 index 0000000000..a96ddccabb --- /dev/null +++ b/testing-modules/spring-testing/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: + diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml new file mode 100644 index 0000000000..a137bc8d33 --- /dev/null +++ b/testing-modules/spring-testing/pom.xml @@ -0,0 +1,75 @@ + + 4.0.0 + org.baeldung + spring-testing + 0.1-SNAPSHOT + spring-testing + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + + + org.hamcrest + java-hamcrest + ${hamcrest.version} + + + + org.springframework.boot + spring-boot-starter + LATEST + test + + + org.springframework.boot + spring-boot-starter-test + LATEST + test + + + org.springframework + spring-core + LATEST + + + org.springframework + spring-context + LATEST + + + org.eclipse.persistence + javax.persistence + 2.1.1 + + + org.springframework.data + spring-data-jpa + LATEST + + + + + spring-testing + + + src/main/resources + true + + + + + + + + 2.0.0.0 + + + \ No newline at end of file diff --git a/testing-modules/mockito/src/main/java/org/baeldung/mockito/repository/User.java b/testing-modules/spring-testing/src/main/java/org/baeldung/mockito/repository/User.java similarity index 100% rename from testing-modules/mockito/src/main/java/org/baeldung/mockito/repository/User.java rename to testing-modules/spring-testing/src/main/java/org/baeldung/mockito/repository/User.java diff --git a/testing-modules/mockito/src/main/java/org/baeldung/mockito/repository/UserRepository.java b/testing-modules/spring-testing/src/main/java/org/baeldung/mockito/repository/UserRepository.java similarity index 100% rename from testing-modules/mockito/src/main/java/org/baeldung/mockito/repository/UserRepository.java rename to testing-modules/spring-testing/src/main/java/org/baeldung/mockito/repository/UserRepository.java diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockAnnotationUnitTest.java b/testing-modules/spring-testing/src/test/java/org/baeldung/mockito/MockAnnotationUnitTest.java similarity index 100% rename from testing-modules/mockito/src/test/java/org/baeldung/mockito/MockAnnotationUnitTest.java rename to testing-modules/spring-testing/src/test/java/org/baeldung/mockito/MockAnnotationUnitTest.java diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockBeanAnnotationIntegrationTest.java b/testing-modules/spring-testing/src/test/java/org/baeldung/mockito/MockBeanAnnotationIntegrationTest.java similarity index 90% rename from testing-modules/mockito/src/test/java/org/baeldung/mockito/MockBeanAnnotationIntegrationTest.java rename to testing-modules/spring-testing/src/test/java/org/baeldung/mockito/MockBeanAnnotationIntegrationTest.java index fd9236fe13..3a7e58fb48 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockBeanAnnotationIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/org/baeldung/mockito/MockBeanAnnotationIntegrationTest.java @@ -20,7 +20,7 @@ public class MockBeanAnnotationIntegrationTest { ApplicationContext context; @Test - public void givenCountMethodMocked_WhenCountInvokedOnBeanFromContext_ThenMockValueReturned() { + public void givenCountMethodMocked_WhenCountInvoked_ThenMockValueReturned() { Mockito.when(mockRepository.count()).thenReturn(123L); UserRepository userRepoFromContext = context.getBean(UserRepository.class);