From 44bf48068feca3dda2500b80f61dffbab6be2d35 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 29 Jan 2017 16:01:58 +0200 Subject: [PATCH] formatting work --- .../com/baeldung/cxf/introduction/Server.java | 2 +- .../jaxrs/implementation/RestfulServer.java | 2 +- .../java9/language/PrivateInterface.java | 8 +- .../baeldung/java9/process/ProcessUtils.java | 23 ++- .../baeldung/java9/process/ServiceMain.java | 1 - .../java9/Java9OptionalsStreamTest.java | 17 +- .../java9/MultiResultionImageTest.java | 7 +- .../httpclient/SimpleHttpRequestsTest.java | 84 ++++----- .../java9/language/TryWithResourcesTest.java | 5 +- .../stream/CollectorImprovementTest.java | 47 ++--- .../language/stream/StreamFeaturesTest.java | 38 ++--- .../baeldung/java9/process/ProcessApi.java | 57 +++---- .../couchbase/async/CouchbaseEntity.java | 4 +- .../couchbase/async/person/Person.java | 27 +-- .../async/person/PersonCrudService.java | 4 +- .../async/person/PersonDocumentConverter.java | 5 +- .../async/person/RegistrationService.java | 9 +- .../async/service/AbstractBucketService.java | 6 +- .../async/service/AbstractCrudService.java | 67 ++------ .../async/service/ClusterService.java | 2 +- .../async/service/ClusterServiceImpl.java | 4 +- .../async/service/JsonDocumentConverter.java | 2 +- .../couchbase/intro/CodeSnippets.java | 39 ++--- .../couchbase/spring/person/Person.java | 27 +-- .../spring/person/PersonCrudService.java | 10 +- .../person/PersonDocumentConverter.java | 5 +- .../spring/person/RegistrationService.java | 9 +- .../spring/service/BucketService.java | 2 +- .../spring/service/ClusterService.java | 6 +- .../spring/service/ClusterServiceImpl.java | 23 ++- .../couchbase/spring/service/CrudService.java | 10 +- .../spring/service/JsonDocumentConverter.java | 2 +- .../spring/service/TutorialBucketService.java | 6 +- .../async/AsyncIntegrationTestConfig.java | 2 +- .../PersonCrudServiceIntegrationTest.java | 161 +++++++++--------- .../ClusterServiceIntegrationTest.java | 4 +- .../spring/IntegrationTestConfig.java | 2 +- .../PersonCrudServiceIntegrationTest.java | 15 +- .../ClusterServiceIntegrationTest.java | 4 +- .../java/baeldung/data/MemberRepository.java | 5 +- .../baeldung/service/MemberRegistration.java | 1 - .../baeldung/test/MemberRegistrationTest.java | 24 +-- .../discovery/DiscoveryApplication.java | 6 +- .../bootstrap/discovery/SecurityConfig.java | 41 ++--- 44 files changed, 341 insertions(+), 484 deletions(-) diff --git a/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java index 0e5af60b9d..2ac649f4c5 100644 --- a/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java +++ b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java @@ -8,7 +8,7 @@ public class Server { String address = "http://localhost:8080/baeldung"; Endpoint.publish(address, implementor); System.out.println("Server ready..."); - Thread.sleep(60 * 1000); + Thread.sleep(60 * 1000); System.out.println("Server exiting"); System.exit(0); } diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java index d3ed2eb70e..0605aef7b3 100644 --- a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java +++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java @@ -11,7 +11,7 @@ public class RestfulServer { factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository())); factoryBean.setAddress("http://localhost:8080/"); Server server = factoryBean.create(); - + System.out.println("Server ready..."); Thread.sleep(60 * 1000); System.out.println("Server exiting"); diff --git a/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java index fd6a496b18..f7b2fad891 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java +++ b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java @@ -1,16 +1,16 @@ package com.baeldung.java9.language; public interface PrivateInterface { - + private static String staticPrivate() { return "static private"; } - + private String instancePrivate() { return "instance private"; } - - public default void check(){ + + public default void check() { String result = staticPrivate(); if (!result.equals("static private")) throw new AssertionError("Incorrect result for static private interface method"); diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java index d6682bd0c8..5cd2567fb3 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java @@ -8,37 +8,36 @@ import java.time.Duration; import java.time.Instant; import java.util.stream.Stream; - public class ProcessUtils { - public static String getClassPath(){ + public static String getClassPath() { String cp = System.getProperty("java.class.path"); - System.out.println("ClassPath is "+cp); + System.out.println("ClassPath is " + cp); return cp; } - public static File getJavaCmd() throws IOException{ + public static File getJavaCmd() throws IOException { String javaHome = System.getProperty("java.home"); File javaCmd; - if(System.getProperty("os.name").startsWith("Win")){ + if (System.getProperty("os.name").startsWith("Win")) { javaCmd = new File(javaHome, "bin/java.exe"); - }else{ + } else { javaCmd = new File(javaHome, "bin/java"); } - if(javaCmd.canExecute()){ + if (javaCmd.canExecute()) { return javaCmd; - }else{ + } else { throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable"); } } - public static String getMainClass(){ + public static String getMainClass() { return System.getProperty("sun.java.command"); } - public static String getSystemProperties(){ - StringBuilder sb = new StringBuilder(); - System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) ); + public static String getSystemProperties() { + StringBuilder sb = new StringBuilder(); + System.getProperties().forEach((s1, s2) -> sb.append(s1 + " - " + s2)); return sb.toString(); } } diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java index 458f746496..299f74e877 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java @@ -8,7 +8,6 @@ public class ServiceMain { ProcessHandle thisProcess = ProcessHandle.current(); long pid = thisProcess.getPid(); - Optional opArgs = Optional.ofNullable(args); String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command")); diff --git a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java index b0684a94f8..121c17a860 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java @@ -19,10 +19,7 @@ public class Java9OptionalsStreamTest { public void filterOutPresentOptionalsWithFilter() { assertEquals(4, listOfOptionals.size()); - List filteredList = listOfOptionals.stream() - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toList()); + List filteredList = listOfOptionals.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()); assertEquals(2, filteredList.size()); assertEquals("foo", filteredList.get(0)); @@ -33,9 +30,7 @@ public class Java9OptionalsStreamTest { public void filterOutPresentOptionalsWithFlatMap() { assertEquals(4, listOfOptionals.size()); - List filteredList = listOfOptionals.stream() - .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) - .collect(Collectors.toList()); + List filteredList = listOfOptionals.stream().flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList()); assertEquals(2, filteredList.size()); assertEquals("foo", filteredList.get(0)); @@ -46,9 +41,7 @@ public class Java9OptionalsStreamTest { public void filterOutPresentOptionalsWithFlatMap2() { assertEquals(4, listOfOptionals.size()); - List filteredList = listOfOptionals.stream() - .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) - .collect(Collectors.toList()); + List filteredList = listOfOptionals.stream().flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList()); assertEquals(2, filteredList.size()); assertEquals("foo", filteredList.get(0)); @@ -59,9 +52,7 @@ public class Java9OptionalsStreamTest { public void filterOutPresentOptionalsWithJava9() { assertEquals(4, listOfOptionals.size()); - List filteredList = listOfOptionals.stream() - .flatMap(Optional::stream) - .collect(Collectors.toList()); + List filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList()); assertEquals(2, filteredList.size()); assertEquals("foo", filteredList.get(0)); diff --git a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java index a00646e4db..c0a5042b58 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java @@ -1,5 +1,5 @@ package com.baeldung.java9; - + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @@ -13,7 +13,6 @@ import org.junit.Test; public class MultiResultionImageTest { - @Test public void baseMultiResImageTest() { int baseIndex = 1; @@ -38,10 +37,8 @@ public class MultiResultionImageTest { return 8 * (i + 1); } - private static BufferedImage createImage(int i) { - return new BufferedImage(getSize(i), getSize(i), - BufferedImage.TYPE_INT_RGB); + return new BufferedImage(getSize(i), getSize(i), BufferedImage.TYPE_INT_RGB); } } diff --git a/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java index ab28b0a805..442a18cbf3 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java @@ -1,6 +1,4 @@ -package com.baeldung.java9.httpclient; - - +package com.baeldung.java9.httpclient; import static java.net.HttpURLConnection.HTTP_OK; import static org.junit.Assert.assertTrue; @@ -28,8 +26,8 @@ import org.junit.Test; public class SimpleHttpRequestsTest { - private URI httpURI; - + private URI httpURI; + @Before public void init() throws URISyntaxException { httpURI = new URI("http://www.baeldung.com/"); @@ -37,26 +35,26 @@ public class SimpleHttpRequestsTest { @Test public void quickGet() throws IOException, InterruptedException, URISyntaxException { - HttpRequest request = HttpRequest.create( httpURI ).GET(); + HttpRequest request = HttpRequest.create(httpURI).GET(); HttpResponse response = request.response(); int responseStatusCode = response.statusCode(); String responseBody = response.body(HttpResponse.asString()); - assertTrue("Get response status code is bigger then 400", responseStatusCode < 400); + assertTrue("Get response status code is bigger then 400", responseStatusCode < 400); } - + @Test - public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{ + public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException { HttpRequest request = HttpRequest.create(httpURI).GET(); long before = System.currentTimeMillis(); CompletableFuture futureResponse = request.responseAsync(); - futureResponse.thenAccept( response -> { + futureResponse.thenAccept(response -> { String responseBody = response.body(HttpResponse.asString()); - }); + }); HttpResponse resp = futureResponse.get(); HttpHeaders hs = resp.headers(); - assertTrue("There should be more then 1 header.", hs.map().size() >1); + assertTrue("There should be more then 1 header.", hs.map().size() > 1); } - + @Test public void postMehtod() throws URISyntaxException, IOException, InterruptedException { HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI); @@ -66,61 +64,63 @@ public class SimpleHttpRequestsTest { int statusCode = response.statusCode(); assertTrue("HTTP return code", statusCode == HTTP_OK); } - + @Test - public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException{ + public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException { CookieManager cManager = new CookieManager(); cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); - - SSLParameters sslParam = new SSLParameters (new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" }); - + + SSLParameters sslParam = new SSLParameters(new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" }); + HttpClient.Builder hcBuilder = HttpClient.create(); hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam); HttpClient httpClient = hcBuilder.build(); HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com")); - + HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET(); HttpResponse response = request.response(); int statusCode = response.statusCode(); assertTrue("HTTP return code", statusCode == HTTP_OK); } - - SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException{ + + SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException { SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters(); - String [] proto = sslP1.getApplicationProtocols(); - String [] cifers = sslP1.getCipherSuites(); + String[] proto = sslP1.getApplicationProtocols(); + String[] cifers = sslP1.getCipherSuites(); System.out.println(printStringArr(proto)); System.out.println(printStringArr(cifers)); return sslP1; } - - String printStringArr(String ... args ){ - if(args == null){ + + String printStringArr(String... args) { + if (args == null) { return null; } StringBuilder sb = new StringBuilder(); - for (String s : args){ + for (String s : args) { sb.append(s); sb.append("\n"); } return sb.toString(); } - - String printHeaders(HttpHeaders h){ - if(h == null){ + + String printHeaders(HttpHeaders h) { + if (h == null) { return null; } - - StringBuilder sb = new StringBuilder(); - Map> hMap = h.map(); - for(String k : hMap.keySet()){ - sb.append(k).append(":"); - List l = hMap.get(k); - if( l != null ){ - l.forEach( s -> { sb.append(s).append(","); } ); - } - sb.append("\n"); - } - return sb.toString(); + + StringBuilder sb = new StringBuilder(); + Map> hMap = h.map(); + for (String k : hMap.keySet()) { + sb.append(k).append(":"); + List l = hMap.get(k); + if (l != null) { + l.forEach(s -> { + sb.append(s).append(","); + }); + } + sb.append("\n"); + } + return sb.toString(); } } diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java index 687dfbc390..6bec3125cc 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java @@ -7,7 +7,7 @@ public class TryWithResourcesTest { static int closeCount = 0; - static class MyAutoCloseable implements AutoCloseable{ + static class MyAutoCloseable implements AutoCloseable { final FinalWrapper finalWrapper = new FinalWrapper(); public void close() { @@ -57,7 +57,6 @@ public class TryWithResourcesTest { assertEquals("Expected and Actual does not match", 5, closeCount); } - static class CloseableException extends Exception implements AutoCloseable { @Override public void close() { @@ -66,5 +65,3 @@ public class TryWithResourcesTest { } } - - diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementTest.java index 16d0c26722..ea76a76a5f 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementTest.java @@ -12,41 +12,30 @@ public class CollectorImprovementTest { @Test public void givenList_whenSatifyPredicate_thenMapValueWithOccurences() { List numbers = List.of(1, 2, 3, 5, 5); - - Map result = numbers.stream() - .filter(val -> val > 3).collect(Collectors.groupingBy( - Function.identity(), Collectors.counting())); - + + Map result = numbers.stream().filter(val -> val > 3).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + assertEquals(1, result.size()); - - result = numbers.stream().collect(Collectors.groupingBy( - Function.identity(), Collectors.filtering(val -> val > 3, - Collectors.counting()))); - + + result = numbers.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.filtering(val -> val > 3, Collectors.counting()))); + assertEquals(4, result.size()); } - + @Test public void givenListOfBlogs_whenAuthorName_thenMapAuthorWithComments() { Blog blog1 = new Blog("1", "Nice", "Very Nice"); Blog blog2 = new Blog("2", "Disappointing", "Ok", "Could be better"); List blogs = List.of(blog1, blog2); - - Map>> authorComments1 = - blogs.stream().collect(Collectors.groupingBy( - Blog::getAuthorName, Collectors.mapping( - Blog::getComments, Collectors.toList()))); - + + Map>> authorComments1 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.mapping(Blog::getComments, Collectors.toList()))); + assertEquals(2, authorComments1.size()); assertEquals(2, authorComments1.get("1").get(0).size()); assertEquals(3, authorComments1.get("2").get(0).size()); - - Map> authorComments2 = - blogs.stream().collect(Collectors.groupingBy( - Blog::getAuthorName, Collectors.flatMapping( - blog -> blog.getComments().stream(), - Collectors.toList()))); - + + Map> authorComments2 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.flatMapping(blog -> blog.getComments().stream(), Collectors.toList()))); + assertEquals(2, authorComments2.size()); assertEquals(2, authorComments2.get("1").size()); assertEquals(3, authorComments2.get("2").size()); @@ -54,18 +43,18 @@ public class CollectorImprovementTest { } class Blog { - private String authorName; - private List comments; - + private String authorName; + private List comments; + public Blog(String authorName, String... comments) { this.authorName = authorName; this.comments = List.of(comments); } - + public String getAuthorName() { return this.authorName; } - + public List getComments() { return this.comments; } diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java index a260e84164..72d17498a9 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java @@ -17,16 +17,11 @@ public class StreamFeaturesTest { public static class TakeAndDropWhileTest { public Stream getStreamAfterTakeWhileOperation() { - return Stream - .iterate("", s -> s + "s") - .takeWhile(s -> s.length() < 10); + return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10); } public Stream getStreamAfterDropWhileOperation() { - return Stream - .iterate("", s -> s + "s") - .takeWhile(s -> s.length() < 10) - .dropWhile(s -> !s.contains("sssss")); + return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10).dropWhile(s -> !s.contains("sssss")); } @Test @@ -72,25 +67,25 @@ public class StreamFeaturesTest { } - public static class OfNullableTest { + public static class OfNullableTest { private List collection = Arrays.asList("A", "B", "C"); - private Map map = new HashMap<>() {{ - put("A", 10); - put("C", 30); - }}; + private Map map = new HashMap<>() { + { + put("A", 10); + put("C", 30); + } + }; private Stream getStreamWithOfNullable() { - return collection.stream() - .flatMap(s -> Stream.ofNullable(map.get(s))); + return collection.stream().flatMap(s -> Stream.ofNullable(map.get(s))); } private Stream getStream() { - return collection.stream() - .flatMap(s -> { - Integer temp = map.get(s); - return temp != null ? Stream.of(temp) : Stream.empty(); - }); + return collection.stream().flatMap(s -> { + Integer temp = map.get(s); + return temp != null ? Stream.of(temp) : Stream.empty(); + }); } private List testOfNullableFrom(Stream stream) { @@ -107,10 +102,7 @@ public class StreamFeaturesTest { @Test public void testOfNullable() { - assertEquals( - testOfNullableFrom(getStream()), - testOfNullableFrom(getStreamWithOfNullable()) - ); + assertEquals(testOfNullableFrom(getStream()), testOfNullableFrom(getStreamWithOfNullable())); } diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java index 419516cb64..9c9951bc54 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java +++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java @@ -22,90 +22,89 @@ import static org.junit.Assert.assertTrue; public class ProcessApi { - @Before public void init() { } @Test - public void processInfoExample()throws NoSuchAlgorithmException{ + public void processInfoExample() throws NoSuchAlgorithmException { ProcessHandle self = ProcessHandle.current(); long PID = self.getPid(); ProcessHandle.Info procInfo = self.info(); Optional args = procInfo.arguments(); - Optional cmd = procInfo.commandLine(); + Optional cmd = procInfo.commandLine(); Optional startTime = procInfo.startInstant(); Optional cpuUsage = procInfo.totalCpuDuration(); waistCPU(); - System.out.println("Args "+ args); - System.out.println("Command " +cmd.orElse("EmptyCmd")); - System.out.println("Start time: "+ startTime.get().toString()); + System.out.println("Args " + args); + System.out.println("Command " + cmd.orElse("EmptyCmd")); + System.out.println("Start time: " + startTime.get().toString()); System.out.println(cpuUsage.get().toMillis()); - + Stream allProc = ProcessHandle.current().children(); allProc.forEach(p -> { - System.out.println("Proc "+ p.getPid()); + System.out.println("Proc " + p.getPid()); }); } @Test - public void createAndDestroyProcess() throws IOException, InterruptedException{ + public void createAndDestroyProcess() throws IOException, InterruptedException { int numberOfChildProcesses = 5; - for(int i=0; i < numberOfChildProcesses; i++){ + for (int i = 0; i < numberOfChildProcesses; i++) { createNewJVM(ServiceMain.class, i).getPid(); } - - Stream childProc = ProcessHandle.current().children(); - assertEquals( childProc.count(), numberOfChildProcesses); - + + Stream childProc = ProcessHandle.current().children(); + assertEquals(childProc.count(), numberOfChildProcesses); + childProc = ProcessHandle.current().children(); childProc.forEach(processHandle -> { - assertTrue("Process "+ processHandle.getPid() +" should be alive!", processHandle.isAlive()); + assertTrue("Process " + processHandle.getPid() + " should be alive!", processHandle.isAlive()); CompletableFuture onProcExit = processHandle.onExit(); onProcExit.thenAccept(procHandle -> { - System.out.println("Process with PID "+ procHandle.getPid() + " has stopped"); + System.out.println("Process with PID " + procHandle.getPid() + " has stopped"); }); }); - + Thread.sleep(10000); - + childProc = ProcessHandle.current().children(); childProc.forEach(procHandle -> { - assertTrue("Could not kill process "+procHandle.getPid(), procHandle.destroy()); + assertTrue("Could not kill process " + procHandle.getPid(), procHandle.destroy()); }); - + Thread.sleep(5000); - + childProc = ProcessHandle.current().children(); childProc.forEach(procHandle -> { - assertFalse("Process "+ procHandle.getPid() +" should not be alive!", procHandle.isAlive()); + assertFalse("Process " + procHandle.getPid() + " should not be alive!", procHandle.isAlive()); }); - + } - private Process createNewJVM(Class mainClass, int number) throws IOException{ + private Process createNewJVM(Class mainClass, int number) throws IOException { ArrayList cmdParams = new ArrayList(5); cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath()); cmdParams.add("-cp"); cmdParams.add(ProcessUtils.getClassPath()); cmdParams.add(mainClass.getName()); - cmdParams.add("Service "+ number); + cmdParams.add("Service " + number); ProcessBuilder myService = new ProcessBuilder(cmdParams); myService.inheritIO(); return myService.start(); } - - private void waistCPU() throws NoSuchAlgorithmException{ + + private void waistCPU() throws NoSuchAlgorithmException { ArrayList randArr = new ArrayList(4096); SecureRandom sr = SecureRandom.getInstanceStrong(); Duration somecpu = Duration.ofMillis(4200L); Instant end = Instant.now().plus(somecpu); while (Instant.now().isBefore(end)) { - //System.out.println(sr.nextInt()); - randArr.add( sr.nextInt() ); + // System.out.println(sr.nextInt()); + randArr.add(sr.nextInt()); } } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java index 16e1876719..8f459e364f 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java @@ -3,7 +3,7 @@ package com.baeldung.couchbase.async; public interface CouchbaseEntity { String getId(); - + void setId(String id); - + } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java index 32ed2ebbe4..f1135a32a2 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java @@ -8,26 +8,27 @@ public class Person implements CouchbaseEntity { private String type; private String name; private String homeTown; - - Person() {} - + + Person() { + } + public Person(Builder b) { this.id = b.id; this.type = b.type; this.name = b.name; this.homeTown = b.homeTown; } - + @Override public String getId() { return id; } - + @Override public void setId(String id) { this.id = id; } - + public String getType() { return type; } @@ -39,19 +40,19 @@ public class Person implements CouchbaseEntity { public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + public String getHomeTown() { return homeTown; } - + public void setHomeTown(String homeTown) { this.homeTown = homeTown; } - + public static class Builder { private String id; private String type; @@ -61,16 +62,16 @@ public class Person implements CouchbaseEntity { public static Builder newInstance() { return new Builder(); } - + public Person build() { return new Person(this); } - + public Builder id(String id) { this.id = id; return this; } - + public Builder type(String type) { this.type = type; return this; diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java index b2ef985725..407bc7ee1c 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java @@ -13,9 +13,7 @@ import com.baeldung.couchbase.async.service.BucketService; public class PersonCrudService extends AbstractCrudService { @Autowired - public PersonCrudService( - @Qualifier("TutorialBucketService") BucketService bucketService, - PersonDocumentConverter converter) { + public PersonCrudService(@Qualifier("TutorialBucketService") BucketService bucketService, PersonDocumentConverter converter) { super(bucketService, converter); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java index 8646cf247a..0f08679ace 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java @@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter { @Override public JsonDocument toDocument(Person p) { - JsonObject content = JsonObject.empty() - .put("type", "Person") - .put("name", p.getName()) - .put("homeTown", p.getHomeTown()); + JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown()); return JsonDocument.create(p.getId(), content); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java index 926cd7f4e8..7cbc3625db 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java @@ -10,19 +10,18 @@ public class RegistrationService { @Autowired private PersonCrudService crud; - + public void registerNewPerson(String name, String homeTown) { Person person = new Person(); person.setName(name); person.setHomeTown(homeTown); crud.create(person); } - + public Person findRegistrant(String id) { - try{ + try { return crud.read(id); - } - catch(CouchbaseException e) { + } catch (CouchbaseException e) { return crud.readFromReplica(id); } } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java index cbc03cbcda..1180ea00a6 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java @@ -11,9 +11,9 @@ public abstract class AbstractBucketService implements BucketService { protected void openBucket() { bucket = clusterService.openBucket(getBucketName(), getBucketPassword()); } - + protected abstract String getBucketName(); - + protected abstract String getBucketPassword(); public AbstractBucketService(ClusterService clusterService) { @@ -24,4 +24,4 @@ public abstract class AbstractBucketService implements BucketService { public Bucket getBucket() { return bucket; } - } +} diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java index 861e2404e5..089cc55d5d 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java @@ -40,7 +40,7 @@ public abstract class AbstractCrudService implements @Override public void create(T t) { - if(t.getId() == null) { + if (t.getId() == null) { t.setId(UUID.randomUUID().toString()); } JsonDocument doc = converter.toDocument(t); @@ -73,18 +73,15 @@ public abstract class AbstractCrudService implements @Override public List readBulk(Iterable ids) { final AsyncBucket asyncBucket = bucket.async(); - Observable asyncOperation = Observable - .from(ids) - .flatMap(new Func1>() { - public Observable call(String key) { - return asyncBucket.get(key); - } - }); + Observable asyncOperation = Observable.from(ids).flatMap(new Func1>() { + public Observable call(String key) { + return asyncBucket.get(key); + } + }); final List items = new ArrayList(); try { - asyncOperation.toBlocking() - .forEach(new Action1() { + asyncOperation.toBlocking().forEach(new Action1() { public void call(JsonDocument doc) { T item = converter.fromDocument(doc); items.add(item); @@ -100,72 +97,42 @@ public abstract class AbstractCrudService implements @Override public void createBulk(Iterable items) { final AsyncBucket asyncBucket = bucket.async(); - Observable - .from(items) - .flatMap(new Func1>() { + Observable.from(items).flatMap(new Func1>() { @SuppressWarnings("unchecked") @Override public Observable call(final T t) { - if(t.getId() == null) { + if (t.getId() == null) { t.setId(UUID.randomUUID().toString()); } JsonDocument doc = converter.toDocument(t); - return asyncBucket.insert(doc) - .retryWhen(RetryBuilder - .anyOf(BackpressureException.class) - .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) - .max(10) - .build()); + return asyncBucket.insert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build()); } - }) - .last() - .toBlocking() - .single(); + }).last().toBlocking().single(); } @Override public void updateBulk(Iterable items) { final AsyncBucket asyncBucket = bucket.async(); - Observable - .from(items) - .flatMap(new Func1>() { + Observable.from(items).flatMap(new Func1>() { @SuppressWarnings("unchecked") @Override public Observable call(final T t) { JsonDocument doc = converter.toDocument(t); - return asyncBucket.upsert(doc) - .retryWhen(RetryBuilder - .anyOf(BackpressureException.class) - .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) - .max(10) - .build()); + return asyncBucket.upsert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build()); } - }) - .last() - .toBlocking() - .single(); + }).last().toBlocking().single(); } @Override public void deleteBulk(Iterable ids) { final AsyncBucket asyncBucket = bucket.async(); - Observable - .from(ids) - .flatMap(new Func1>() { + Observable.from(ids).flatMap(new Func1>() { @SuppressWarnings("unchecked") @Override public Observable call(String key) { - return asyncBucket.remove(key) - .retryWhen(RetryBuilder - .anyOf(BackpressureException.class) - .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) - .max(10) - .build()); + return asyncBucket.remove(key).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build()); } - }) - .last() - .toBlocking() - .single(); + }).last().toBlocking().single(); } @Override diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java index ee67405b12..7bf891244f 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java @@ -3,6 +3,6 @@ package com.baeldung.couchbase.async.service; import com.couchbase.client.java.Bucket; public interface ClusterService { - + Bucket openBucket(String name, String password); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java index 7ce75d21f5..e708922988 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java @@ -18,7 +18,7 @@ public class ClusterServiceImpl implements ClusterService { private Cluster cluster; private Map buckets = new ConcurrentHashMap<>(); - + @PostConstruct private void init() { CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create(); @@ -27,7 +27,7 @@ public class ClusterServiceImpl implements ClusterService { @Override synchronized public Bucket openBucket(String name, String password) { - if(!buckets.containsKey(name)) { + if (!buckets.containsKey(name)) { Bucket bucket = cluster.openBucket(name, password); buckets.put(name, bucket); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java index 85e14a87ce..193e91016a 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java @@ -5,6 +5,6 @@ import com.couchbase.client.java.document.JsonDocument; public interface JsonDocumentConverter { JsonDocument toDocument(T t); - + T fromDocument(JsonDocument doc); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java index 2cb9e1f4f7..e7bddc6442 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java @@ -14,40 +14,32 @@ import com.couchbase.client.java.env.CouchbaseEnvironment; import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; public class CodeSnippets { - + static Cluster loadClusterWithDefaultEnvironment() { return CouchbaseCluster.create("localhost"); } static Cluster loadClusterWithCustomEnvironment() { - CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder() - .connectTimeout(10000) - .kvTimeout(3000) - .build(); + CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().connectTimeout(10000).kvTimeout(3000).build(); return CouchbaseCluster.create(env, "localhost"); } - + static Bucket loadDefaultBucketWithBlankPassword(Cluster cluster) { return cluster.openBucket(); } - + static Bucket loadBaeldungBucket(Cluster cluster) { return cluster.openBucket("baeldung", ""); } static JsonDocument insertExample(Bucket bucket) { - JsonObject content = JsonObject.empty() - .put("name", "John Doe") - .put("type", "Person") - .put("email", "john.doe@mydomain.com") - .put("homeTown", "Chicago") - ; + JsonObject content = JsonObject.empty().put("name", "John Doe").put("type", "Person").put("email", "john.doe@mydomain.com").put("homeTown", "Chicago"); String id = UUID.randomUUID().toString(); JsonDocument document = JsonDocument.create(id, content); JsonDocument inserted = bucket.insert(document); return inserted; } - + static JsonDocument retrieveAndUpsertExample(Bucket bucket, String id) { JsonDocument document = bucket.get(id); JsonObject content = document.content(); @@ -55,7 +47,7 @@ public class CodeSnippets { JsonDocument upserted = bucket.upsert(document); return upserted; } - + static JsonDocument replaceExample(Bucket bucket, String id) { JsonDocument document = bucket.get(id); JsonObject content = document.content(); @@ -63,30 +55,29 @@ public class CodeSnippets { JsonDocument replaced = bucket.replace(document); return replaced; } - + static JsonDocument removeExample(Bucket bucket, String id) { JsonDocument removed = bucket.remove(id); return removed; } - + static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) { - try{ + try { return bucket.get(id); - } - catch(CouchbaseException e) { + } catch (CouchbaseException e) { List list = bucket.getFromReplica(id, ReplicaMode.FIRST); - if(!list.isEmpty()) { + if (!list.isEmpty()) { return list.get(0); } } return null; } - + static JsonDocument getLatestReplicaVersion(Bucket bucket, String id) { long maxCasValue = -1; JsonDocument latest = null; - for(JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) { - if(replica.cas() > maxCasValue) { + for (JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) { + if (replica.cas() > maxCasValue) { latest = replica; maxCasValue = replica.cas(); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java index 0348ba1e5f..403b7c8d3b 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java @@ -6,24 +6,25 @@ public class Person { private String type; private String name; private String homeTown; - - Person() {} - + + Person() { + } + public Person(Builder b) { this.id = b.id; this.type = b.type; this.name = b.name; this.homeTown = b.homeTown; } - + public String getId() { return id; } - + public void setId(String id) { this.id = id; } - + public String getType() { return type; } @@ -35,19 +36,19 @@ public class Person { public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + public String getHomeTown() { return homeTown; } - + public void setHomeTown(String homeTown) { this.homeTown = homeTown; } - + public static class Builder { private String id; private String type; @@ -57,16 +58,16 @@ public class Person { public static Builder newInstance() { return new Builder(); } - + public Person build() { return new Person(this); } - + public Builder id(String id) { this.id = id; return this; } - + public Builder type(String type) { this.type = type; return this; diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java index de035f1d2c..163f6417ca 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java @@ -16,15 +16,15 @@ import com.couchbase.client.java.document.JsonDocument; @Service public class PersonCrudService implements CrudService { - + @Autowired private TutorialBucketService bucketService; - + @Autowired private PersonDocumentConverter converter; - + private Bucket bucket; - + @PostConstruct private void init() { bucket = bucketService.getBucket(); @@ -32,7 +32,7 @@ public class PersonCrudService implements CrudService { @Override public void create(Person person) { - if(person.getId() == null) { + if (person.getId() == null) { person.setId(UUID.randomUUID().toString()); } JsonDocument document = converter.toDocument(person); diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java index 030c9fde27..71108d16dd 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java @@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter { @Override public JsonDocument toDocument(Person p) { - JsonObject content = JsonObject.empty() - .put("type", "Person") - .put("name", p.getName()) - .put("homeTown", p.getHomeTown()); + JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown()); return JsonDocument.create(p.getId(), content); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java index 5ffe7acf24..cad3bdd5a5 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java @@ -10,19 +10,18 @@ public class RegistrationService { @Autowired private PersonCrudService crud; - + public void registerNewPerson(String name, String homeTown) { Person person = new Person(); person.setName(name); person.setHomeTown(homeTown); crud.create(person); } - + public Person findRegistrant(String id) { - try{ + try { return crud.read(id); - } - catch(CouchbaseException e) { + } catch (CouchbaseException e) { return crud.readFromReplica(id); } } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java index 97ff1e4fd5..1ea9c72114 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java @@ -5,5 +5,5 @@ import com.couchbase.client.java.Bucket; public interface BucketService { Bucket getBucket(); - + } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java index a8543fbd91..da7a10141f 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java @@ -7,11 +7,11 @@ import com.couchbase.client.java.Bucket; import com.couchbase.client.java.document.JsonDocument; public interface ClusterService { - + Bucket openBucket(String name, String password); - + List getDocuments(Bucket bucket, Iterable keys); - + List getDocumentsAsync(AsyncBucket bucket, Iterable keys); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java index 3499fa956e..1cceb11ccc 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java @@ -29,7 +29,7 @@ public class ClusterServiceImpl implements ClusterService { private Cluster cluster; private Map buckets = new ConcurrentHashMap<>(); - + @PostConstruct private void init() { CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create(); @@ -38,7 +38,7 @@ public class ClusterServiceImpl implements ClusterService { @Override synchronized public Bucket openBucket(String name, String password) { - if(!buckets.containsKey(name)) { + if (!buckets.containsKey(name)) { Bucket bucket = cluster.openBucket(name, password); buckets.put(name, bucket); } @@ -48,9 +48,9 @@ public class ClusterServiceImpl implements ClusterService { @Override public List getDocuments(Bucket bucket, Iterable keys) { List docs = new ArrayList<>(); - for(String key : keys) { + for (String key : keys) { JsonDocument doc = bucket.get(key); - if(doc != null) { + if (doc != null) { docs.add(doc); } } @@ -59,18 +59,15 @@ public class ClusterServiceImpl implements ClusterService { @Override public List getDocumentsAsync(final AsyncBucket asyncBucket, Iterable keys) { - Observable asyncBulkGet = Observable - .from(keys) - .flatMap(new Func1>() { - public Observable call(String key) { - return asyncBucket.get(key); - } - }); + Observable asyncBulkGet = Observable.from(keys).flatMap(new Func1>() { + public Observable call(String key) { + return asyncBucket.get(key); + } + }); final List docs = new ArrayList<>(); try { - asyncBulkGet.toBlocking() - .forEach(new Action1() { + asyncBulkGet.toBlocking().forEach(new Action1() { public void call(JsonDocument doc) { docs.add(doc); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java index f683b9f562..5b12af7003 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java @@ -3,14 +3,14 @@ package com.baeldung.couchbase.spring.service; public interface CrudService { void create(T t); - + T read(String id); - + T readFromReplica(String id); - + void update(T t); - + void delete(String id); - + boolean exists(String id); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java index cf4861fbeb..f63bb8691b 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java @@ -5,6 +5,6 @@ import com.couchbase.client.java.document.JsonDocument; public interface JsonDocumentConverter { JsonDocument toDocument(T t); - + T fromDocument(JsonDocument doc); } diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java index 8a28deb1d6..b91c131912 100644 --- a/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java @@ -14,15 +14,15 @@ public class TutorialBucketService implements BucketService { @Autowired private ClusterService couchbase; - + private Bucket bucket; - + @PostConstruct private void init() { bucket = couchbase.openBucket("baeldung-tutorial", ""); } - @Override + @Override public Bucket getBucket() { return bucket; } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java index 6afdfe04bd..efc3e9957f 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java @@ -4,6 +4,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan(basePackages={"com.baeldung.couchbase.async"}) +@ComponentScan(basePackages = { "com.baeldung.couchbase.async" }) public class AsyncIntegrationTestConfig { } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java index 5907a4cc63..565aaed5da 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java @@ -29,10 +29,10 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { @Autowired @Qualifier("TutorialBucketService") private BucketService bucketService; - + @Autowired private PersonDocumentConverter converter; - + private Bucket bucket; @PostConstruct @@ -42,182 +42,175 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { @Test public final void givenRandomPerson_whenCreate_thenPersonPersisted() { - //create person + // create person Person person = randomPerson(); personService.create(person); - - //check results + + // check results assertNotNull(person.getId()); assertNotNull(bucket.get(person.getId())); - - //cleanup + + // cleanup bucket.remove(person.getId()); } @Test public final void givenId_whenRead_thenReturnsPerson() { - //create and insert person document + // create and insert person document String id = insertRandomPersonDocument().id(); - //read person and check results + // read person and check results assertNotNull(personService.read(id)); - - //cleanup + + // cleanup bucket.remove(id); } @Test public final void givenNewHometown_whenUpdate_thenNewHometownPersisted() { - //create and insert person document + // create and insert person document JsonDocument doc = insertRandomPersonDocument(); - - //update person + + // update person Person expected = converter.fromDocument(doc); String updatedHomeTown = RandomStringUtils.randomAlphabetic(12); expected.setHomeTown(updatedHomeTown); personService.update(expected); - - //check results + + // check results JsonDocument actual = bucket.get(expected.getId()); assertNotNull(actual); assertNotNull(actual.content()); assertEquals(expected.getHomeTown(), actual.content().getString("homeTown")); - - //cleanup + + // cleanup bucket.remove(expected.getId()); } @Test public final void givenRandomPerson_whenDelete_thenPersonNotInBucket() { - //create and insert person document + // create and insert person document String id = insertRandomPersonDocument().id(); - //delete person and check results + // delete person and check results personService.delete(id); assertNull(bucket.get(id)); } - + @Test public final void givenIds_whenReadBulk_thenReturnsOnlyPersonsWithMatchingIds() { List ids = new ArrayList<>(); - - //add some person documents - for(int i=0; i<5; i++) { + + // add some person documents + for (int i = 0; i < 5; i++) { ids.add(insertRandomPersonDocument().id()); } - - //perform bulk read + + // perform bulk read List persons = personService.readBulk(ids); - - //check results - for(Person person : persons) { + + // check results + for (Person person : persons) { assertTrue(ids.contains(person.getId())); } - - //cleanup - for(String id : ids) { + + // cleanup + for (String id : ids) { bucket.remove(id); - } + } } - + @Test public final void givenPersons_whenInsertBulk_thenPersonsAreInserted() { - - //create some persons + + // create some persons List persons = new ArrayList<>(); - for(int i=0; i<5; i++) { + for (int i = 0; i < 5; i++) { persons.add(randomPerson()); } - //perform bulk insert + // perform bulk insert personService.createBulk(persons); - - //check results - for(Person person : persons) { + + // check results + for (Person person : persons) { assertNotNull(bucket.get(person.getId())); } - - //cleanup - for(Person person : persons) { + + // cleanup + for (Person person : persons) { bucket.remove(person.getId()); - } + } } @Test public final void givenPersons_whenUpdateBulk_thenPersonsAreUpdated() { - + List ids = new ArrayList<>(); - - //add some person documents - for(int i=0; i<5; i++) { + + // add some person documents + for (int i = 0; i < 5; i++) { ids.add(insertRandomPersonDocument().id()); } - //load persons from Couchbase + // load persons from Couchbase List persons = new ArrayList<>(); - for(String id : ids) { + for (String id : ids) { persons.add(converter.fromDocument(bucket.get(id))); } - //modify persons - for(Person person : persons) { + // modify persons + for (Person person : persons) { person.setHomeTown(RandomStringUtils.randomAlphabetic(10)); } - - //perform bulk update + + // perform bulk update personService.updateBulk(persons); - - //check results - for(Person person : persons) { + + // check results + for (Person person : persons) { JsonDocument doc = bucket.get(person.getId()); assertEquals(person.getName(), doc.content().getString("name")); assertEquals(person.getHomeTown(), doc.content().getString("homeTown")); } - - //cleanup - for(String id : ids) { + + // cleanup + for (String id : ids) { bucket.remove(id); - } + } } - + @Test public void givenIds_whenDeleteBulk_thenPersonsAreDeleted() { - + List ids = new ArrayList<>(); - - //add some person documents - for(int i=0; i<5; i++) { + + // add some person documents + for (int i = 0; i < 5; i++) { ids.add(insertRandomPersonDocument().id()); } - - //perform bulk delete + + // perform bulk delete personService.deleteBulk(ids); - - //check results - for(String id : ids) { + + // check results + for (String id : ids) { assertNull(bucket.get(id)); - } + } } - + private JsonDocument insertRandomPersonDocument() { Person expected = randomPersonWithId(); JsonDocument doc = converter.toDocument(expected); - return bucket.insert(doc); + return bucket.insert(doc); } private Person randomPerson() { - return Person.Builder.newInstance() - .name(RandomStringUtils.randomAlphabetic(10)) - .homeTown(RandomStringUtils.randomAlphabetic(10)) - .build(); + return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); } private Person randomPersonWithId() { - return Person.Builder.newInstance() - .id(UUID.randomUUID().toString()) - .name(RandomStringUtils.randomAlphabetic(10)) - .homeTown(RandomStringUtils.randomAlphabetic(10)) - .build(); + return Person.Builder.newInstance().id(UUID.randomUUID().toString()).name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); } } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java index 08e3728c77..d0db5d37a3 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java @@ -22,9 +22,9 @@ public class ClusterServiceIntegrationTest extends AsyncIntegrationTest { @Autowired private ClusterService couchbaseService; - + private Bucket defaultBucket; - + @Test public void whenOpenBucket_thenBucketIsNotNull() throws Exception { defaultBucket = couchbaseService.openBucket("default", ""); diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java index ac71911b9b..d814b31a07 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java @@ -4,6 +4,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan(basePackages={"com.baeldung.couchbase.spring"}) +@ComponentScan(basePackages = { "com.baeldung.couchbase.spring" }) public class IntegrationTestConfig { } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java index b3fadae6ca..ec15be1acc 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java @@ -24,7 +24,7 @@ public class PersonCrudServiceIntegrationTest extends IntegrationTest { @PostConstruct private void init() { clarkKent = personService.read(CLARK_KENT_ID); - if(clarkKent == null) { + if (clarkKent == null) { clarkKent = buildClarkKent(); personService.create(clarkKent); } @@ -50,7 +50,7 @@ public class PersonCrudServiceIntegrationTest extends IntegrationTest { personService.create(expected); String updatedHomeTown = RandomStringUtils.randomAlphabetic(12); expected.setHomeTown(updatedHomeTown); - personService.update(expected); + personService.update(expected); Person actual = personService.read(expected.getId()); assertNotNull(actual); assertEquals(expected.getHomeTown(), actual.getHomeTown()); @@ -66,17 +66,10 @@ public class PersonCrudServiceIntegrationTest extends IntegrationTest { } private Person buildClarkKent() { - return Person.Builder.newInstance() - .id(CLARK_KENT_ID) - .name(CLARK_KENT) - .homeTown(SMALLVILLE) - .build(); + return Person.Builder.newInstance().id(CLARK_KENT_ID).name(CLARK_KENT).homeTown(SMALLVILLE).build(); } private Person randomPerson() { - return Person.Builder.newInstance() - .name(RandomStringUtils.randomAlphabetic(10)) - .homeTown(RandomStringUtils.randomAlphabetic(10)) - .build(); + return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); } } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java index f3ee4585a3..ead247dfbc 100644 --- a/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java @@ -21,9 +21,9 @@ public class ClusterServiceIntegrationTest extends IntegrationTest { @Autowired private ClusterService couchbaseService; - + private Bucket defaultBucket; - + @Test public void whenOpenBucket_thenBucketIsNotNull() throws Exception { defaultBucket = couchbaseService.openBucket("default", ""); diff --git a/deltaspike/src/main/java/baeldung/data/MemberRepository.java b/deltaspike/src/main/java/baeldung/data/MemberRepository.java index 56a4a4e634..220388bcf0 100644 --- a/deltaspike/src/main/java/baeldung/data/MemberRepository.java +++ b/deltaspike/src/main/java/baeldung/data/MemberRepository.java @@ -35,9 +35,6 @@ public abstract class MemberRepository extends AbstractEntityRepository findAllOrderedByNameWithQueryDSL() { final QMember member = QMember.member; - return jpaQuery() - .from(member) - .orderBy(member.email.asc()) - .list(member); + return jpaQuery().from(member).orderBy(member.email.asc()).list(member); } } diff --git a/deltaspike/src/main/java/baeldung/service/MemberRegistration.java b/deltaspike/src/main/java/baeldung/service/MemberRegistration.java index ec65471622..9396e550d5 100644 --- a/deltaspike/src/main/java/baeldung/service/MemberRegistration.java +++ b/deltaspike/src/main/java/baeldung/service/MemberRegistration.java @@ -64,7 +64,6 @@ public class MemberRegistration { } } - public void register(Member member) throws Exception { log.info("Registering " + member.getName()); validateMember(member); diff --git a/deltaspike/src/test/java/baeldung/test/MemberRegistrationTest.java b/deltaspike/src/test/java/baeldung/test/MemberRegistrationTest.java index 0270d2d164..7014d066d2 100644 --- a/deltaspike/src/test/java/baeldung/test/MemberRegistrationTest.java +++ b/deltaspike/src/test/java/baeldung/test/MemberRegistrationTest.java @@ -41,27 +41,13 @@ import org.junit.runner.RunWith; public class MemberRegistrationTest { @Deployment public static Archive createTestArchive() { - File[] files = Maven.resolver().loadPomFromFile("pom.xml") - .importRuntimeDependencies().resolve().withTransitivity().asFile(); + File[] files = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile(); return ShrinkWrap.create(WebArchive.class, "test.war") - .addClasses( - EntityManagerProducer.class, - Member.class, - MemberRegistration.class, - MemberRepository.class, - Resources.class, - QueryDslRepositoryExtension.class, - QueryDslSupport.class, - SecondaryPersistenceUnit.class, - SecondaryEntityManagerProducer.class, - SecondaryEntityManagerResolver.class) - .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml") - .addAsResource("META-INF/apache-deltaspike.properties") - .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") - .addAsWebInfResource("test-ds.xml") - .addAsWebInfResource("test-secondary-ds.xml") - .addAsLibraries(files); + .addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class, + SecondaryEntityManagerProducer.class, SecondaryEntityManagerResolver.class) + .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml").addAsResource("META-INF/apache-deltaspike.properties").addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml").addAsWebInfResource("test-ds.xml") + .addAsWebInfResource("test-secondary-ds.xml").addAsLibraries(files); } @Inject diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java index 4ac445b083..32bcdc90b6 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/DiscoveryApplication.java @@ -7,7 +7,7 @@ import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class DiscoveryApplication { - public static void main(String[] args) { - SpringApplication.run(DiscoveryApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(DiscoveryApplication.class, args); + } } diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java index b559da6394..a89faba962 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java @@ -16,50 +16,29 @@ import org.springframework.security.config.http.SessionCreationPolicy; public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{ + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("discUser").password("discPassword").roles("SYSTEM"); } @Override protected void configure(HttpSecurity http) throws Exception { - http.sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.ALWAYS) - .and() - .requestMatchers() - .antMatchers("/eureka/**") - .and() - .authorizeRequests() - .antMatchers("/eureka/**").hasRole("SYSTEM") - .anyRequest().denyAll() - .and() - .httpBasic() - .and() - .csrf() - .disable(); + http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and().requestMatchers().antMatchers("/eureka/**").and().authorizeRequests().antMatchers("/eureka/**").hasRole("SYSTEM").anyRequest().denyAll().and().httpBasic().and().csrf() + .disable(); } @Configuration - //no order tag means this is the last security filter to be evaluated + // no order tag means this is the last security filter to be evaluated public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication(); } - @Override protected void configure(HttpSecurity http) throws Exception { - http - .sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.NEVER) - .and() - .httpBasic() - .disable() - .authorizeRequests() - .antMatchers(HttpMethod.GET, "/").hasRole("ADMIN") - .antMatchers("/info","/health").authenticated() - .anyRequest().denyAll() - .and() - .csrf() - .disable(); + @Override + protected void configure(HttpSecurity http) throws Exception { + http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and().httpBasic().disable().authorizeRequests().antMatchers(HttpMethod.GET, "/").hasRole("ADMIN").antMatchers("/info", "/health").authenticated().anyRequest().denyAll() + .and().csrf().disable(); } } }