diff --git a/aws-app-sync/pom.xml b/aws-app-sync/pom.xml new file mode 100644 index 0000000000..1f915978ab --- /dev/null +++ b/aws-app-sync/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + + com.baeldung + aws-app-sync + 0.0.1-SNAPSHOT + aws-app-sync + + Spring Boot using AWS App Sync + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java new file mode 100644 index 0000000000..b310e60748 --- /dev/null +++ b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java @@ -0,0 +1,32 @@ +package com.baeldung.awsappsync; + +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; + +import java.nio.charset.StandardCharsets; +import java.util.Map; + +public class AppSyncClientHelper { + + static String apiUrl = "https://m4i3b6icrrb7livfbypfspiifi.appsync-api.us-east-2.amazonaws.com"; + static String apiKey = "da2-bm4rpatkkrc5jfyhvvq7itjeke"; + static String API_KEY_HEADER = "x-api-key"; + + public static WebClient.ResponseSpec getResponseBodySpec(Map requestBody) { + return WebClient + .builder() + .baseUrl(apiUrl) + .defaultHeader(API_KEY_HEADER, apiKey) + .defaultHeader("Content-Type", "application/json") + .build() + .method(HttpMethod.POST) + .uri("/graphql") + .body(BodyInserters.fromValue(requestBody)) + .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) + .acceptCharset(StandardCharsets.UTF_8) + .retrieve(); + } + +} diff --git a/aws-app-sync/src/main/java/com/baeldung/awsappsync/AwsAppSyncApplication.java b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AwsAppSyncApplication.java new file mode 100644 index 0000000000..19fffd2994 --- /dev/null +++ b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AwsAppSyncApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.awsappsync; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AwsAppSyncApplication { + + public static void main(String[] args) { + SpringApplication.run(AwsAppSyncApplication.class, args); + } + +} diff --git a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java new file mode 100644 index 0000000000..22d99959b3 --- /dev/null +++ b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java @@ -0,0 +1,72 @@ +package com.baeldung.awsappsync; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.web.reactive.function.client.WebClient; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +class AwsAppSyncApplicationTests { + + @Test + void givenGraphQuery_whenListEvents_thenReturnAllEvents() { + + Map requestBody = new HashMap<>(); + requestBody.put("query", "query ListEvents {" + + " listEvents {" + + " items {" + + " id" + + " name" + + " where" + + " when" + + " description" + + " }" + + " }" + + "}"); + requestBody.put("variables", ""); + requestBody.put("operationName", "ListEvents"); + + String bodyString = AppSyncClientHelper.getResponseBodySpec(requestBody) + .bodyToMono(String.class).block(); + + assertNotNull(bodyString); + assertTrue(bodyString.contains("My First Event")); + assertTrue(bodyString.contains("where")); + assertTrue(bodyString.contains("when")); + } + + @Test + void givenGraphAdd_whenMutation_thenReturnIdNameDesc() { + + String queryString = "mutation add {" + + " createEvent(" + + " name:\"My added GraphQL event\"" + + " where:\"Day 2\"" + + " when:\"Saturday night\"" + + " description:\"Studying GraphQL\"" + + " ){" + + " id" + + " name" + + " description" + + " }" + + "}"; + + Map requestBody = new HashMap<>(); + requestBody.put("query", queryString); + requestBody.put("variables", ""); + requestBody.put("operationName", "add"); + + WebClient.ResponseSpec response = AppSyncClientHelper.getResponseBodySpec(requestBody); + + String bodyString = response.bodyToMono(String.class).block(); + + assertNotNull(bodyString); + assertTrue(bodyString.contains("My added GraphQL event")); + assertFalse(bodyString.contains("where")); + assertFalse(bodyString.contains("when")); + } +} diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java index 56cc9f30d9..7ae2af0857 100644 --- a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java @@ -1,22 +1,22 @@ -package com.baeldung.java14.record; - -import java.util.Objects; - -public record Person (String name, String address) { - - public static String UNKNOWN_ADDRESS = "Unknown"; - public static String UNNAMED = "Unnamed"; - - public Person { - Objects.requireNonNull(name); - Objects.requireNonNull(address); - } - - public Person(String name) { - this(name, UNKNOWN_ADDRESS); - } - - public static Person unnamed(String address) { - return new Person(UNNAMED, address); - } -} +package com.baeldung.java14.record; + +import java.util.Objects; + +public record Person (String name, String address) { + + public static String UNKNOWN_ADDRESS = "Unknown"; + public static String UNNAMED = "Unnamed"; + + public Person { + Objects.requireNonNull(name); + Objects.requireNonNull(address); + } + + public Person(String name) { + this(name, UNKNOWN_ADDRESS); + } + + public static Person unnamed(String address) { + return new Person(UNNAMED, address); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java new file mode 100644 index 0000000000..b2264f30e6 --- /dev/null +++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java @@ -0,0 +1,84 @@ +package com.baeldung.java14.foreign.api; + +import jdk.incubator.foreign.*; +import org.junit.Test; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +import java.lang.invoke.VarHandle; +import java.nio.ByteOrder; + +public class ForeignMemoryUnitTest { + + @Test + public void whenAValueIsSet_thenAccessTheValue() { + long value = 10; + MemoryAddress memoryAddress = + MemorySegment.allocateNative(8).baseAddress(); + VarHandle varHandle = MemoryHandles.varHandle(long.class, + ByteOrder.nativeOrder()); + varHandle.set(memoryAddress, value); + assertThat(varHandle.get(memoryAddress), is(value)); + } + + @Test + public void whenMultipleValuesAreSet_thenAccessAll() { + VarHandle varHandle = MemoryHandles.varHandle(int.class, + ByteOrder.nativeOrder()); + + try(MemorySegment memorySegment = + MemorySegment.allocateNative(100)) { + MemoryAddress base = memorySegment.baseAddress(); + for(int i=0; i<25; i++) { + varHandle.set(base.addOffset((i*4)), i); + } + for(int i=0; i<25; i++) { + assertThat(varHandle.get(base.addOffset((i*4))), is(i)); + } + } + } + + @Test + public void whenSetValuesWithMemoryLayout_thenTheyCanBeRetrieved() { + SequenceLayout sequenceLayout = + MemoryLayout.ofSequence(25, + MemoryLayout.ofValueBits(64, ByteOrder.nativeOrder())); + VarHandle varHandle = + sequenceLayout.varHandle(long.class, + MemoryLayout.PathElement.sequenceElement()); + + try(MemorySegment memorySegment = + MemorySegment.allocateNative(sequenceLayout)) { + MemoryAddress base = memorySegment.baseAddress(); + for(long i=0; i convertListAfterJava8(List list) { - Map map = list.stream().collect(Collectors.toMap(Animal::getId, animal -> animal)); + Map map = list.stream().collect(Collectors.toMap(Animal::getId, Function.identity())); return map; } diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java index ad2ab2a756..15960c300d 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java @@ -53,14 +53,14 @@ public class CollectionToArrayListUnitTest { verifyShallowCopy(srcCollection, newList); } - + /** * Section 5. Deep Copy */ @Test public void whenUsingDeepCopy_thenVerifyDeepCopy() { ArrayList newList = srcCollection.stream() - .map(foo -> foo.deepCopy()) + .map(Foo::deepCopy) .collect(toCollection(ArrayList::new)); verifyDeepCopy(srcCollection, newList); @@ -83,13 +83,13 @@ public class CollectionToArrayListUnitTest { * @param a * @param b */ - private void verifyShallowCopy(Collection a, Collection b) { + private void verifyShallowCopy(Collection a, Collection b) { assertEquals("Collections have different lengths", a.size(), b.size()); Iterator iterA = a.iterator(); Iterator iterB = b.iterator(); while (iterA.hasNext()) { // use '==' to test instance identity - assertTrue("Foo instances differ!", iterA.next() == iterB.next()); + assertSame("Foo instances differ!", iterA.next(), iterB.next()); } } @@ -98,7 +98,7 @@ public class CollectionToArrayListUnitTest { * @param a * @param b */ - private void verifyDeepCopy(Collection a, Collection b) { + private void verifyDeepCopy(Collection a, Collection b) { assertEquals("Collections have different lengths", a.size(), b.size()); Iterator iterA = a.iterator(); Iterator iterB = b.iterator(); @@ -106,7 +106,7 @@ public class CollectionToArrayListUnitTest { Foo nextA = iterA.next(); Foo nextB = iterB.next(); // should not be same instance - assertFalse("Foo instances are the same!", nextA == nextB); + assertNotSame("Foo instances are the same!", nextA, nextB); // but should have same content assertFalse("Foo instances have different content!", fooDiff(nextA, nextB)); } diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java index 4d6cba7d27..7d94f88d21 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java @@ -23,7 +23,7 @@ public class ConvertIteratorToListServiceUnitTest { Iterator iterator; @Before - public void setUp() throws Exception { + public void setUp() { iterator = Arrays.asList(1, 2, 3) .iterator(); } @@ -31,7 +31,7 @@ public class ConvertIteratorToListServiceUnitTest { @Test public void givenAnIterator_whenConvertIteratorToListUsingWhileLoop_thenReturnAList() { - List actualList = new ArrayList(); + List actualList = new ArrayList<>(); // Convert Iterator to List using while loop dsf while (iterator.hasNext()) { @@ -44,7 +44,7 @@ public class ConvertIteratorToListServiceUnitTest { @Test public void givenAnIterator_whenConvertIteratorToListAfterJava8_thenReturnAList() { - List actualList = new ArrayList(); + List actualList = new ArrayList<>(); // Convert Iterator to List using Java 8 iterator.forEachRemaining(actualList::add); diff --git a/java-python-interop/README.md b/java-python-interop/README.md new file mode 100644 index 0000000000..dc9573ecde --- /dev/null +++ b/java-python-interop/README.md @@ -0,0 +1,5 @@ +## Java Python Interop + +This module contains articles about Java and Python interoperability. + +### Relevant Articles: diff --git a/java-python-interop/pom.xml b/java-python-interop/pom.xml new file mode 100644 index 0000000000..6ee5a0be3b --- /dev/null +++ b/java-python-interop/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + java-python-interop + 0.0.1-SNAPSHOT + java-python-interop + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.python + jython-slim + ${jython.version} + + + org.apache.commons + commons-exec + ${commons-exec.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + java-python-interop + + + src/main/resources + true + + + src/test/resources + true + + + + + + 2.7.2 + 1.3 + 3.6.1 + + + \ No newline at end of file diff --git a/java-python-interop/src/main/java/com/baeldung/python/interop/ScriptEngineManagerUtils.java b/java-python-interop/src/main/java/com/baeldung/python/interop/ScriptEngineManagerUtils.java new file mode 100644 index 0000000000..981f174c33 --- /dev/null +++ b/java-python-interop/src/main/java/com/baeldung/python/interop/ScriptEngineManagerUtils.java @@ -0,0 +1,34 @@ +package com.baeldung.python.interop; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.script.ScriptEngineFactory; +import javax.script.ScriptEngineManager; + +public class ScriptEngineManagerUtils { + + private static final Logger LOGGER = LoggerFactory.getLogger(ScriptEngineManagerUtils.class); + + private ScriptEngineManagerUtils() { + } + + public static void listEngines() { + ScriptEngineManager manager = new ScriptEngineManager(); + List engines = manager.getEngineFactories(); + + for (ScriptEngineFactory engine : engines) { + LOGGER.info("Engine name: {}", engine.getEngineName()); + LOGGER.info("Version: {}", engine.getEngineVersion()); + LOGGER.info("Language: {}", engine.getLanguageName()); + + LOGGER.info("Short Names:"); + for (String names : engine.getNames()) { + LOGGER.info(names); + } + } + } + +} diff --git a/java-python-interop/src/main/resources/logback.xml b/java-python-interop/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-python-interop/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-python-interop/src/test/java/com/baeldung/python/interop/JavaPythonInteropUnitTest.java b/java-python-interop/src/test/java/com/baeldung/python/interop/JavaPythonInteropUnitTest.java new file mode 100644 index 0000000000..5ec3a2b61f --- /dev/null +++ b/java-python-interop/src/test/java/com/baeldung/python/interop/JavaPythonInteropUnitTest.java @@ -0,0 +1,131 @@ +package com.baeldung.python.interop; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.util.List; +import java.util.stream.Collectors; + +import javax.script.ScriptContext; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.SimpleScriptContext; + +import org.apache.commons.exec.CommandLine; +import org.apache.commons.exec.DefaultExecutor; +import org.apache.commons.exec.ExecuteException; +import org.apache.commons.exec.PumpStreamHandler; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.python.core.PyException; +import org.python.core.PyObject; +import org.python.util.PythonInterpreter; + +public class JavaPythonInteropUnitTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void givenPythonScript_whenPythonProcessInvoked_thenSuccess() throws Exception { + ProcessBuilder processBuilder = new ProcessBuilder("python", resolvePythonScriptPath("hello.py")); + processBuilder.redirectErrorStream(true); + + Process process = processBuilder.start(); + List results = readProcessOutput(process.getInputStream()); + + assertThat("Results should not be empty", results, is(not(empty()))); + assertThat("Results should contain output of script: ", results, hasItem(containsString("Hello Baeldung Readers!!"))); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + } + + @Test + public void givenPythonScriptEngineIsAvailable_whenScriptInvoked_thenOutputDisplayed() throws Exception { + StringWriter output = new StringWriter(); + ScriptContext context = new SimpleScriptContext(); + context.setWriter(output); + + ScriptEngineManager manager = new ScriptEngineManager(); + ScriptEngine engine = manager.getEngineByName("python"); + engine.eval(new FileReader(resolvePythonScriptPath("hello.py")), context); + assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", output.toString() + .trim()); + } + + @Test + public void givenPythonInterpreter_whenPrintExecuted_thenOutputDisplayed() { + try (PythonInterpreter pyInterp = new PythonInterpreter()) { + StringWriter output = new StringWriter(); + pyInterp.setOut(output); + + pyInterp.exec("print('Hello Baeldung Readers!!')"); + assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", output.toString() + .trim()); + } + } + + @Test + public void givenPythonInterpreter_whenNumbersAdded_thenOutputDisplayed() { + try (PythonInterpreter pyInterp = new PythonInterpreter()) { + pyInterp.exec("x = 10+10"); + PyObject x = pyInterp.get("x"); + assertEquals("x: ", 20, x.asInt()); + } + } + + @Test + public void givenPythonInterpreter_whenErrorOccurs_thenExceptionIsThrown() { + thrown.expect(PyException.class); + thrown.expectMessage("ImportError: No module named syds"); + + try (PythonInterpreter pyInterp = new PythonInterpreter()) { + pyInterp.exec("import syds"); + } + } + + @Test + public void givenPythonScript_whenPythonProcessExecuted_thenSuccess() throws ExecuteException, IOException { + String line = "python " + resolvePythonScriptPath("hello.py"); + CommandLine cmdLine = CommandLine.parse(line); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); + + DefaultExecutor executor = new DefaultExecutor(); + executor.setStreamHandler(streamHandler); + + int exitCode = executor.execute(cmdLine); + assertEquals("No errors should be detected", 0, exitCode); + assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", outputStream.toString() + .trim()); + } + + private List readProcessOutput(InputStream inputStream) throws IOException { + try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) { + return output.lines() + .collect(Collectors.toList()); + } + } + + private String resolvePythonScriptPath(String filename) { + File file = new File("src/test/resources/" + filename); + return file.getAbsolutePath(); + } + +} diff --git a/java-python-interop/src/test/resources/hello.py b/java-python-interop/src/test/resources/hello.py new file mode 100644 index 0000000000..13275d9257 --- /dev/null +++ b/java-python-interop/src/test/resources/hello.py @@ -0,0 +1 @@ +print("Hello Baeldung Readers!!") \ No newline at end of file diff --git a/libraries-rpc/pom.xml b/libraries-rpc/pom.xml new file mode 100644 index 0000000000..8741a41062 --- /dev/null +++ b/libraries-rpc/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + libraries-rpc + libraries-rpc + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.twitter + finagle-core_2.13 + ${finagle.core.version} + + + com.twitter + finagle-http_2.13 + ${finagle.http.version} + + + + + + 20.4.0 + 20.4.0 + + + + diff --git a/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/GreetingService.java b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/GreetingService.java new file mode 100644 index 0000000000..7f3d741f94 --- /dev/null +++ b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/GreetingService.java @@ -0,0 +1,18 @@ +package com.baeldung.rpc.finagle; + +import com.twitter.finagle.Service; +import com.twitter.finagle.http.Request; +import com.twitter.finagle.http.Response; +import com.twitter.finagle.http.Status; +import com.twitter.io.Buf; +import com.twitter.io.Reader; +import com.twitter.util.Future; + +public class GreetingService extends Service { + @Override + public Future apply(Request request) { + String greeting = "Hello " + request.getParam("name"); + Reader reader = Reader.fromBuf(new Buf.ByteArray(greeting.getBytes(), 0, greeting.length())); + return Future.value(Response.apply(request.version(), Status.Ok(), reader)); + } +} diff --git a/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/LogFilter.java b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/LogFilter.java new file mode 100644 index 0000000000..7fc5440016 --- /dev/null +++ b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/LogFilter.java @@ -0,0 +1,22 @@ +package com.baeldung.rpc.finagle; + +import com.twitter.finagle.Service; +import com.twitter.finagle.SimpleFilter; +import com.twitter.finagle.http.Request; +import com.twitter.finagle.http.Response; +import com.twitter.util.Future; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LogFilter extends SimpleFilter { + + private static final Logger logger = LoggerFactory.getLogger(LogFilter.class); + + @Override + public Future apply(Request request, Service service) { + logger.info("Request host:" + request.host().getOrElse(() -> "")); + logger.info("Request params:"); + request.getParams().forEach(entry -> logger.info("\t" + entry.getKey() + " : " + entry.getValue())); + return service.apply(request); + } +} diff --git a/libraries-rpc/src/main/resources/logback.xml b/libraries-rpc/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/libraries-rpc/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/libraries-rpc/src/test/java/com/baeldung/rpc/finagle/FinagleIntegrationTest.java b/libraries-rpc/src/test/java/com/baeldung/rpc/finagle/FinagleIntegrationTest.java new file mode 100644 index 0000000000..8dcdb19e7e --- /dev/null +++ b/libraries-rpc/src/test/java/com/baeldung/rpc/finagle/FinagleIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.rpc.finagle; + +import com.twitter.finagle.Http; +import com.twitter.finagle.Service; +import com.twitter.finagle.http.Method; +import com.twitter.finagle.http.Request; +import com.twitter.finagle.http.Response; +import com.twitter.util.Await; +import com.twitter.util.Future; +import org.junit.Test; +import scala.runtime.BoxedUnit; + +import static org.junit.Assert.assertEquals; + +public class FinagleIntegrationTest { + @Test + public void givenServerAndClient_whenRequestSent_thenClientShouldReceiveResponseFromServer() throws Exception { + // given + Service serverService = new LogFilter().andThen(new GreetingService()); + Http.serve(":8080", serverService); + + Service clientService = new LogFilter().andThen(Http.newService(":8080")); + + // when + Request request = Request.apply(Method.Get(), "/?name=John"); + request.host("localhost"); + Future response = clientService.apply(request); + + // then + Await.result(response + .onSuccess(r -> { + assertEquals("Hello John", r.getContentString()); + return BoxedUnit.UNIT; + }) + .onFailure(r -> { + throw new RuntimeException(r); + }) + ); + } +} diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/DockerPatternConverter.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/DockerPatternConverter.java new file mode 100644 index 0000000000..c2e40cd565 --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/DockerPatternConverter.java @@ -0,0 +1,30 @@ +package com.baeldung.logging.log4j2.plugins; + +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.pattern.ConverterKeys; +import org.apache.logging.log4j.core.pattern.LogEventPatternConverter; +import org.apache.logging.log4j.core.pattern.PatternConverter; + +@Plugin(name = "DockerPatternConverter", category = PatternConverter.CATEGORY) +@ConverterKeys({"docker", "container"}) +public class DockerPatternConverter extends LogEventPatternConverter { + + private DockerPatternConverter(String[] options) { + super("Docker", "docker"); + } + + public static DockerPatternConverter newInstance(String[] options) { + return new DockerPatternConverter(options); + } + + @Override + public void format(LogEvent event, StringBuilder toAppendTo) { + toAppendTo.append(dockerContainer()); + } + + private String dockerContainer() { + //get docker container ID inside which application is running here + return "container-1"; + } +} diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaAppender.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaAppender.java new file mode 100644 index 0000000000..3e91aa5e94 --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaAppender.java @@ -0,0 +1,133 @@ +package com.baeldung.logging.log4j2.plugins; + +import org.apache.logging.log4j.core.Core; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required; + +import java.io.Serializable; + +@Plugin(name = "Kafka2", category = Core.CATEGORY_NAME) +public class KafkaAppender extends AbstractAppender { + + @PluginBuilderFactory + public static Builder newBuilder() { + return new Builder(); + } + + public static class Builder implements org.apache.logging.log4j.core.util.Builder { + + @PluginBuilderAttribute("name") + @Required + private String name; + + @PluginBuilderAttribute("ip") + private String ipAddress; + + @PluginBuilderAttribute("port") + private int port; + + @PluginBuilderAttribute("topic") + private String topic; + + @PluginBuilderAttribute("partition") + private String partition; + + @PluginElement("Layout") + private Layout layout; + + @PluginElement("Filter") + private Filter filter; + + public Layout getLayout() { + return layout; + } + + public Builder setLayout(Layout layout) { + this.layout = layout; + return this; + } + + public Filter getFilter() { + return filter; + } + + public String getName() { + return name; + } + + public Builder setName(String name) { + this.name = name; + return this; + } + + public Builder setFilter(Filter filter) { + this.filter = filter; + return this; + } + + public String getIpAddress() { + return ipAddress; + } + + public Builder setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + public int getPort() { + return port; + } + + public Builder setPort(int port) { + this.port = port; + return this; + } + + public String getTopic() { + return topic; + } + + public Builder setTopic(String topic) { + this.topic = topic; + return this; + } + + public String getPartition() { + return partition; + } + + public Builder setPartition(String partition) { + this.partition = partition; + return this; + } + + @Override + public KafkaAppender build() { + return new KafkaAppender(getName(), getFilter(), getLayout(), true, new KafkaBroker(ipAddress, port, topic, partition)); + } + } + + private KafkaBroker broker; + + private KafkaAppender(String name, Filter filter, Layout layout, boolean ignoreExceptions, KafkaBroker broker) { + super(name, filter, layout, ignoreExceptions); + this.broker = broker; + } + + @Override + public void append(LogEvent event) { + + connectAndSendToKafka(broker, event); + } + + private void connectAndSendToKafka(KafkaBroker broker, LogEvent event) { + //send to Kafka + } +} diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaBroker.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaBroker.java new file mode 100644 index 0000000000..0479e71c41 --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaBroker.java @@ -0,0 +1,38 @@ +package com.baeldung.logging.log4j2.plugins; + +import java.io.Serializable; + +public class KafkaBroker implements Serializable { + + private final String ipAddress; + private final int port; + + public KafkaBroker(String ipAddress, int port, String topic, String partition) { + this.ipAddress = ipAddress; + this.port = port; + this.topic = topic; + this.partition = partition; + } + + public String getTopic() { + return topic; + } + + public String getPartition() { + return partition; + } + + private final String topic; + private final String partition; + + + public String getIpAddress() { + return ipAddress; + } + + public int getPort() { + return port; + } + + +} diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaLookup.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaLookup.java new file mode 100644 index 0000000000..c2679861c4 --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaLookup.java @@ -0,0 +1,24 @@ +package com.baeldung.logging.log4j2.plugins; + +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.lookup.StrLookup; + +@Plugin(name = "kafka", category = StrLookup.CATEGORY) +public class KafkaLookup implements StrLookup { + + @Override + public String lookup(String key) { + return getFromKafka(key); + } + + @Override + public String lookup(LogEvent event, String key) { + return getFromKafka(key); + } + + private String getFromKafka(String topicName) { + //kafka search logic should go here + return "topic1-p1"; + } +} diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/ListAppender.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/ListAppender.java new file mode 100644 index 0000000000..e3819028db --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/ListAppender.java @@ -0,0 +1,48 @@ +/** + * + */ +package com.baeldung.logging.log4j2.plugins; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.Core; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static java.util.Collections.synchronizedList; + +@Plugin(name = "ListAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE) +public class ListAppender extends AbstractAppender { + + private List logList; + + protected ListAppender(String name, Filter filter) { + super(name, filter, null); + logList = synchronizedList(new ArrayList<>()); + } + + @PluginFactory + public static ListAppender createAppender(@PluginAttribute("name") String name, @PluginElement("Filter") final Filter filter) { + return new ListAppender(name, filter); + } + + @Override + public void append(LogEvent event) { + if (event.getLevel() + .isLessSpecificThan(Level.WARN)) { + error("Unable to log less than WARN level."); + return; + } + logList.add(event); + } + +} diff --git a/logging-modules/log4j2/src/test/resources/log4j2.xml b/logging-modules/log4j2/src/test/resources/log4j2.xml index ee26bcecf2..050e0aa705 100644 --- a/logging-modules/log4j2/src/test/resources/log4j2.xml +++ b/logging-modules/log4j2/src/test/resources/log4j2.xml @@ -50,6 +50,12 @@ + + + + + + + + + diff --git a/pdf/pom.xml b/pdf/pom.xml index d148aa1670..463c88948d 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -60,6 +60,16 @@ poi-ooxml ${poi-ooxml.version} + + org.thymeleaf + thymeleaf + 3.0.11.RELEASE + + + org.xhtmlrenderer + flying-saucer-pdf + 9.1.20 + diff --git a/pdf/src/main/java/com/baeldung/pdf/PDFThymeleafExample.java b/pdf/src/main/java/com/baeldung/pdf/PDFThymeleafExample.java new file mode 100644 index 0000000000..2e1df1d320 --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDFThymeleafExample.java @@ -0,0 +1,48 @@ +package com.baeldung.pdf; + +import com.lowagie.text.DocumentException; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.Context; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.xhtmlrenderer.pdf.ITextRenderer; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +public class PDFThymeleafExample { + + public static void main(String[] args) throws IOException, DocumentException { + PDFThymeleafExample thymeleaf2Pdf = new PDFThymeleafExample(); + String html = thymeleaf2Pdf.parseThymeleafTemplate(); + thymeleaf2Pdf.generatePdfFromHtml(html); + } + + public void generatePdfFromHtml(String html) throws IOException, DocumentException { + String outputFolder = System.getProperty("user.home") + File.separator + "thymeleaf.pdf"; + OutputStream outputStream = new FileOutputStream(outputFolder); + + ITextRenderer renderer = new ITextRenderer(); + renderer.setDocumentFromString(html); + renderer.layout(); + renderer.createPDF(outputStream); + + outputStream.close(); + } + + private String parseThymeleafTemplate() { + ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode(TemplateMode.HTML); + + TemplateEngine templateEngine = new TemplateEngine(); + templateEngine.setTemplateResolver(templateResolver); + + Context context = new Context(); + context.setVariable("to", "Baeldung.com"); + + return templateEngine.process("thymeleaf_template", context); + } +} diff --git a/pdf/src/main/resources/thymeleaf_template.html b/pdf/src/main/resources/thymeleaf_template.html new file mode 100644 index 0000000000..3e856367cc --- /dev/null +++ b/pdf/src/main/resources/thymeleaf_template.html @@ -0,0 +1,7 @@ + + +

+ +

+ + \ No newline at end of file diff --git a/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java b/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java new file mode 100644 index 0000000000..e253dce06c --- /dev/null +++ b/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.pdf; + +import com.lowagie.text.DocumentException; +import org.junit.Test; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.Context; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.xhtmlrenderer.pdf.ITextRenderer; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import static org.junit.Assert.assertTrue; + +public class PDFThymeleafUnitTest { + + @Test + public void givenThymeleafTemplate_whenParsedAndRenderedToPDF_thenItShouldNotBeEmpty() throws DocumentException, IOException { + String html = parseThymeleafTemplate(); + + ByteArrayOutputStream outputStream = generatePdfOutputStreamFromHtml(html); + + assertTrue(outputStream.size() > 0); + } + + private ByteArrayOutputStream generatePdfOutputStreamFromHtml(String html) throws IOException, DocumentException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + ITextRenderer renderer = new ITextRenderer(); + renderer.setDocumentFromString(html); + renderer.layout(); + renderer.createPDF(outputStream); + + outputStream.close(); + return outputStream; + } + + private String parseThymeleafTemplate() { + ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode(TemplateMode.HTML); + + TemplateEngine templateEngine = new TemplateEngine(); + templateEngine.setTemplateResolver(templateResolver); + + Context context = new Context(); + context.setVariable("to", "Baeldung.com"); + + return templateEngine.process("thymeleaf_template", context); + } +} diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java new file mode 100644 index 0000000000..44e4ecb539 --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java @@ -0,0 +1,168 @@ +package com.baeldung.bsontojson; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.HashSet; +import java.util.Set; + +import dev.morphia.annotations.Embedded; +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Field; +import dev.morphia.annotations.Id; +import dev.morphia.annotations.Index; +import dev.morphia.annotations.IndexOptions; +import dev.morphia.annotations.Indexes; +import dev.morphia.annotations.Property; +import dev.morphia.annotations.Reference; +import dev.morphia.annotations.Validation; + +@Entity("Books") +@Indexes({ @Index(fields = @Field("title"), options = @IndexOptions(name = "book_title")) }) +@Validation("{ price : { $gt : 0 } }") +public class Book { + @Id + private String isbn; + @Property + private String title; + private String author; + @Embedded + private Publisher publisher; + @Property("price") + private double cost; + @Reference + private Set companionBooks; + @Property + private LocalDateTime publishDate; + + public Book() { + + } + + public Book(String isbn, String title, String author, double cost, Publisher publisher) { + this.isbn = isbn; + this.title = title; + this.author = author; + this.cost = cost; + this.publisher = publisher; + this.companionBooks = new HashSet<>(); + } + + // Getters and setters ... + public String getIsbn() { + return isbn; + } + + public Book setIsbn(String isbn) { + this.isbn = isbn; + return this; + } + + public String getTitle() { + return title; + } + + public Book setTitle(String title) { + this.title = title; + return this; + } + + public String getAuthor() { + return author; + } + + public Book setAuthor(String author) { + this.author = author; + return this; + } + + public Publisher getPublisher() { + return publisher; + } + + public Book setPublisher(Publisher publisher) { + this.publisher = publisher; + return this; + } + + public double getCost() { + return cost; + } + + public Book setCost(double cost) { + this.cost = cost; + return this; + } + + public LocalDateTime getPublishDate() { + return publishDate; + } + + public Book setPublishDate(LocalDateTime publishDate) { + this.publishDate = publishDate; + return this; + } + + public Set getCompanionBooks() { + return companionBooks; + } + + public Book addCompanionBooks(Book book) { + if (companionBooks != null) + this.companionBooks.add(book); + return this; + } + + @Override + public String toString() { + return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((author == null) ? 0 : author.hashCode()); + long temp; + temp = Double.doubleToLongBits(cost); + result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + ((isbn == null) ? 0 : isbn.hashCode()); + result = prime * result + ((publisher == null) ? 0 : publisher.hashCode()); + result = prime * result + ((title == null) ? 0 : title.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Book other = (Book) obj; + if (author == null) { + if (other.author != null) + return false; + } else if (!author.equals(other.author)) + return false; + if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost)) + return false; + if (isbn == null) { + if (other.isbn != null) + return false; + } else if (!isbn.equals(other.isbn)) + return false; + if (publisher == null) { + if (other.publisher != null) + return false; + } else if (!publisher.equals(other.publisher)) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + +} diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Publisher.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Publisher.java new file mode 100644 index 0000000000..1ab262c82b --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Publisher.java @@ -0,0 +1,70 @@ +package com.baeldung.bsontojson; + +import org.bson.types.ObjectId; + +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Id; + +@Entity +public class Publisher { + + @Id + private ObjectId id; + private String name; + + public Publisher() { + + } + + public Publisher(ObjectId id, String name) { + this.id = id; + this.name = name; + } + + public ObjectId getId() { + return id; + } + + public void setId(ObjectId id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Catalog [id=" + id + ", name=" + name + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Publisher other = (Publisher) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java index 4e70394069..12053523f8 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java @@ -2,32 +2,18 @@ package com.baeldung.bsontojson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import java.sql.Timestamp; -import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.TimeZone; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import org.bson.Document; -import org.bson.json.Converter; import org.bson.json.JsonMode; import org.bson.json.JsonWriterSettings; -import org.bson.json.StrictJsonWriter; import org.bson.types.ObjectId; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.jupiter.api.AfterEach; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.baeldung.morphia.domain.Book; -import com.baeldung.morphia.domain.Publisher; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; @@ -42,7 +28,7 @@ public class BsonToJsonLiveTest { @BeforeClass public static void setUp() { Morphia morphia = new Morphia(); - morphia.mapPackage("com.baeldung.morphia"); + morphia.mapPackage("com.baeldung.bsontojson"); datastore = morphia.createDatastore(new MongoClient(), DB_NAME); datastore.ensureIndexes(); @@ -72,7 +58,7 @@ public class BsonToJsonLiveTest { } String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + "\"title\": \"title\", " + "\"author\": \"author\", " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + @@ -100,7 +86,7 @@ public class BsonToJsonLiveTest { } String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + "\"title\": \"title\", " + "\"author\": \"author\", " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + @@ -127,7 +113,7 @@ public class BsonToJsonLiveTest { } String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + "\"title\": \"title\", " + "\"author\": \"author\", " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + diff --git a/pom.xml b/pom.xml index c6addfa6aa..89ac3534b6 100644 --- a/pom.xml +++ b/pom.xml @@ -461,7 +461,8 @@ java-lite java-numbers java-numbers-2 - java-numbers-3 + java-numbers-3 + java-python-interop java-rmi java-spi java-vavr-stream @@ -508,6 +509,7 @@ libraries-http-2 libraries-io libraries-primitive + libraries-rpc libraries-security libraries-server libraries-testing @@ -896,6 +898,7 @@ atomix aws + aws-app-sync aws-lambda aws-reactive diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/configForDbProperties.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/configForDbProperties.xml new file mode 100644 index 0000000000..00fd5f0508 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/configForDbProperties.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml index 4468bb485f..bf4452da4a 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml @@ -7,7 +7,8 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd" > - + + diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties index 6524ce6109..eb5703ca72 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties @@ -1,4 +1,5 @@ -database.url=jdbc:postgresql:/localhost:5432/instance + +jdbc.url=jdbc:postgresql:/localhost:5432 database.username=foo database.password=bar -jdbc.url=jdbc:postgresql:/localhost:5432 \ No newline at end of file + diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java index 6827ee1cf1..2150d4b3ec 100644 --- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java @@ -6,7 +6,7 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import static org.assertj.core.api.Assertions.assertThat; -@SpringJUnitConfig(locations = "classpath:configForProperties.xml") +@SpringJUnitConfig(locations = {"classpath:configForProperties.xml", "classpath:configForDbProperties.xml"}) public class MultiplePropertiesXmlConfigIntegrationTest { @Value("${key.something}") private String something; diff --git a/spring-session/pom.xml b/spring-session/pom.xml index 42a414afdc..8388efb6c3 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-session/spring-session-redis/pom.xml b/spring-session/spring-session-redis/pom.xml index 37402634b0..8d225e06ed 100644 --- a/spring-session/spring-session-redis/pom.xml +++ b/spring-session/spring-session-redis/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -25,7 +25,7 @@ org.springframework.session - spring-session + spring-session-data-redis org.springframework.boot @@ -36,6 +36,11 @@ embedded-redis ${embedded-redis.version} + + redis.clients + jedis + jar + diff --git a/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java b/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java index 1da6d9422d..678c98e7eb 100644 --- a/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java +++ b/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java @@ -1,23 +1,31 @@ package com.baeldung.spring.session; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { - + @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("admin").password("password").roles("ADMIN"); + auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN"); } - + @Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic().and().authorizeRequests().antMatchers("/").hasRole("ADMIN").anyRequest().authenticated(); } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-session/spring-session-redis/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java b/spring-session/spring-session-redis/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java index 7ee0294315..065533c73f 100644 --- a/spring-session/spring-session-redis/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java +++ b/spring-session/spring-session-redis/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index 9fa839f1c2..628f439cc0 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -42,15 +42,16 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 org.springframework.social spring-social-facebook + ${spring.social.facebook.version} - + org.springframework.boot spring-boot-starter-data-jpa @@ -60,6 +61,12 @@ com.h2database h2 + + + net.bytebuddy + byte-buddy-dep + ${bytebuddy.version} + @@ -93,5 +100,10 @@
+ + + 1.10.9 + 2.0.3.RELEASE + \ No newline at end of file diff --git a/spring-social-login/src/main/java/com/baeldung/config/Application.java b/spring-social-login/src/main/java/com/baeldung/config/Application.java index 5d083d2d47..c65df6dbfe 100644 --- a/spring-social-login/src/main/java/com/baeldung/config/Application.java +++ b/spring-social-login/src/main/java/com/baeldung/config/Application.java @@ -3,7 +3,7 @@ package com.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication diff --git a/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java b/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java index 3d3081fef9..152c7b229a 100644 --- a/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java +++ b/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java @@ -1,8 +1,7 @@ package com.baeldung.config; -import com.baeldung.security.FacebookSignInAdapter; -import com.baeldung.security.FacebookConnectionSignup; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -14,22 +13,27 @@ import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.social.connect.ConnectionFactoryLocator; import org.springframework.social.connect.UsersConnectionRepository; import org.springframework.social.connect.mem.InMemoryUsersConnectionRepository; +import org.springframework.social.connect.support.ConnectionFactoryRegistry; import org.springframework.social.connect.web.ProviderSignInController; +import org.springframework.social.facebook.connect.FacebookConnectionFactory; + +import com.baeldung.security.FacebookConnectionSignup; +import com.baeldung.security.FacebookSignInAdapter; @Configuration @EnableWebSecurity @ComponentScan(basePackages = { "com.baeldung.security" }) public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Value("${spring.social.facebook.appSecret}") + String appSecret; + + @Value("${spring.social.facebook.appId}") + String appId; @Autowired private UserDetailsService userDetailsService; - @Autowired - private ConnectionFactoryLocator connectionFactoryLocator; - - @Autowired - private UsersConnectionRepository usersConnectionRepository; - @Autowired private FacebookConnectionSignup facebookConnectionSignup; @@ -55,7 +59,19 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean // @Primary public ProviderSignInController providerSignInController() { + ConnectionFactoryLocator connectionFactoryLocator = connectionFactoryLocator(); + UsersConnectionRepository usersConnectionRepository = getUsersConnectionRepository(connectionFactoryLocator); ((InMemoryUsersConnectionRepository) usersConnectionRepository).setConnectionSignUp(facebookConnectionSignup); return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new FacebookSignInAdapter()); } + + private ConnectionFactoryLocator connectionFactoryLocator() { + ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry(); + registry.addConnectionFactory(new FacebookConnectionFactory(appId, appSecret)); + return registry; + } + + private UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) { + return new InMemoryUsersConnectionRepository(connectionFactoryLocator); + } } \ No newline at end of file