Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-12669
This commit is contained in:
@@ -66,3 +66,10 @@ jmeter/src/main/resources/*-JMeter.csv
|
||||
**/nb-configuration.xml
|
||||
core-scala/.cache-main
|
||||
core-scala/.cache-tests
|
||||
|
||||
|
||||
persistence-modules/hibernate5/transaction.log
|
||||
apache-avro/src/main/java/com/baeldung/avro/model/
|
||||
jta/transaction-logs/
|
||||
software-security/sql-injection-samples/derby.log
|
||||
spring-soap/src/main/java/com/baeldung/springsoap/gen/
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung
|
||||
|
||||
class Car implements VehicleTrait {}
|
||||
@@ -22,7 +22,7 @@ trait UserTrait implements Human {
|
||||
msg
|
||||
}
|
||||
|
||||
def whoAmI() {
|
||||
def self() {
|
||||
return this
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung
|
||||
|
||||
trait VehicleTrait extends WheelTrait {
|
||||
|
||||
String showWheels() {
|
||||
return "Num of Wheels $noOfWheels"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung
|
||||
|
||||
trait WheelTrait {
|
||||
|
||||
int noOfWheels
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.map
|
||||
|
||||
import static org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class MapUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingEach_thenMapIsIterated() {
|
||||
def map = [
|
||||
'FF0000' : 'Red',
|
||||
'00FF00' : 'Lime',
|
||||
'0000FF' : 'Blue',
|
||||
'FFFF00' : 'Yellow'
|
||||
]
|
||||
|
||||
map.each { println "Hex Code: $it.key = Color Name: $it.value" }
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachWithEntry_thenMapIsIterated() {
|
||||
def map = [
|
||||
'E6E6FA' : 'Lavender',
|
||||
'D8BFD8' : 'Thistle',
|
||||
'DDA0DD' : 'Plum',
|
||||
]
|
||||
|
||||
map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" }
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachWithKeyAndValue_thenMapIsIterated() {
|
||||
def map = [
|
||||
'000000' : 'Black',
|
||||
'FFFFFF' : 'White',
|
||||
'808080' : 'Gray'
|
||||
]
|
||||
|
||||
map.each { key, val ->
|
||||
println "Hex Code: $key = Color Name $val"
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachWithIndexAndEntry_thenMapIsIterated() {
|
||||
def map = [
|
||||
'800080' : 'Purple',
|
||||
'4B0082' : 'Indigo',
|
||||
'6A5ACD' : 'Slate Blue'
|
||||
]
|
||||
|
||||
map.eachWithIndex { entry, index ->
|
||||
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
|
||||
println "$indent Hex Code: $entry.key = Color Name: $entry.value"
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() {
|
||||
def map = [
|
||||
'FFA07A' : 'Light Salmon',
|
||||
'FF7F50' : 'Coral',
|
||||
'FF6347' : 'Tomato',
|
||||
'FF4500' : 'Orange Red'
|
||||
]
|
||||
|
||||
map.eachWithIndex { key, val, index ->
|
||||
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
|
||||
println "$indent Hex Code: $key = Color Name: $val"
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingForLoop_thenMapIsIterated() {
|
||||
def map = [
|
||||
'2E8B57' : 'Seagreen',
|
||||
'228B22' : 'Forest Green',
|
||||
'008000' : 'Green'
|
||||
]
|
||||
|
||||
for (entry in map) {
|
||||
println "Hex Code: $entry.key = Color Name: $entry.value"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ class TraitsUnitTest extends Specification {
|
||||
|
||||
def 'Should return employee instance when using Employee.whoAmI method' () {
|
||||
when:
|
||||
def emp = employee.whoAmI()
|
||||
def emp = employee.self()
|
||||
then:
|
||||
emp
|
||||
emp instanceof Employee
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.multireleaseapp;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class App {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(App.class);
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String dateToCheck = args[0];
|
||||
boolean isLeapYear = DateHelper.checkIfLeapYear(dateToCheck);
|
||||
logger.info("Date given " + dateToCheck + " is leap year: " + isLeapYear);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.multireleaseapp;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class DateHelper {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DateHelper.class);
|
||||
|
||||
public static boolean checkIfLeapYear(String dateStr) throws Exception {
|
||||
logger.info("Checking for leap year using Java 1 calendar API");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(dateStr));
|
||||
int year = cal.get(Calendar.YEAR);
|
||||
return (new GregorianCalendar()).isLeapYear(year);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.multireleaseapp;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class DateHelper {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DateHelper.class);
|
||||
|
||||
public static boolean checkIfLeapYear(String dateStr) throws Exception {
|
||||
logger.info("Checking for leap year using Java 9 Date Api");
|
||||
return LocalDate.parse(dateStr)
|
||||
.isLeapYear();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -27,3 +27,4 @@
|
||||
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
|
||||
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
|
||||
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
|
||||
- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)
|
||||
|
||||
@@ -52,6 +52,17 @@
|
||||
<artifactId>colt</artifactId>
|
||||
<version>${colt.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.list.primitive;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import gnu.trove.list.array.TIntArrayList;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.SingleShotTime)
|
||||
@OutputTimeUnit(TimeUnit.MILLISECONDS)
|
||||
@Measurement(batchSize = 100000, iterations = 10)
|
||||
@Warmup(batchSize = 100000, iterations = 10)
|
||||
@State(Scope.Thread)
|
||||
public class PrimitivesListPerformance {
|
||||
|
||||
private List<Integer> arrayList = new ArrayList<>();
|
||||
private TIntArrayList tList = new TIntArrayList();
|
||||
private cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList();
|
||||
private IntArrayList fastUtilList = new IntArrayList();
|
||||
|
||||
private int getValue = 10;
|
||||
|
||||
@Benchmark
|
||||
public boolean addArrayList() {
|
||||
return arrayList.add(getValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean addTroveIntList() {
|
||||
return tList.add(getValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void addColtIntList() {
|
||||
coltList.add(getValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean addFastUtilIntList() {
|
||||
return fastUtilList.add(getValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int getArrayList() {
|
||||
return arrayList.get(getValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int getTroveIntList() {
|
||||
return tList.get(getValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int getColtIntList() {
|
||||
return coltList.get(getValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int getFastUtilIntList() {
|
||||
return fastUtilList.getInt(getValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean containsArrayList() {
|
||||
return arrayList.contains(getValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean containsTroveIntList() {
|
||||
return tList.contains(getValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean containsColtIntList() {
|
||||
return coltList.contains(getValue);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean containsFastUtilIntList() {
|
||||
return fastUtilList.contains(getValue);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(PrimitivesListPerformance.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -17,7 +18,6 @@ import org.slf4j.LoggerFactory;
|
||||
public class WriteCsvFileExampleUnitTest {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WriteCsvFileExampleUnitTest.class);
|
||||
|
||||
private static final String CSV_FILE_NAME = "src/test/resources/exampleOutput.csv";
|
||||
private WriteCsvFileExample csvExample;
|
||||
|
||||
@Before
|
||||
@@ -65,12 +65,12 @@ public class WriteCsvFileExampleUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDataArray_whenConvertToCSV_thenOutputCreated() {
|
||||
public void givenDataArray_whenConvertToCSV_thenOutputCreated() throws IOException {
|
||||
List<String[]> dataLines = new ArrayList<String[]>();
|
||||
dataLines.add(new String[] { "John", "Doe", "38", "Comment Data\nAnother line of comment data" });
|
||||
dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" });
|
||||
|
||||
File csvOutputFile = new File(CSV_FILE_NAME);
|
||||
File csvOutputFile = File.createTempFile("exampleOutput", ".csv");
|
||||
try (PrintWriter pw = new PrintWriter(csvOutputFile)) {
|
||||
dataLines.stream()
|
||||
.map(csvExample::convertToCSV)
|
||||
@@ -80,5 +80,6 @@ public class WriteCsvFileExampleUnitTest {
|
||||
}
|
||||
|
||||
assertTrue(csvOutputFile.exists());
|
||||
csvOutputFile.deleteOnExit();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
John,Doe,38,Comment Data Another line of comment data
|
||||
Jane,"Doe, Jr.",19,"She said ""I'm being quoted"""
|
||||
|
@@ -0,0 +1,33 @@
|
||||
package org.baeldung.gson.conversion;
|
||||
|
||||
import com.google.gson.*;
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class JsonObjectConversionsUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingJsonParser_thenConvertToJsonObject() throws Exception {
|
||||
// Example 1: Using JsonParser
|
||||
String json = "{ \"name\": \"Baeldung\", \"java\": true }";
|
||||
|
||||
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
|
||||
|
||||
Assert.assertTrue(jsonObject.isJsonObject());
|
||||
Assert.assertTrue(jsonObject.get("name").getAsString().equals("Baeldung"));
|
||||
Assert.assertTrue(jsonObject.get("java").getAsBoolean() == true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingGsonInstanceFromJson_thenConvertToJsonObject() throws Exception {
|
||||
// Example 2: Using fromJson
|
||||
String json = "{ \"name\": \"Baeldung\", \"java\": true }";
|
||||
|
||||
JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class);
|
||||
|
||||
Assert.assertTrue(convertedObject.isJsonObject());
|
||||
Assert.assertTrue(convertedObject.get("name").getAsString().equals("Baeldung"));
|
||||
Assert.assertTrue(convertedObject.get("java").getAsBoolean() == true);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.jackson.dtos;
|
||||
|
||||
public class Address {
|
||||
|
||||
String streetNumber;
|
||||
String streetName;
|
||||
String city;
|
||||
|
||||
public String getStreetNumber() {
|
||||
return streetNumber;
|
||||
}
|
||||
|
||||
public void setStreetNumber(String streetNumber) {
|
||||
this.streetNumber = streetNumber;
|
||||
}
|
||||
|
||||
public String getStreetName() {
|
||||
return streetName;
|
||||
}
|
||||
|
||||
public void setStreetName(String streetName) {
|
||||
this.streetName = streetName;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.jackson.dtos;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
|
||||
|
||||
@JacksonXmlRootElement(localName = "person")
|
||||
public final class Person {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private List<String> phoneNumbers = new ArrayList<>();
|
||||
private List<Address> address = new ArrayList<>();
|
||||
|
||||
public List<Address> getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(List<Address> address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public List<String> getPhoneNumbers() {
|
||||
return phoneNumbers;
|
||||
}
|
||||
|
||||
public void setPhoneNumbers(List<String> phoneNumbers) {
|
||||
this.phoneNumbers = phoneNumbers;
|
||||
}
|
||||
|
||||
}
|
||||
+69
-11
@@ -2,19 +2,25 @@ package com.baeldung.jackson.xml;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.dtos.Address;
|
||||
import com.baeldung.jackson.dtos.Person;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public class XMLSerializeDeserializeUnitTest {
|
||||
|
||||
@@ -49,24 +55,76 @@ public class XMLSerializeDeserializeUnitTest {
|
||||
assertTrue(value.getX() == 1 && value.getY() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test
|
||||
public void whenJavaGotFromXmlStrWithCapitalElem_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
SimpleBeanForCapitalizedFields value = xmlMapper.
|
||||
readValue("<SimpleBeanForCapitalizedFields><X>1</X><y>2</y></SimpleBeanForCapitalizedFields>",
|
||||
SimpleBeanForCapitalizedFields.class);
|
||||
SimpleBeanForCapitalizedFields value = xmlMapper.readValue("<SimpleBeanForCapitalizedFields><X>1</X><y>2</y></SimpleBeanForCapitalizedFields>", SimpleBeanForCapitalizedFields.class);
|
||||
assertTrue(value.getX() == 1 && value.getY() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaSerializedToXmlFileWithCapitalizedField_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"),
|
||||
new SimpleBeanForCapitalizedFields());
|
||||
xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"), new SimpleBeanForCapitalizedFields());
|
||||
File file = new File("target/simple_bean_capitalized.xml");
|
||||
assertNotNull(file);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaDeserializedFromXmlFile_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
|
||||
String xml = "<person><firstName>Rohan</firstName><lastName>Daye</lastName><phoneNumbers><phoneNumbers>9911034731</phoneNumbers><phoneNumbers>9911033478</phoneNumbers></phoneNumbers><address><address><streetNumber>1</streetNumber><streetName>Name1</streetName><city>City1</city></address><address><streetNumber>2</streetNumber><streetName>Name2</streetName><city>City2</city></address></address></person>";
|
||||
Person value = xmlMapper.readValue(xml, Person.class);
|
||||
|
||||
assertTrue(value.getAddress()
|
||||
.get(0)
|
||||
.getCity()
|
||||
.equalsIgnoreCase("city1")
|
||||
&& value.getAddress()
|
||||
.get(1)
|
||||
.getCity()
|
||||
.equalsIgnoreCase("city2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaSerializedToXmlFile_thenSuccess() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
|
||||
String expectedXml = "<person><firstName>Rohan</firstName><lastName>Daye</lastName><phoneNumbers><phoneNumbers>9911034731</phoneNumbers><phoneNumbers>9911033478</phoneNumbers></phoneNumbers><address><address><streetNumber>1</streetNumber><streetName>Name1</streetName><city>City1</city></address><address><streetNumber>2</streetNumber><streetName>Name2</streetName><city>City2</city></address></address></person>";
|
||||
|
||||
Person person = new Person();
|
||||
|
||||
person.setFirstName("Rohan");
|
||||
person.setLastName("Daye");
|
||||
|
||||
List<String> ph = new ArrayList<>();
|
||||
ph.add("9911034731");
|
||||
ph.add("9911033478");
|
||||
person.setPhoneNumbers(ph);
|
||||
|
||||
List<Address> addresses = new ArrayList<>();
|
||||
|
||||
Address address1 = new Address();
|
||||
address1.setStreetNumber("1");
|
||||
address1.setStreetName("Name1");
|
||||
address1.setCity("City1");
|
||||
|
||||
Address address2 = new Address();
|
||||
address2.setStreetNumber("2");
|
||||
address2.setStreetName("Name2");
|
||||
address2.setCity("City2");
|
||||
|
||||
addresses.add(address1);
|
||||
addresses.add(address2);
|
||||
|
||||
person.setAddress(addresses);
|
||||
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
xmlMapper.writeValue(byteArrayOutputStream, person);
|
||||
assertEquals(expectedXml, byteArrayOutputStream.toString());
|
||||
}
|
||||
|
||||
private static String inputStreamToString(InputStream is) throws IOException {
|
||||
BufferedReader br;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
@@ -103,10 +161,10 @@ class SimpleBean {
|
||||
|
||||
}
|
||||
|
||||
class SimpleBeanForCapitalizedFields {
|
||||
@JsonProperty("X")
|
||||
private int x = 1;
|
||||
private int y = 2;
|
||||
class SimpleBeanForCapitalizedFields {
|
||||
@JsonProperty("X")
|
||||
private int x = 1;
|
||||
private int y = 2;
|
||||
|
||||
public int getX() {
|
||||
return x;
|
||||
|
||||
+9
-4
@@ -9,8 +9,10 @@ import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.collections4.MultiMapUtils;
|
||||
import org.apache.commons.collections4.MultiSet;
|
||||
import org.apache.commons.collections4.MultiValuedMap;
|
||||
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
|
||||
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
|
||||
@@ -65,25 +67,28 @@ public class MultiValuedMapUnitTest {
|
||||
@Test
|
||||
public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() {
|
||||
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
|
||||
|
||||
map.put("fruits", "apple");
|
||||
map.put("fruits", "orange");
|
||||
map.put("vehicles", "car");
|
||||
map.put("vehicles", "bike");
|
||||
|
||||
assertThat(((Collection<String>) map.keys())).contains("fruits", "vehicles");
|
||||
MultiSet<String> keys = map.keys();
|
||||
|
||||
assertThat((keys)).contains("fruits", "vehicles");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() {
|
||||
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
|
||||
|
||||
map.put("fruits", "apple");
|
||||
map.put("fruits", "orange");
|
||||
map.put("vehicles", "car");
|
||||
map.put("vehicles", "bike");
|
||||
|
||||
assertThat((Collection<String>) map.keySet()).contains("fruits", "vehicles");
|
||||
Set<String> keys = map.keySet();
|
||||
|
||||
assertThat(keys).contains("fruits", "vehicles");
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,12 @@
|
||||
<version>${commons-collections4.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
@@ -86,6 +92,7 @@
|
||||
<jackson-databind.version>2.9.7</jackson-databind.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<javax.version>1.1.2</javax.version>
|
||||
<assertj-core.version>3.11.1</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.jsonobject.iterate;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
public class JSONObjectIterator {
|
||||
|
||||
private Map<String, Object> keyValuePairs;
|
||||
|
||||
public JSONObjectIterator() {
|
||||
keyValuePairs = new HashMap<>();
|
||||
}
|
||||
|
||||
public void handleValue(String key, Object value) {
|
||||
if (value instanceof JSONArray) {
|
||||
handleJSONArray(key, (JSONArray) value);
|
||||
} else if (value instanceof JSONObject) {
|
||||
handleJSONObject((JSONObject) value);
|
||||
}
|
||||
keyValuePairs.put(key, value);
|
||||
}
|
||||
|
||||
public void handleJSONObject(JSONObject jsonObject) {
|
||||
Iterator<String> jsonObjectIterator = jsonObject.keys();
|
||||
jsonObjectIterator.forEachRemaining(key -> {
|
||||
Object value = jsonObject.get(key);
|
||||
handleValue(key, value);
|
||||
});
|
||||
}
|
||||
|
||||
public void handleJSONArray(String key, JSONArray jsonArray) {
|
||||
Iterator<Object> jsonArrayIterator = jsonArray.iterator();
|
||||
jsonArrayIterator.forEachRemaining(element -> {
|
||||
handleValue(key, element);
|
||||
});
|
||||
}
|
||||
|
||||
public Map<String, Object> getKeyValuePairs() {
|
||||
return keyValuePairs;
|
||||
}
|
||||
|
||||
public void setKeyValuePairs(Map<String, Object> keyValuePairs) {
|
||||
this.keyValuePairs = keyValuePairs;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.jsonobject.iterate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JSONObjectIteratorUnitTest {
|
||||
|
||||
private JSONObjectIterator jsonObjectIterator = new JSONObjectIterator();
|
||||
|
||||
@Test
|
||||
public void givenJSONObject_whenIterating_thenGetKeyValuePairs() {
|
||||
JSONObject jsonObject = getJsonObject();
|
||||
|
||||
jsonObjectIterator.handleJSONObject(jsonObject);
|
||||
|
||||
Map<String, Object> keyValuePairs = jsonObjectIterator.getKeyValuePairs();
|
||||
assertThat(keyValuePairs.get("rType")).isEqualTo("Regular");
|
||||
assertThat(keyValuePairs.get("rId")).isEqualTo("1001");
|
||||
assertThat(keyValuePairs.get("cType")).isEqualTo("Chocolate");
|
||||
assertThat(keyValuePairs.get("cId")).isEqualTo("1002");
|
||||
assertThat(keyValuePairs.get("bType")).isEqualTo("BlueBerry");
|
||||
assertThat(keyValuePairs.get("bId")).isEqualTo("1003");
|
||||
assertThat(keyValuePairs.get("name")).isEqualTo("Cake");
|
||||
assertThat(keyValuePairs.get("cakeId")).isEqualTo("0001");
|
||||
assertThat(keyValuePairs.get("type")).isEqualTo("donut");
|
||||
assertThat(keyValuePairs.get("Type")).isEqualTo("Maple");
|
||||
assertThat(keyValuePairs.get("tId")).isEqualTo("5001");
|
||||
assertThat(keyValuePairs.get("batters")
|
||||
.toString()).isEqualTo("[{\"rType\":\"Regular\",\"rId\":\"1001\"},{\"cType\":\"Chocolate\",\"cId\":\"1002\"},{\"bType\":\"BlueBerry\",\"bId\":\"1003\"}]");
|
||||
assertThat(keyValuePairs.get("cakeShapes")
|
||||
.toString()).isEqualTo("[\"square\",\"circle\",\"heart\"]");
|
||||
assertThat(keyValuePairs.get("topping")
|
||||
.toString()).isEqualTo("{\"Type\":\"Maple\",\"tId\":\"5001\"}");
|
||||
}
|
||||
|
||||
private JSONObject getJsonObject() {
|
||||
JSONObject cake = new JSONObject();
|
||||
cake.put("cakeId", "0001");
|
||||
cake.put("type", "donut");
|
||||
cake.put("name", "Cake");
|
||||
|
||||
JSONArray batters = new JSONArray();
|
||||
JSONObject regular = new JSONObject();
|
||||
regular.put("rId", "1001");
|
||||
regular.put("rType", "Regular");
|
||||
batters.put(regular);
|
||||
JSONObject chocolate = new JSONObject();
|
||||
chocolate.put("cId", "1002");
|
||||
chocolate.put("cType", "Chocolate");
|
||||
batters.put(chocolate);
|
||||
JSONObject blueberry = new JSONObject();
|
||||
blueberry.put("bId", "1003");
|
||||
blueberry.put("bType", "BlueBerry");
|
||||
batters.put(blueberry);
|
||||
|
||||
JSONArray cakeShapes = new JSONArray();
|
||||
cakeShapes.put("square");
|
||||
cakeShapes.put("circle");
|
||||
cakeShapes.put("heart");
|
||||
|
||||
cake.put("cakeShapes", cakeShapes);
|
||||
|
||||
cake.put("batters", batters);
|
||||
|
||||
JSONObject topping = new JSONObject();
|
||||
topping.put("tId", "5001");
|
||||
topping.put("Type", "Maple");
|
||||
|
||||
cake.put("topping", topping);
|
||||
|
||||
return cake;
|
||||
}
|
||||
|
||||
}
|
||||
+911
-902
File diff suppressed because it is too large
Load Diff
@@ -6,7 +6,7 @@ import org.derive4j.Make;
|
||||
|
||||
@Data(value = @Derive(
|
||||
inClass = "{ClassName}Impl",
|
||||
make = {Make.lazyConstructor, Make.constructors}
|
||||
make = {Make.lazyConstructor, Make.constructors, Make.getters}
|
||||
))
|
||||
public interface LazyRequest {
|
||||
interface Cases<R>{
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.reflections;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Date;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.reflections.Reflections;
|
||||
import org.reflections.scanners.MethodAnnotationsScanner;
|
||||
import org.reflections.scanners.MethodParameterScanner;
|
||||
import org.reflections.scanners.ResourcesScanner;
|
||||
import org.reflections.scanners.Scanner;
|
||||
import org.reflections.scanners.SubTypesScanner;
|
||||
import org.reflections.util.ClasspathHelper;
|
||||
import org.reflections.util.ConfigurationBuilder;
|
||||
|
||||
public class ReflectionsApp {
|
||||
|
||||
public Set<Class<? extends Scanner>> getReflectionsSubTypes() {
|
||||
Reflections reflections = new Reflections("org.reflections");
|
||||
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
|
||||
return scannersSet;
|
||||
}
|
||||
|
||||
public Set<Class<?>> getJDKFunctinalInterfaces() {
|
||||
Reflections reflections = new Reflections("java.util.function");
|
||||
Set<Class<?>> typesSet = reflections.getTypesAnnotatedWith(FunctionalInterface.class);
|
||||
return typesSet;
|
||||
}
|
||||
|
||||
public Set<Method> getDateDeprecatedMethods() {
|
||||
Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
|
||||
Set<Method> deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class);
|
||||
return deprecatedMethodsSet;
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public Set<Constructor> getDateDeprecatedConstructors() {
|
||||
Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
|
||||
Set<Constructor> constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class);
|
||||
return constructorsSet;
|
||||
}
|
||||
|
||||
public Set<Method> getMethodsWithDateParam() {
|
||||
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
|
||||
Set<Method> methodsSet = reflections.getMethodsMatchParams(Date.class);
|
||||
return methodsSet;
|
||||
}
|
||||
|
||||
public Set<Method> getMethodsWithVoidReturn() {
|
||||
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
|
||||
Set<Method> methodsSet = reflections.getMethodsReturn(void.class);
|
||||
return methodsSet;
|
||||
}
|
||||
|
||||
public Set<String> getPomXmlPaths() {
|
||||
Reflections reflections = new Reflections(new ResourcesScanner());
|
||||
Set<String> resourcesSet = reflections.getResources(Pattern.compile(".*pom\\.xml"));
|
||||
return resourcesSet;
|
||||
}
|
||||
|
||||
public Set<Class<? extends Scanner>> getReflectionsSubTypesUsingBuilder() {
|
||||
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections"))
|
||||
.setScanners(new SubTypesScanner()));
|
||||
|
||||
Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
|
||||
return scannersSet;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.reflections;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ReflectionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTypeThenGetAllSubTypes() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getReflectionsSubTypes()
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTypeAndUsingBuilderThenGetAllSubTypes() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getReflectionsSubTypesUsingBuilder()
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnnotationThenGetAllAnnotatedMethods() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getDateDeprecatedMethods()
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnnotationThenGetAllAnnotatedConstructors() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getDateDeprecatedConstructors()
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParamTypeThenGetAllMethods() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getMethodsWithDateParam()
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReturnTypeThenGetAllMethods() {
|
||||
ReflectionsApp reflectionsApp = new ReflectionsApp();
|
||||
assertFalse(reflectionsApp.getMethodsWithVoidReturn()
|
||||
.isEmpty());
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -1 +1,2 @@
|
||||
/output-resources
|
||||
/output-resources
|
||||
/.idea/
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user