formatting work

This commit is contained in:
eugenp 2017-01-29 16:01:58 +02:00
parent 1eb53d544c
commit 44bf48068f
44 changed files with 341 additions and 484 deletions

View File

@ -10,7 +10,7 @@ public interface PrivateInterface {
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");

View File

@ -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(){
public static String getSystemProperties() {
StringBuilder sb = new StringBuilder();
System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) );
System.getProperties().forEach((s1, s2) -> sb.append(s1 + " - " + s2));
return sb.toString();
}
}

View File

@ -8,7 +8,6 @@ public class ServiceMain {
ProcessHandle thisProcess = ProcessHandle.current();
long pid = thisProcess.getPid();
Optional<String[]> opArgs = Optional.ofNullable(args);
String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));

View File

@ -19,10 +19,7 @@ public class Java9OptionalsStreamTest {
public void filterOutPresentOptionalsWithFilter() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
List<String> 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<String> filteredList = listOfOptionals.stream()
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
.collect(Collectors.toList());
List<String> 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<String> filteredList = listOfOptionals.stream()
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
.collect(Collectors.toList());
List<String> 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<String> filteredList = listOfOptionals.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
List<String> filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));

View File

@ -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);
}
}

View File

@ -1,7 +1,5 @@
package com.baeldung.java9.httpclient;
import static java.net.HttpURLConnection.HTTP_OK;
import static org.junit.Assert.assertTrue;
@ -28,7 +26,7 @@ import org.junit.Test;
public class SimpleHttpRequestsTest {
private URI httpURI;
private URI httpURI;
@Before
public void init() throws URISyntaxException {
@ -37,24 +35,24 @@ 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<HttpResponse> 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
@ -68,11 +66,11 @@ public class SimpleHttpRequestsTest {
}
@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);
@ -85,42 +83,44 @@ public class SimpleHttpRequestsTest {
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<String, List<String>> hMap = h.map();
for(String k : hMap.keySet()){
sb.append(k).append(":");
List<String> 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<String, List<String>> hMap = h.map();
for (String k : hMap.keySet()) {
sb.append(k).append(":");
List<String> l = hMap.get(k);
if (l != null) {
l.forEach(s -> {
sb.append(s).append(",");
});
}
sb.append("\n");
}
return sb.toString();
}
}

View File

@ -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 {
}
}

View File

@ -13,15 +13,11 @@ public class CollectorImprovementTest {
public void givenList_whenSatifyPredicate_thenMapValueWithOccurences() {
List<Integer> numbers = List.of(1, 2, 3, 5, 5);
Map<Integer, Long> result = numbers.stream()
.filter(val -> val > 3).collect(Collectors.groupingBy(
Function.identity(), Collectors.counting()));
Map<Integer, Long> 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());
}
@ -32,20 +28,13 @@ public class CollectorImprovementTest {
Blog blog2 = new Blog("2", "Disappointing", "Ok", "Could be better");
List<Blog> blogs = List.of(blog1, blog2);
Map<String, List<List<String>>> authorComments1 =
blogs.stream().collect(Collectors.groupingBy(
Blog::getAuthorName, Collectors.mapping(
Blog::getComments, Collectors.toList())));
Map<String, List<List<String>>> 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<String, List<String>> authorComments2 =
blogs.stream().collect(Collectors.groupingBy(
Blog::getAuthorName, Collectors.flatMapping(
blog -> blog.getComments().stream(),
Collectors.toList())));
Map<String, List<String>> 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());
@ -54,7 +43,7 @@ public class CollectorImprovementTest {
}
class Blog {
private String authorName;
private String authorName;
private List<String> comments;
public Blog(String authorName, String... comments) {

View File

@ -17,16 +17,11 @@ public class StreamFeaturesTest {
public static class TakeAndDropWhileTest {
public Stream<String> 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<String> 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<String> collection = Arrays.asList("A", "B", "C");
private Map<String, Integer> map = new HashMap<>() {{
put("A", 10);
put("C", 30);
}};
private Map<String, Integer> map = new HashMap<>() {
{
put("A", 10);
put("C", 30);
}
};
private Stream<Integer> getStreamWithOfNullable() {
return collection.stream()
.flatMap(s -> Stream.ofNullable(map.get(s)));
return collection.stream().flatMap(s -> Stream.ofNullable(map.get(s)));
}
private Stream<Integer> 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<Integer> testOfNullableFrom(Stream<Integer> stream) {
@ -107,10 +102,7 @@ public class StreamFeaturesTest {
@Test
public void testOfNullable() {
assertEquals(
testOfNullableFrom(getStream()),
testOfNullableFrom(getStreamWithOfNullable())
);
assertEquals(testOfNullableFrom(getStream()), testOfNullableFrom(getStreamWithOfNullable()));
}

View File

@ -22,51 +22,50 @@ 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<String[]> args = procInfo.arguments();
Optional<String> cmd = procInfo.commandLine();
Optional<String> cmd = procInfo.commandLine();
Optional<Instant> startTime = procInfo.startInstant();
Optional<Duration> 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<ProcessHandle> 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<ProcessHandle> childProc = ProcessHandle.current().children();
assertEquals( childProc.count(), numberOfChildProcesses);
Stream<ProcessHandle> 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<ProcessHandle> 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");
});
});
@ -74,38 +73,38 @@ public class ProcessApi {
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<String> cmdParams = new ArrayList<String>(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<Integer> randArr = new ArrayList<Integer>(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());
}
}

View File

@ -9,7 +9,8 @@ public class Person implements CouchbaseEntity {
private String name;
private String homeTown;
Person() {}
Person() {
}
public Person(Builder b) {
this.id = b.id;

View File

@ -13,9 +13,7 @@ import com.baeldung.couchbase.async.service.BucketService;
public class PersonCrudService extends AbstractCrudService<Person> {
@Autowired
public PersonCrudService(
@Qualifier("TutorialBucketService") BucketService bucketService,
PersonDocumentConverter converter) {
public PersonCrudService(@Qualifier("TutorialBucketService") BucketService bucketService, PersonDocumentConverter converter) {
super(bucketService, converter);
}

View File

@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter<Person> {
@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);
}

View File

@ -19,10 +19,9 @@ public class RegistrationService {
}
public Person findRegistrant(String id) {
try{
try {
return crud.read(id);
}
catch(CouchbaseException e) {
} catch (CouchbaseException e) {
return crud.readFromReplica(id);
}
}

View File

@ -24,4 +24,4 @@ public abstract class AbstractBucketService implements BucketService {
public Bucket getBucket() {
return bucket;
}
}
}

View File

@ -40,7 +40,7 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> 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<T extends CouchbaseEntity> implements
@Override
public List<T> readBulk(Iterable<String> ids) {
final AsyncBucket asyncBucket = bucket.async();
Observable<JsonDocument> asyncOperation = Observable
.from(ids)
.flatMap(new Func1<String, Observable<JsonDocument>>() {
public Observable<JsonDocument> call(String key) {
return asyncBucket.get(key);
}
});
Observable<JsonDocument> asyncOperation = Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() {
public Observable<JsonDocument> call(String key) {
return asyncBucket.get(key);
}
});
final List<T> items = new ArrayList<T>();
try {
asyncOperation.toBlocking()
.forEach(new Action1<JsonDocument>() {
asyncOperation.toBlocking().forEach(new Action1<JsonDocument>() {
public void call(JsonDocument doc) {
T item = converter.fromDocument(doc);
items.add(item);
@ -100,72 +97,42 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements
@Override
public void createBulk(Iterable<T> items) {
final AsyncBucket asyncBucket = bucket.async();
Observable
.from(items)
.flatMap(new Func1<T, Observable<JsonDocument>>() {
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> 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<T> items) {
final AsyncBucket asyncBucket = bucket.async();
Observable
.from(items)
.flatMap(new Func1<T, Observable<JsonDocument>>() {
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> 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<String> ids) {
final AsyncBucket asyncBucket = bucket.async();
Observable
.from(ids)
.flatMap(new Func1<String, Observable<JsonDocument>>() {
Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> 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

View File

@ -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);
}

View File

@ -20,10 +20,7 @@ public class CodeSnippets {
}
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");
}
@ -36,12 +33,7 @@ public class CodeSnippets {
}
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);
@ -70,12 +62,11 @@ public class CodeSnippets {
}
static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) {
try{
try {
return bucket.get(id);
}
catch(CouchbaseException e) {
} catch (CouchbaseException e) {
List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST);
if(!list.isEmpty()) {
if (!list.isEmpty()) {
return list.get(0);
}
}
@ -85,8 +76,8 @@ public class CodeSnippets {
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();
}

View File

@ -7,7 +7,8 @@ public class Person {
private String name;
private String homeTown;
Person() {}
Person() {
}
public Person(Builder b) {
this.id = b.id;

View File

@ -32,7 +32,7 @@ public class PersonCrudService implements CrudService<Person> {
@Override
public void create(Person person) {
if(person.getId() == null) {
if (person.getId() == null) {
person.setId(UUID.randomUUID().toString());
}
JsonDocument document = converter.toDocument(person);

View File

@ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter<Person> {
@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);
}

View File

@ -19,10 +19,9 @@ public class RegistrationService {
}
public Person findRegistrant(String id) {
try{
try {
return crud.read(id);
}
catch(CouchbaseException e) {
} catch (CouchbaseException e) {
return crud.readFromReplica(id);
}
}

View File

@ -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<JsonDocument> getDocuments(Bucket bucket, Iterable<String> keys) {
List<JsonDocument> 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<JsonDocument> getDocumentsAsync(final AsyncBucket asyncBucket, Iterable<String> keys) {
Observable<JsonDocument> asyncBulkGet = Observable
.from(keys)
.flatMap(new Func1<String, Observable<JsonDocument>>() {
public Observable<JsonDocument> call(String key) {
return asyncBucket.get(key);
}
});
Observable<JsonDocument> asyncBulkGet = Observable.from(keys).flatMap(new Func1<String, Observable<JsonDocument>>() {
public Observable<JsonDocument> call(String key) {
return asyncBucket.get(key);
}
});
final List<JsonDocument> docs = new ArrayList<>();
try {
asyncBulkGet.toBlocking()
.forEach(new Action1<JsonDocument>() {
asyncBulkGet.toBlocking().forEach(new Action1<JsonDocument>() {
public void call(JsonDocument doc) {
docs.add(doc);
}

View File

@ -22,7 +22,7 @@ public class TutorialBucketService implements BucketService {
bucket = couchbase.openBucket("baeldung-tutorial", "");
}
@Override
@Override
public Bucket getBucket() {
return bucket;
}

View File

@ -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 {
}

View File

@ -42,57 +42,57 @@ 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));
}
@ -101,21 +101,21 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
public final void givenIds_whenReadBulk_thenReturnsOnlyPersonsWithMatchingIds() {
List<String> 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<Person> 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);
}
}
@ -123,22 +123,22 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
@Test
public final void givenPersons_whenInsertBulk_thenPersonsAreInserted() {
//create some persons
// create some persons
List<Person> 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());
}
}
@ -148,34 +148,34 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
List<String> 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<Person> 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);
}
}
@ -185,16 +185,16 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
List<String> 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));
}
@ -207,17 +207,10 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
}
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();
}
}

View File

@ -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 {
}

View File

@ -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);
}
@ -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();
}
}

View File

@ -35,9 +35,6 @@ public abstract class MemberRepository extends AbstractEntityRepository<Member,
public List<Member> 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);
}
}

View File

@ -64,7 +64,6 @@ public class MemberRegistration {
}
}
public void register(Member member) throws Exception {
log.info("Registering " + member.getName());
validateMember(member);

View File

@ -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

View File

@ -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);
}
}

View File

@ -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();
}
}
}