From e57bd766456f6954bfd614d0da5a9f04dc47c7c4 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 10 Sep 2018 16:09:45 +0400 Subject: [PATCH 01/18] HashMap sort TreeMap --- .../com/baeldung/performance/Employee.java | 8 ++++ .../java/com/baeldung/sort/SortHashMap.java | 42 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java diff --git a/core-java-collections/src/main/java/com/baeldung/performance/Employee.java b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java index d811cfbb7d..1ed4410371 100644 --- a/core-java-collections/src/main/java/com/baeldung/performance/Employee.java +++ b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java @@ -44,4 +44,12 @@ public class Employee { result = 31 * result + name.hashCode(); return result; } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } } diff --git a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java new file mode 100644 index 0000000000..fe0aab9218 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -0,0 +1,42 @@ +package com.baeldung.sort; + +import com.baeldung.performance.Employee; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +public class SortHashMap { + + private static Map map = new HashMap<>(); + + public static void main(String[] args) { + + initialize(); + + treeMapSortByKey(); + } + + public static void treeMapSortByKey() + { + TreeMap sorted = new TreeMap<>(map); + sorted.putAll(map); + + for (Map.Entry entry : sorted.entrySet()) { + System.out.println("Key = " + entry.getKey() + + ", Value = " + entry.getValue()); + } + + } + + private static void initialize() { + Employee employee1 = new Employee(1L, "Mher"); + map.put(employee1.getName(), employee1); + Employee employee2 = new Employee(22L, "Annie"); + map.put(employee2.getName(), employee2); + Employee employee3 = new Employee(8L, "John"); + map.put(employee3.getName(), employee3); + Employee employee4 = new Employee(2L, "George"); + map.put(employee4.getName(), employee4); + } +} From 23fc41db24562e22d1a88ffa6606b1d7d9e3f5e1 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 10 Sep 2018 17:22:21 +0400 Subject: [PATCH 02/18] ArrayList and TreeSet --- .../java/com/baeldung/sort/SortHashMap.java | 46 ++++++++++++++++--- 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java index fe0aab9218..6bf56274ac 100644 --- a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -2,9 +2,7 @@ package com.baeldung.sort; import com.baeldung.performance.Employee; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; +import java.util.*; public class SortHashMap { @@ -14,11 +12,28 @@ public class SortHashMap { initialize(); - treeMapSortByKey(); + //treeMapSortByKey(); + + //arrayListSortByValue(); + //arrayListSortByKey(); + + treeSetByKey(); + treeSetByValue(); } - public static void treeMapSortByKey() - { + private static void treeSetByValue() { + Comparator comp = (Employee o1, Employee o2) -> (o1.getId().compareTo(o2.getId())); + SortedSet values = new TreeSet<>(comp); + values.addAll(map.values()); + System.out.println(values); + } + + private static void treeSetByKey() { + SortedSet keys = new TreeSet<>(map.keySet()); + System.out.println(keys); + } + + private static void treeMapSortByKey() { TreeMap sorted = new TreeMap<>(map); sorted.putAll(map); @@ -29,6 +44,25 @@ public class SortHashMap { } + private static void arrayListSortByValue() { + List employeeById = new ArrayList<>(map.values()); + + Collections.sort(employeeById, new Comparator() { + + public int compare(Employee o1, Employee o2) { + return (int)(o1.getId() - o2.getId()); + } + }); + + System.out.println(employeeById); + } + + private static void arrayListSortByKey() { + List employeeByKey = new ArrayList<>(map.keySet()); + Collections.sort(employeeByKey); + System.out.println(employeeByKey); + } + private static void initialize() { Employee employee1 = new Employee(1L, "Mher"); map.put(employee1.getName(), employee1); From 2d15cb3b49bd2ae1ad1f39bc2d87b864538bce4b Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Tue, 11 Sep 2018 15:58:47 +0400 Subject: [PATCH 03/18] set benchmark tests --- .../src/main/java/com/baeldung/sort/SortHashMap.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java index 6bf56274ac..6adb2ee120 100644 --- a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -17,8 +17,16 @@ public class SortHashMap { //arrayListSortByValue(); //arrayListSortByKey(); - treeSetByKey(); - treeSetByValue(); + //treeSetByKey(); + //treeSetByValue(); + + sortStream(); + } + + private static void sortStream() { + map.entrySet().stream() + .sorted(Map.Entry.comparingByKey().reversed()) + .forEach(System.out::println); } private static void treeSetByValue() { From 6e71cd302cfac6e259693c4d28009023bbf54a3f Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Thu, 13 Sep 2018 00:10:16 +0400 Subject: [PATCH 04/18] HashMap sort initial version --- .../java/com/baeldung/sort/SortHashMap.java | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java index 6adb2ee120..938f740e9a 100644 --- a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -1,8 +1,11 @@ package com.baeldung.sort; import com.baeldung.performance.Employee; +import com.google.common.collect.Lists; +import com.google.common.collect.Ordering; import java.util.*; +import java.util.stream.Collectors; public class SortHashMap { @@ -20,13 +23,36 @@ public class SortHashMap { //treeSetByKey(); //treeSetByValue(); - sortStream(); + //sortStream(); + + sortGuava(); + } + + private static void sortGuava() { + Ordering> orderById = new Ordering>() { + @Override + public int compare(Map.Entry left, Map.Entry right) { + return left.getValue().getId().compareTo(right.getValue().getId()); + } + }; + + List> toList = Lists.newArrayList(map.entrySet()); + Collections.sort(toList, orderById); + + toList.forEach(System.out::println); } private static void sortStream() { map.entrySet().stream() .sorted(Map.Entry.comparingByKey().reversed()) .forEach(System.out::println); + + Map result = map.entrySet().stream() + .sorted(Comparator.comparingLong(e -> e.getValue().getId())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, + (oldValue, newValue) -> oldValue, LinkedHashMap::new)); + + result.entrySet().forEach(System.out::println); } private static void treeSetByValue() { From e0172002d5c171ea2c2dc93b59bfede09b6524dc Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Thu, 13 Sep 2018 01:14:09 +0400 Subject: [PATCH 05/18] minor change --- .../src/main/java/com/baeldung/sort/SortHashMap.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java index 938f740e9a..c803e8f193 100644 --- a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -63,8 +63,8 @@ public class SortHashMap { } private static void treeSetByKey() { - SortedSet keys = new TreeSet<>(map.keySet()); - System.out.println(keys); + SortedSet keysSet = new TreeSet<>(map.keySet()); + System.out.println(keysSet); } private static void treeMapSortByKey() { From fdf873daf7c718235b75999081f1acb10585ec62 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 14 Sep 2018 12:12:48 +0400 Subject: [PATCH 06/18] adding comparator to Employee --- .../main/java/com/baeldung/sort/Employee.java | 60 +++++++++++++++++++ .../java/com/baeldung/sort/SortHashMap.java | 41 +++++-------- 2 files changed, 74 insertions(+), 27 deletions(-) create mode 100644 core-java-collections/src/main/java/com/baeldung/sort/Employee.java diff --git a/core-java-collections/src/main/java/com/baeldung/sort/Employee.java b/core-java-collections/src/main/java/com/baeldung/sort/Employee.java new file mode 100644 index 0000000000..b5e56f6141 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/sort/Employee.java @@ -0,0 +1,60 @@ +package com.baeldung.sort; + +public class Employee implements Comparable { + + private Long id; + private String name; + + public Employee(Long id, String name) { + this.name = name; + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Employee employee = (Employee) o; + + if (!id.equals(employee.id)) return false; + return name.equals(employee.name); + + } + + @Override + public int hashCode() { + int result = id.hashCode(); + result = 31 * result + name.hashCode(); + return result; + } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } + + @Override + public int compareTo(Employee employee) { + return (int)(this.id - employee.getId()); + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java index c803e8f193..f7ea2f655b 100644 --- a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -1,6 +1,7 @@ package com.baeldung.sort; -import com.baeldung.performance.Employee; +import com.google.common.base.Functions; +import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; @@ -15,31 +16,24 @@ public class SortHashMap { initialize(); - //treeMapSortByKey(); + treeMapSortByKey(); - //arrayListSortByValue(); - //arrayListSortByKey(); + arrayListSortByValue(); + arrayListSortByKey(); - //treeSetByKey(); - //treeSetByValue(); + treeSetByKey(); + treeSetByValue(); - //sortStream(); + sortStream(); sortGuava(); } private static void sortGuava() { - Ordering> orderById = new Ordering>() { - @Override - public int compare(Map.Entry left, Map.Entry right) { - return left.getValue().getId().compareTo(right.getValue().getId()); - } - }; + final Ordering naturalReverseValueOrdering = + Ordering.natural().reverse().nullsLast().onResultOf(Functions.forMap(map, null)); - List> toList = Lists.newArrayList(map.entrySet()); - Collections.sort(toList, orderById); - - toList.forEach(System.out::println); + System.out.println(ImmutableSortedMap.copyOf(map, naturalReverseValueOrdering)); } private static void sortStream() { @@ -48,7 +42,7 @@ public class SortHashMap { .forEach(System.out::println); Map result = map.entrySet().stream() - .sorted(Comparator.comparingLong(e -> e.getValue().getId())) + .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); @@ -56,9 +50,7 @@ public class SortHashMap { } private static void treeSetByValue() { - Comparator comp = (Employee o1, Employee o2) -> (o1.getId().compareTo(o2.getId())); - SortedSet values = new TreeSet<>(comp); - values.addAll(map.values()); + SortedSet values = new TreeSet<>(map.values()); System.out.println(values); } @@ -81,12 +73,7 @@ public class SortHashMap { private static void arrayListSortByValue() { List employeeById = new ArrayList<>(map.values()); - Collections.sort(employeeById, new Comparator() { - - public int compare(Employee o1, Employee o2) { - return (int)(o1.getId() - o2.getId()); - } - }); + Collections.sort(employeeById); System.out.println(employeeById); } From 9d9325b972c4e5e5a65283e0b7b6b8ffcbcac8b1 Mon Sep 17 00:00:00 2001 From: Mher Baghinyan Date: Sun, 16 Sep 2018 11:18:22 +0400 Subject: [PATCH 07/18] Update SortHashMap.java --- .../src/main/java/com/baeldung/sort/SortHashMap.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java index f7ea2f655b..ce2d0d3c3f 100644 --- a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -30,10 +30,10 @@ public class SortHashMap { } private static void sortGuava() { - final Ordering naturalReverseValueOrdering = - Ordering.natural().reverse().nullsLast().onResultOf(Functions.forMap(map, null)); + final Ordering naturalOrdering = + Ordering.natural().onResultOf(Functions.forMap(map, null)); - System.out.println(ImmutableSortedMap.copyOf(map, naturalReverseValueOrdering)); + System.out.println(ImmutableSortedMap.copyOf(map, naturalOrdering)); } private static void sortStream() { From d9724fc1536603bc550dc2e6f63bf93afd5cd39a Mon Sep 17 00:00:00 2001 From: Chirag Dewan Date: Sat, 22 Sep 2018 15:22:06 +0530 Subject: [PATCH 08/18] BAEL-1426 Adding a message generator and updated Word Count Transactional App --- .../kafka/TransactionalMessageProducer.java | 56 +++++++++++++++++++ ...alApp.java => TransactionalWordCount.java} | 39 +++++++------ .../main/java/com/baeldung/kafka/Tuple.java | 24 ++++++++ 3 files changed, 101 insertions(+), 18 deletions(-) create mode 100644 libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java rename libraries/src/main/java/com/baeldung/kafka/{TransactionalApp.java => TransactionalWordCount.java} (66%) create mode 100644 libraries/src/main/java/com/baeldung/kafka/Tuple.java diff --git a/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java b/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java new file mode 100644 index 0000000000..15488bbaf4 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kafka/TransactionalMessageProducer.java @@ -0,0 +1,56 @@ +package com.baeldung.kafka; + +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.KafkaException; + +import java.util.Properties; +import java.util.stream.Stream; + +import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.TRANSACTIONAL_ID_CONFIG; +import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG; + +public class TransactionalMessageProducer { + + private static final String DATA_MESSAGE_1 = "Put any space separated data here for count"; + private static final String DATA_MESSAGE_2 = "Output will contain count of every word in the message"; + + public static void main(String[] args) { + + KafkaProducer producer = createKafkaProducer(); + + producer.initTransactions(); + + try{ + + producer.beginTransaction(); + + Stream.of(DATA_MESSAGE_1, DATA_MESSAGE_2).forEach(s -> producer.send( + new ProducerRecord("input", null, s))); + + producer.commitTransaction(); + + }catch (KafkaException e){ + + producer.abortTransaction(); + + } + + } + + private static KafkaProducer createKafkaProducer() { + + Properties props = new Properties(); + props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ENABLE_IDEMPOTENCE_CONFIG, "true"); + props.put(TRANSACTIONAL_ID_CONFIG, "prod-0"); + props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + + return new KafkaProducer(props); + + } +} diff --git a/libraries/src/main/java/com/baeldung/kafka/TransactionalApp.java b/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java similarity index 66% rename from libraries/src/main/java/com/baeldung/kafka/TransactionalApp.java rename to libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java index 1e95041a0d..0563ba6684 100644 --- a/libraries/src/main/java/com/baeldung/kafka/TransactionalApp.java +++ b/libraries/src/main/java/com/baeldung/kafka/TransactionalWordCount.java @@ -14,6 +14,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static java.time.Duration.ofSeconds; import static java.util.Collections.singleton; @@ -21,16 +23,16 @@ import static org.apache.kafka.clients.consumer.ConsumerConfig.*; import static org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG; import static org.apache.kafka.clients.producer.ProducerConfig.*; -public class TransactionalApp { +public class TransactionalWordCount { - private static final String CONSUMER_GROUP_ID = "test"; + private static final String CONSUMER_GROUP_ID = "my-group-id"; private static final String OUTPUT_TOPIC = "output"; private static final String INPUT_TOPIC = "input"; public static void main(String[] args) { - KafkaConsumer consumer = initConsumer(); - KafkaProducer producer = initProducer(); + KafkaConsumer consumer = createKafkaConsumer(); + KafkaProducer producer = createKafkaProducer(); producer.initTransactions(); @@ -38,12 +40,17 @@ public class TransactionalApp { while (true) { - ConsumerRecords records = consumer.poll(ofSeconds(20)); + ConsumerRecords records = consumer.poll(ofSeconds(60)); + + Map wordCountMap = records.records(new TopicPartition(INPUT_TOPIC, 0)) + .stream() + .flatMap(record -> Stream.of(record.value().split(" "))) + .map(word -> Tuple.of(word, 1)) + .collect(Collectors.toMap(tuple -> tuple.getKey(), t1 -> t1.getValue(), (v1, v2) -> v1 + v2)); producer.beginTransaction(); - for (ConsumerRecord record : records) - producer.send(new ProducerRecord(OUTPUT_TOPIC, record)); + wordCountMap.forEach((key, value) -> producer.send(new ProducerRecord(OUTPUT_TOPIC, key, value.toString()))); Map offsetsToCommit = new HashMap<>(); @@ -51,7 +58,7 @@ public class TransactionalApp { List> partitionedRecords = records.records(partition); long offset = partitionedRecords.get(partitionedRecords.size() - 1).offset(); - offsetsToCommit.put(partition, new OffsetAndMetadata(offset)); + offsetsToCommit.put(partition, new OffsetAndMetadata(offset + 1)); } producer.sendOffsetsToTransaction(offsetsToCommit, CONSUMER_GROUP_ID); @@ -68,11 +75,12 @@ public class TransactionalApp { } - private static KafkaConsumer initConsumer() { + private static KafkaConsumer createKafkaConsumer() { Properties props = new Properties(); props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(GROUP_ID_CONFIG, CONSUMER_GROUP_ID); props.put(ENABLE_AUTO_COMMIT_CONFIG, "false"); + props.put(ISOLATION_LEVEL_CONFIG, "read_committed"); props.put(KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); props.put(VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); @@ -81,19 +89,14 @@ public class TransactionalApp { return consumer; } - private static KafkaProducer initProducer() { + private static KafkaProducer createKafkaProducer() { Properties props = new Properties(); - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); - props.put(ACKS_CONFIG, "all"); - props.put(RETRIES_CONFIG, 3); - props.put(BATCH_SIZE_CONFIG, 16384); - props.put(LINGER_MS_CONFIG, 1); - props.put(BUFFER_MEMORY_CONFIG, 33554432); + props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ENABLE_IDEMPOTENCE_CONFIG, "true"); props.put(TRANSACTIONAL_ID_CONFIG, "prod-1"); - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); + props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); return new KafkaProducer(props); diff --git a/libraries/src/main/java/com/baeldung/kafka/Tuple.java b/libraries/src/main/java/com/baeldung/kafka/Tuple.java new file mode 100644 index 0000000000..883de4ba21 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/kafka/Tuple.java @@ -0,0 +1,24 @@ +package com.baeldung.kafka; + +public class Tuple { + + private String key; + private Integer value; + + private Tuple(String key, Integer value) { + this.key = key; + this.value = value; + } + + public static Tuple of(String key, Integer value){ + return new Tuple(key,value); + } + + public String getKey() { + return key; + } + + public Integer getValue() { + return value; + } +} From 91ea35ee387324346156e3711cb6a4e196d3654e Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Sat, 22 Sep 2018 21:15:03 +0400 Subject: [PATCH 09/18] review changes --- .../java/com/baeldung/sort/SortHashMap.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java index f7ea2f655b..38eddc6cf3 100644 --- a/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java +++ b/core-java-collections/src/main/java/com/baeldung/sort/SortHashMap.java @@ -21,12 +21,15 @@ public class SortHashMap { arrayListSortByValue(); arrayListSortByKey(); - treeSetByKey(); - treeSetByValue(); - sortStream(); sortGuava(); + + addDuplicates(); + + treeSetByKey(); + treeSetByValue(); + } private static void sortGuava() { @@ -63,10 +66,7 @@ public class SortHashMap { TreeMap sorted = new TreeMap<>(map); sorted.putAll(map); - for (Map.Entry entry : sorted.entrySet()) { - System.out.println("Key = " + entry.getKey() + - ", Value = " + entry.getValue()); - } + sorted.entrySet().forEach(System.out::println); } @@ -94,4 +94,11 @@ public class SortHashMap { Employee employee4 = new Employee(2L, "George"); map.put(employee4.getName(), employee4); } + + private static void addDuplicates() { + Employee employee5 = new Employee(1L, "Mher"); + map.put(employee5.getName(), employee5); + Employee employee6 = new Employee(22L, "Annie"); + map.put(employee6.getName(), employee6); + } } From 7d4b0d161075501b215952456a63139d040038dc Mon Sep 17 00:00:00 2001 From: Alfonso Lentini Date: Sun, 23 Sep 2018 12:29:23 +0200 Subject: [PATCH 10/18] ScribeJava --- libraries-security/pom.xml | 22 ++++++- .../scribejava/ScribejavaApplication.java | 15 +++++ .../com/baeldung/scribejava/api/MyApi.java | 27 +++++++++ .../controller/GoogleController.java | 49 ++++++++++++++++ .../controller/TwitterController.java | 57 +++++++++++++++++++ .../scribejava/controller/UserController.java | 46 +++++++++++++++ .../scribejava/oauth/AuthServiceConfig.java | 45 +++++++++++++++ .../scribejava/oauth/WebSecurityConfig.java | 53 +++++++++++++++++ .../scribejava/service/GoogleService.java | 31 ++++++++++ .../scribejava/service/MyService.java | 29 ++++++++++ .../scribejava/service/TwitterService.java | 29 ++++++++++ .../src/main/resources/application.properties | 1 + .../ScribejavaApplicationTests.java | 16 ++++++ 13 files changed, 418 insertions(+), 2 deletions(-) create mode 100644 libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java create mode 100644 libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java create mode 100644 libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java create mode 100644 libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java create mode 100644 libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java create mode 100644 libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java create mode 100644 libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java create mode 100644 libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java create mode 100644 libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java create mode 100644 libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java create mode 100644 libraries-security/src/main/resources/application.properties create mode 100644 libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaApplicationTests.java diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index 8f8506172f..0b7cddb885 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -8,12 +8,30 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-boot-1 + 0.0.1-SNAPSHOT + ../parent-boot-1 + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.security.oauth + spring-security-oauth2 + 2.3.3.RELEASE + + + + com.github.scribejava + scribejava-apis + 5.6.0 + + junit junit diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java b/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java new file mode 100644 index 0000000000..bb86c497b0 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.scribejava; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +@SpringBootApplication +public class ScribejavaApplication { + + public static void main(String[] args) { + SpringApplication.run(ScribejavaApplication.class, args); + } + + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java b/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java new file mode 100644 index 0000000000..577e753c07 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java @@ -0,0 +1,27 @@ +package com.baeldung.scribejava.api; + +import com.github.scribejava.core.builder.api.DefaultApi20; + +public class MyApi extends DefaultApi20 { + + public MyApi() { + } + + private static class InstanceHolder { + private static final MyApi INSTANCE = new MyApi(); + } + + public static MyApi instance() { + return InstanceHolder.INSTANCE; + } + + @Override + public String getAccessTokenEndpoint() { + return "http://localhost:8080/oauth/token"; + } + + @Override + protected String getAuthorizationBaseUrl() { + return null; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java new file mode 100644 index 0000000000..ffe4f0cc8a --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java @@ -0,0 +1,49 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.GoogleService; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; + +@RestController +public class GoogleController { + + @Autowired + private GoogleService service; + + + @GetMapping(value ="/me/google") + public void me(HttpServletResponse response){ + String auth = service.getService().getAuthorizationUrl(); + + response.setHeader("Location", auth); + response.setStatus(302); + + } + + @GetMapping(value = "/auth/google") + public String google(@RequestParam String code, HttpServletResponse servletResponse){ + + try { + OAuth2AccessToken token = service.getService().getAccessToken(code); + + OAuthRequest request = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json"); + service.getService().signRequest(token, request); + Response response = service.getService().execute(request); + return response.getBody(); + + }catch (Exception e){ + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java new file mode 100644 index 0000000000..bfcd6d960c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java @@ -0,0 +1,57 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.TwitterService; +import com.github.scribejava.core.model.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Scanner; +import java.util.concurrent.ExecutionException; + +@RestController +public class TwitterController { + + @Autowired + private TwitterService service; + + + @GetMapping(value ="/me/twitter") + public String me(HttpServletResponse servletResponse){ + try { + OAuth1RequestToken requestToken = service.getService().getRequestToken(); + + String auth = service.getService().getAuthorizationUrl(requestToken); + + Runtime runtime = Runtime.getRuntime(); + try { + runtime.exec("rundll32 url.dll,FileProtocolHandler " + auth); + } catch (IOException e) { + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return null; + } + + System.out.println("Insert twitter code:"); + Scanner in = new Scanner(System.in); + + String oauthverifier = in.nextLine(); + + final OAuth1AccessToken accessToken = service.getService().getAccessToken(requestToken,oauthverifier); + + OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json"); + service.getService().signRequest(accessToken, request); + Response response = service.getService().execute(request); + return response.getBody(); + + } catch (IOException | InterruptedException | ExecutionException e) { + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + } + + + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java new file mode 100644 index 0000000000..68a11250de --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java @@ -0,0 +1,46 @@ +package com.baeldung.scribejava.controller; + +import com.baeldung.scribejava.service.MyService; +import com.github.scribejava.core.model.OAuth2AccessToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import java.security.Principal; + +@RestController(value = "/user") +public class UserController { + + @Autowired + private MyService service; + + @GetMapping("/me/myapi") + public String me(@RequestParam String username, @RequestParam String password, HttpServletResponse responsehttp) { + + try { + OAuth2AccessToken token = service.getService().getAccessTokenPasswordGrant(username, password); + + OAuthRequest request = new OAuthRequest(Verb.GET, "http://localhost:8080/me"); + service.getService().signRequest(token, request); + Response response = service.getService().execute(request); + + return response.getBody(); + + } catch (Exception e) { + responsehttp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + + return null; + + } + + @GetMapping("/me") + public Principal user(Principal principal) { + return principal; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java new file mode 100644 index 0000000000..2c7162399b --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java @@ -0,0 +1,45 @@ +package com.baeldung.scribejava.oauth; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; + + +@Configuration +@EnableAuthorizationServer +public class AuthServiceConfig extends AuthorizationServerConfigurerAdapter { + + @Autowired + @Qualifier("authenticationManagerBean") + private AuthenticationManager authenticationManager; + + @Override + public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { + oauthServer.tokenKeyAccess("permitAll()") + .checkTokenAccess("isAuthenticated()"); + } + + @Override + public void configure(ClientDetailsServiceConfigurer clients) throws Exception { + clients.inMemory() + .withClient("baeldung_api_key") + .secret("baeldung_api_secret") + .authorizedGrantTypes("password","refresh_token") + .scopes("read","write").autoApprove(true); + } + + @Override + public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { + endpoints + .authenticationManager(authenticationManager) + .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java new file mode 100644 index 0000000000..7aa51400ea --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.scribejava.oauth; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; + +@Configuration +@EnableResourceServer +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .headers().frameOptions().disable() + .and() + .csrf().disable(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("baeldung") + .password("scribejava") + .roles("USER"); + } + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + + @EnableResourceServer + @Configuration + public class ResourceServerConfig extends ResourceServerConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/user/me").authenticated() + .and() + .csrf().disable(); + } + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java new file mode 100644 index 0000000000..fbcc39763c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java @@ -0,0 +1,31 @@ +package com.baeldung.scribejava.service; + +import com.github.scribejava.apis.GoogleApi20; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth20Service; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +@Component +public class GoogleService { + + private OAuth20Service service; + private final String API_KEY = "api_key"; + private final String API_SECRET = "api_secret"; + private final String SCOPE = "https://www.googleapis.com/auth/userinfo.email"; + private final String CALLBACK = "http://localhost:8080/auth/google"; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .scope(SCOPE) + .callback(CALLBACK) + .build(GoogleApi20.instance()); + } + + + public OAuth20Service getService() { + return service; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java new file mode 100644 index 0000000000..739c82172c --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java @@ -0,0 +1,29 @@ +package com.baeldung.scribejava.service; + +import com.baeldung.scribejava.api.MyApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth20Service; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class MyService { + + private OAuth20Service service; + private final String API_KEY = "baeldung_api_key"; + private final String API_SECRET = "baeldung_api_secret"; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .scope("read write") + .build(MyApi.instance()); + } + + + public OAuth20Service getService() { + return service; + } +} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java new file mode 100644 index 0000000000..df49f74679 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java @@ -0,0 +1,29 @@ +package com.baeldung.scribejava.service; + +import com.github.scribejava.apis.TwitterApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.oauth.OAuth10aService; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class TwitterService { + + private final String API_KEY = "api_key"; + private final String API_SECRET = "api_secret"; + private OAuth10aService service; + + @PostConstruct + private void init(){ + this.service = new ServiceBuilder(API_KEY) + .apiSecret(API_SECRET) + .build(TwitterApi.instance()); + } + + public OAuth10aService getService(){ + return service; + } + + +} diff --git a/libraries-security/src/main/resources/application.properties b/libraries-security/src/main/resources/application.properties new file mode 100644 index 0000000000..71c6176533 --- /dev/null +++ b/libraries-security/src/main/resources/application.properties @@ -0,0 +1 @@ +security.oauth2.resource.filter-order = 3 \ No newline at end of file diff --git a/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaApplicationTests.java b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaApplicationTests.java new file mode 100644 index 0000000000..99e2265d10 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaApplicationTests.java @@ -0,0 +1,16 @@ +package com.baeldung.scribejava; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ScribejavaApplicationTests { + + @Test + public void contextLoads() { + } + +} From b9970c5e3a27eade87c86e2381b132b37387eeb5 Mon Sep 17 00:00:00 2001 From: nguyennamthai Date: Sun, 23 Sep 2018 17:46:26 +0700 Subject: [PATCH 11/18] Bael 2110 (#5286) * Fix a division method mistake * What a Spring bean is * Update * 2nd update --- .../java/com/baeldung/definition/Config.java | 16 ++++++++++++++++ .../baeldung/definition/domain/Address.java | 14 ++++++++++++++ .../baeldung/definition/domain/Company.java | 14 ++++++++++++++ .../definition/SpringBeanIntegrationTest.java | 18 ++++++++++++++++++ 4 files changed, 62 insertions(+) create mode 100644 spring-core/src/main/java/com/baeldung/definition/Config.java create mode 100644 spring-core/src/main/java/com/baeldung/definition/domain/Address.java create mode 100644 spring-core/src/main/java/com/baeldung/definition/domain/Company.java create mode 100644 spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java diff --git a/spring-core/src/main/java/com/baeldung/definition/Config.java b/spring-core/src/main/java/com/baeldung/definition/Config.java new file mode 100644 index 0000000000..126e6259ca --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/Config.java @@ -0,0 +1,16 @@ +package com.baeldung.definition; + +import com.baeldung.definition.domain.Address; +import com.baeldung.definition.domain.Company; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackageClasses = Company.class) +public class Config { + @Bean + public Address getAddress() { + return new Address("High Street", 1000); + } +} diff --git a/spring-core/src/main/java/com/baeldung/definition/domain/Address.java b/spring-core/src/main/java/com/baeldung/definition/domain/Address.java new file mode 100644 index 0000000000..91be18398e --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/domain/Address.java @@ -0,0 +1,14 @@ +package com.baeldung.definition.domain; + +import lombok.Data; + +@Data +public class Address { + private String street; + private int number; + + public Address(String street, int number) { + this.street = street; + this.number = number; + } +} diff --git a/spring-core/src/main/java/com/baeldung/definition/domain/Company.java b/spring-core/src/main/java/com/baeldung/definition/domain/Company.java new file mode 100644 index 0000000000..eabde8afdf --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/definition/domain/Company.java @@ -0,0 +1,14 @@ +package com.baeldung.definition.domain; + +import lombok.Data; +import org.springframework.stereotype.Component; + +@Data +@Component +public class Company { + private Address address; + + public Company(Address address) { + this.address = address; + } +} diff --git a/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java b/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java new file mode 100644 index 0000000000..0057611308 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/definition/SpringBeanIntegrationTest.java @@ -0,0 +1,18 @@ +package com.baeldung.definition; + +import com.baeldung.definition.domain.Company; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.Assert.assertEquals; + +public class SpringBeanIntegrationTest { + @Test + public void whenUsingIoC_thenDependenciesAreInjected() { + ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); + Company company = context.getBean("company", Company.class); + assertEquals("High Street", company.getAddress().getStreet()); + assertEquals(1000, company.getAddress().getNumber()); + } +} From 6ff8919dec39752225fb8ab7a0f91d13165a6cb4 Mon Sep 17 00:00:00 2001 From: Alfonso Lentini Date: Sun, 23 Sep 2018 12:54:26 +0200 Subject: [PATCH 12/18] build fix --- libraries-security/pom.xml | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index 0b7cddb885..75ccf29cd6 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -29,7 +29,7 @@ com.github.scribejava scribejava-apis - 5.6.0 + ${scribejava.version} @@ -41,8 +41,21 @@ + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + 4.12 + 2.0.4.RELEASE + 5.6.0 + From 419b6e66b18b591f709bc740cfffabe3fccaa035 Mon Sep 17 00:00:00 2001 From: Alfonso Lentini Date: Sun, 23 Sep 2018 13:19:48 +0200 Subject: [PATCH 13/18] build fix --- .../com/baeldung/scribejava/api/MyApi.java | 2 +- .../controller/TwitterController.java | 56 +++++++++---------- 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java b/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java index 577e753c07..cf073d3035 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/api/MyApi.java @@ -4,7 +4,7 @@ import com.github.scribejava.core.builder.api.DefaultApi20; public class MyApi extends DefaultApi20 { - public MyApi() { + private MyApi() { } private static class InstanceHolder { diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java index bfcd6d960c..0b8b48220d 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java @@ -20,34 +20,34 @@ public class TwitterController { @GetMapping(value ="/me/twitter") public String me(HttpServletResponse servletResponse){ - try { - OAuth1RequestToken requestToken = service.getService().getRequestToken(); - - String auth = service.getService().getAuthorizationUrl(requestToken); - - Runtime runtime = Runtime.getRuntime(); - try { - runtime.exec("rundll32 url.dll,FileProtocolHandler " + auth); - } catch (IOException e) { - servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return null; - } - - System.out.println("Insert twitter code:"); - Scanner in = new Scanner(System.in); - - String oauthverifier = in.nextLine(); - - final OAuth1AccessToken accessToken = service.getService().getAccessToken(requestToken,oauthverifier); - - OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json"); - service.getService().signRequest(accessToken, request); - Response response = service.getService().execute(request); - return response.getBody(); - - } catch (IOException | InterruptedException | ExecutionException e) { - servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); - } +// try { +// OAuth1RequestToken requestToken = service.getService().getRequestToken(); +// +// String auth = service.getService().getAuthorizationUrl(requestToken); +// +// Runtime runtime = Runtime.getRuntime(); +// try { +// runtime.exec("rundll32 url.dll,FileProtocolHandler " + auth); +// } catch (IOException e) { +// servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); +// return null; +// } +// +// System.out.println("Insert twitter code:"); +// Scanner in = new Scanner(System.in); +// +// String oauthverifier = in.nextLine(); +// +// final OAuth1AccessToken accessToken = service.getService().getAccessToken(requestToken,oauthverifier); +// +// OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json"); +// service.getService().signRequest(accessToken, request); +// Response response = service.getService().execute(request); +// return response.getBody(); +// +// } catch (IOException | InterruptedException | ExecutionException e) { +// servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); +// } return null; } From 98f57fee9d3582eddf786454903b4ad7fb606003 Mon Sep 17 00:00:00 2001 From: Alfonso Lentini Date: Sun, 23 Sep 2018 13:20:39 +0200 Subject: [PATCH 14/18] build fix --- libraries-security/pom.xml | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index 75ccf29cd6..a57f029702 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -41,16 +41,6 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - 4.12 2.0.4.RELEASE From 465c571f1851c0f2f5b28ff3a02a8bacdb322a20 Mon Sep 17 00:00:00 2001 From: Alfonso Lentini Date: Sun, 23 Sep 2018 13:55:39 +0200 Subject: [PATCH 15/18] build fix --- .../controller/TwitterController.java | 56 +++++++++---------- ...tionTests.java => ScribejavaUnitTest.java} | 5 +- 2 files changed, 31 insertions(+), 30 deletions(-) rename libraries-security/src/test/java/com/baeldung/scribejava/{ScribejavaApplicationTests.java => ScribejavaUnitTest.java} (78%) diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java index 0b8b48220d..bfcd6d960c 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java @@ -20,34 +20,34 @@ public class TwitterController { @GetMapping(value ="/me/twitter") public String me(HttpServletResponse servletResponse){ -// try { -// OAuth1RequestToken requestToken = service.getService().getRequestToken(); -// -// String auth = service.getService().getAuthorizationUrl(requestToken); -// -// Runtime runtime = Runtime.getRuntime(); -// try { -// runtime.exec("rundll32 url.dll,FileProtocolHandler " + auth); -// } catch (IOException e) { -// servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); -// return null; -// } -// -// System.out.println("Insert twitter code:"); -// Scanner in = new Scanner(System.in); -// -// String oauthverifier = in.nextLine(); -// -// final OAuth1AccessToken accessToken = service.getService().getAccessToken(requestToken,oauthverifier); -// -// OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json"); -// service.getService().signRequest(accessToken, request); -// Response response = service.getService().execute(request); -// return response.getBody(); -// -// } catch (IOException | InterruptedException | ExecutionException e) { -// servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); -// } + try { + OAuth1RequestToken requestToken = service.getService().getRequestToken(); + + String auth = service.getService().getAuthorizationUrl(requestToken); + + Runtime runtime = Runtime.getRuntime(); + try { + runtime.exec("rundll32 url.dll,FileProtocolHandler " + auth); + } catch (IOException e) { + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return null; + } + + System.out.println("Insert twitter code:"); + Scanner in = new Scanner(System.in); + + String oauthverifier = in.nextLine(); + + final OAuth1AccessToken accessToken = service.getService().getAccessToken(requestToken,oauthverifier); + + OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json"); + service.getService().signRequest(accessToken, request); + Response response = service.getService().execute(request); + return response.getBody(); + + } catch (IOException | InterruptedException | ExecutionException e) { + servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } return null; } diff --git a/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaApplicationTests.java b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java similarity index 78% rename from libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaApplicationTests.java rename to libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java index 99e2265d10..6565a5b085 100644 --- a/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaApplicationTests.java +++ b/libraries-security/src/test/java/com/baeldung/scribejava/ScribejavaUnitTest.java @@ -7,10 +7,11 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class ScribejavaApplicationTests { +public class ScribejavaUnitTest { @Test - public void contextLoads() { + public void contextLoad(){ + } } From 1a8eb6a0efe078eeebbd0a520feb769cd70fda30 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 23 Sep 2018 17:54:41 +0300 Subject: [PATCH 16/18] refactor dao --- .../springbootmvc/jsfapplication/model/TodoDao.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java index d33f5e5da0..96d44474af 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java @@ -14,7 +14,7 @@ import org.springframework.stereotype.Component; public class TodoDao implements Dao { private List todoList = new ArrayList<>(); - + @Override public Optional get(int id) { return Optional.ofNullable(todoList.get(id)); @@ -22,9 +22,9 @@ public class TodoDao implements Dao { @Override public Collection getAll() { - return Collections.unmodifiableCollection(todoList.stream() + return todoList.stream() .filter(Objects::nonNull) - .collect(Collectors.toList())); + .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } @Override From a336320f5294a9663049cdfb8849b65df71c4ca9 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 23 Sep 2018 18:32:13 +0300 Subject: [PATCH 17/18] Update README.md --- spring-security-mvc-socket/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-mvc-socket/README.md b/spring-security-mvc-socket/README.md index e99555e7fa..3daf9199e6 100644 --- a/spring-security-mvc-socket/README.md +++ b/spring-security-mvc-socket/README.md @@ -7,4 +7,4 @@ To login, use credentials from the data.sql file in src/main/resource, eg: user/ ### Relevant Articles: - [Intro to Security and WebSockets](http://www.baeldung.com/spring-security-websockets) -- [Spring WebSockets: Specific User Chat](http://www.baeldung.com/spring-websocket-specific-user-chat) \ No newline at end of file +- [Spring WebSockets: Specific User Chat](https://www.baeldung.com/spring-websockets-send-message-to-user) From f599419181b74f8cba9e683e4d82c865acac141b Mon Sep 17 00:00:00 2001 From: vizsoro Date: Sun, 23 Sep 2018 20:25:06 +0200 Subject: [PATCH 18/18] using collectingAndThen --- .../springbootmvc/jsfapplication/model/TodoDao.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java index d33f5e5da0..96d44474af 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/jsfapplication/model/TodoDao.java @@ -14,7 +14,7 @@ import org.springframework.stereotype.Component; public class TodoDao implements Dao { private List todoList = new ArrayList<>(); - + @Override public Optional get(int id) { return Optional.ofNullable(todoList.get(id)); @@ -22,9 +22,9 @@ public class TodoDao implements Dao { @Override public Collection getAll() { - return Collections.unmodifiableCollection(todoList.stream() + return todoList.stream() .filter(Objects::nonNull) - .collect(Collectors.toList())); + .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } @Override