Merge branch 'master' into thombergs-patch-31-1

This commit is contained in:
Tom Hombergs
2018-10-08 20:28:07 +02:00
committed by GitHub
65 changed files with 1898 additions and 190 deletions
+7 -26
View File
@@ -2,41 +2,22 @@
The "REST with Spring" Classes
==============================
Here's the Master Class of REST With Spring (price changes permanently next Friday): <br/>
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material): <br/>
**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
And here's the Master Class of Learn Spring Security: <br/>
**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
Spring Tutorials
Java and Spring Tutorials
================
This project is **a collection of small and focused tutorials** each covering a single and well defined area of development.
Most of the tutorial projects are focused on the `Spring Framework` (and `Spring Security`).
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Securiyt.
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
Building the project
====================
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
Working with the code in Eclipse
================================
Any IDE can be used to work with the projects, but if you're using Eclipse, consider the following.
- import the included **formatter** in Eclipse:
`https://github.com/eugenp/tutorials/tree/master/eclipse`
CI - Jenkins
================================
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**
### Relevant Articles:
================================
- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
- [Apache Maven Tutorial](http://www.baeldung.com/maven)
- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)
@@ -98,7 +98,7 @@ public class FindKthLargest {
private int randomPartition(Integer arr[], int left, int right) {
int n = right - left + 1;
int pivot = (int) (Math.random()) % n;
int pivot = (int) (Math.random() * n);
swap(arr, left + pivot, right);
return partition(arr, left, right);
}
@@ -1,16 +1,18 @@
package com.baeldung.java8;
import com.baeldung.java8.entity.Human;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.java8.entity.Human;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
public class Java8SortUnitTest {
@@ -111,5 +113,22 @@ public class Java8SortUnitTest {
humans.sort(Comparator.comparing(Human::getName));
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<String> letters = Lists.newArrayList("B", "A", "C");
final List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
Assert.assertThat(sortedLetters.get(0), equalTo("A"));
}
@Test
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
}
}
+1
View File
@@ -48,6 +48,7 @@
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
+5
View File
@@ -68,6 +68,11 @@
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>0.6.5</version>
</dependency>
</dependencies>
@@ -0,0 +1,105 @@
package com.baeldung.map.java_8;
import com.baeldung.sort.Employee;
import one.util.streamex.EntryStream;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MergeMaps {
private static Map<String, Employee> map1 = new HashMap<>();
private static Map<String, Employee> map2 = new HashMap<>();
public static void main(String[] args) {
initialize();
mergeFunction();
streamConcat();
streamOf();
streamEx();
streamMerge();
}
private static void streamMerge() {
Map<String, Employee> map3 = map2.entrySet()
.stream()
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> new Employee(v1.getId(), v2.getName()),
() -> new HashMap<>(map1)
)
);
System.out.println(map3);
}
private static void streamEx() {
Map<String, Employee> map3 = EntryStream.of(map1)
.append(EntryStream.of(map2))
.toMap((e1, e2) -> e1);
System.out.println(map3);
}
private static void streamOf() {
Map<String, Employee> map3 = Stream.of(map1, map2)
.flatMap(map -> map.entrySet().stream())
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> new Employee(v1.getId(), v2.getName())
)
);
map3.entrySet().forEach(System.out::println);
}
private static void streamConcat() {
Map<String, Employee> result = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(value1, value2) -> new Employee(value2.getId(), value1.getName())
));
result.entrySet().forEach(System.out::println);
}
private static void mergeFunction() {
Map<String, Employee> map3 = new HashMap<>(map1);
map2.forEach(
(key, value) -> map3.merge(key, value, (v1, v2) ->
new Employee(v1.getId(), v2.getName()))
);
map3.entrySet().forEach(System.out::println);
}
private static void initialize() {
Employee employee1 = new Employee(1L, "Henry");
map1.put(employee1.getName(), employee1);
Employee employee2 = new Employee(22L, "Annie");
map1.put(employee2.getName(), employee2);
Employee employee3 = new Employee(8L, "John");
map1.put(employee3.getName(), employee3);
Employee employee4 = new Employee(2L, "George");
map2.put(employee4.getName(), employee4);
Employee employee5 = new Employee(3L, "Henry");
map2.put(employee5.getName(), employee5);
}
}
@@ -0,0 +1,44 @@
package com.baeldung.java.map;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.MultiMap;
import org.apache.commons.collections4.MultiMapUtils;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.map.MultiValueMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
public class KeyCheckTest {
@Test
public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
Map<String, String> map = Collections.singletonMap("key", "value");
assertTrue(map.containsKey("key"));
assertFalse(map.containsKey("missing"));
}
@Test
public void whenKeyHasNullValue_thenGetStillWorks() {
Map<String, String> map = Collections.singletonMap("nothing", null);
assertTrue(map.containsKey("nothing"));
assertNull(map.get("nothing"));
}
}
@@ -0,0 +1,48 @@
package com.baeldung.stream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class OutputStreamExamples {
public void fileOutputStreamByteSequence(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes);
}
}
public void fileOutputStreamByteSubSequence(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes, 6, 5);
}
}
public void fileOutputStreamByteSingle(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes[6]);
}
}
public void bufferedOutputStream(String file, String... data) throws IOException {
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
for (String s : data) {
out.write(s.getBytes());
out.write(" ".getBytes());
}
}
}
public void outputStreamWriter(String file, String data) throws IOException {
try (OutputStream out = new FileOutputStream(file); Writer writer = new OutputStreamWriter(out, "UTF-8")) {
writer.write(data);
}
}
}
@@ -0,0 +1,76 @@
package com.baeldung.stream;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
public class OutputStreamExamplesTest {
StringBuilder filePath = new StringBuilder();
@Before
public void init() {
filePath.append("src");
filePath.append(File.separator);
filePath.append("test");
filePath.append(File.separator);
filePath.append("resources");
filePath.append(File.separator);
filePath.append("output_file.txt");
}
@Test
public void givenOutputStream_whenWriteSingleByteCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.fileOutputStreamByteSingle(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenOutputStream_whenWriteByteSequenceCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.fileOutputStreamByteSequence(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenOutputStream_whenWriteByteSubSequenceCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.fileOutputStreamByteSubSequence(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenBufferedOutputStream_whenCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.bufferedOutputStream(filePath.toString(), "Hello", "World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenOutputStreamWriter_whenCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.outputStreamWriter(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
}
-2
View File
@@ -25,7 +25,6 @@
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
- [Spring Security – Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers)
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
@@ -37,7 +36,6 @@
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
- [Guide to UUID in JAVA](http://www.baeldung.com/guide-to-uuid-in-java)
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
@@ -0,0 +1,121 @@
package com.baeldung.kotlin
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
class StructuralJumpUnitTest {
@Test
fun givenLoop_whenBreak_thenComplete() {
var value = ""
for (i in "hello_world") {
if (i == '_')
break
value += i.toString()
}
assertEquals("hello", value)
}
@Test
fun givenLoop_whenBreakWithLabel_thenComplete() {
var value = ""
outer_loop@ for (i in 'a'..'d') {
for (j in 1..3) {
value += "" + i + j
if (i == 'b' && j == 1)
break@outer_loop
}
}
assertEquals("a1a2a3b1", value)
}
@Test
fun givenLoop_whenContinue_thenComplete() {
var result = ""
for (i in "hello_world") {
if (i == '_')
continue
result += i
}
assertEquals("helloworld", result)
}
@Test
fun givenLoop_whenContinueWithLabel_thenComplete() {
var result = ""
outer_loop@ for (i in 'a'..'c') {
for (j in 1..3) {
if (i == 'b')
continue@outer_loop
result += "" + i + j
}
}
assertEquals("a1a2a3c1c2c3", result)
}
@Test
fun givenLambda_whenReturn_thenComplete() {
var result = returnInLambda();
assertEquals("hello", result)
}
private fun returnInLambda(): String {
var result = ""
"hello_world".forEach {
// non-local return directly to the caller
if (it == '_') return result
result += it.toString()
}
//this line won't be reached
return result;
}
@Test
fun givenLambda_whenReturnWithExplicitLabel_thenComplete() {
var result = ""
"hello_world".forEach lit@{
if (it == '_') {
// local return to the caller of the lambda, i.e. the forEach loop
return@lit
}
result += it.toString()
}
assertEquals("helloworld", result)
}
@Test
fun givenLambda_whenReturnWithImplicitLabel_thenComplete() {
var result = ""
"hello_world".forEach {
if (it == '_') {
// local return to the caller of the lambda, i.e. the forEach loop
return@forEach
}
result += it.toString()
}
assertEquals("helloworld", result)
}
@Test
fun givenAnonymousFunction_return_thenComplete() {
var result = ""
"hello_world".forEach(fun(element) {
// local return to the caller of the anonymous fun, i.e. the forEach loop
if (element == '_') return
result += element.toString()
})
assertEquals("helloworld", result)
}
@Test
fun givenAnonymousFunction_returnToLabel_thenComplete() {
var result = ""
run loop@{
"hello_world".forEach {
// non-local return from the lambda passed to run
if (it == '_') return@loop
result += it.toString()
}
}
assertEquals("hello", result)
}
}
+1
View File
@@ -14,4 +14,5 @@
- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa)
- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking)
- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle)
- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class)
- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column)
@@ -0,0 +1,47 @@
package com.baeldung.hibernate.namingstrategy;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
public class CustomPhysicalNamingStrategy implements PhysicalNamingStrategy {
@Override
public Identifier toPhysicalCatalogName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
return convertToSnakeCase(identifier);
}
@Override
public Identifier toPhysicalColumnName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
return convertToSnakeCase(identifier);
}
@Override
public Identifier toPhysicalSchemaName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
return convertToSnakeCase(identifier);
}
@Override
public Identifier toPhysicalSequenceName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
return convertToSnakeCase(identifier);
}
@Override
public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
return convertToSnakeCase(identifier);
}
private Identifier convertToSnakeCase(final Identifier identifier) {
if (identifier == null) {
return identifier;
}
final String regex = "([a-z])([A-Z])";
final String replacement = "$1_$2";
final String newName = identifier.getText()
.replaceAll(regex, replacement)
.toLowerCase();
return Identifier.toIdentifier(newName);
}
}
@@ -0,0 +1,56 @@
package com.baeldung.hibernate.namingstrategy;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Customers")
public class Customer {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
@Column(name = "email")
private String emailAddress;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
@@ -0,0 +1,75 @@
package com.baeldung.hibernate.namingstrategy;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class NamingStrategyLiveTest {
private Session session;
@Before
public void init() {
try {
Configuration configuration = new Configuration();
Properties properties = new Properties();
properties.load(Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("hibernate-namingstrategy.properties"));
configuration.setProperties(properties);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
.build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(Customer.class);
SessionFactory factory = metadataSources.buildMetadata()
.buildSessionFactory();
session = factory.openSession();
} catch (HibernateException | IOException e) {
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
}
}
@After
public void close() {
if (session != null)
session.close();
}
@Test
public void testCustomPhysicalNamingStrategy() {
Customer customer = new Customer();
customer.setFirstName("first name");
customer.setLastName("last name");
customer.setEmailAddress("[email protected]");
session.beginTransaction();
Long id = (Long) session.save(customer);
session.flush();
session.clear();
Object[] result = (Object[]) session.createNativeQuery("select c.first_name, c.last_name, c.email from customers c where c.id = :id")
.setParameter("id", id)
.getSingleResult();
}
}
@@ -0,0 +1,10 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.physical_naming_strategy=com.baeldung.hibernate.namingstrategy.CustomPhysicalNamingStrategy
hibernate.implicit_naming_strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
+1 -1
View File
@@ -118,7 +118,7 @@
<properties>
<!-- marshalling -->
<jackson.version>2.9.6</jackson.version>
<jackson.version>2.9.7</jackson.version>
<!-- util -->
<commons-lang3.version>3.8</commons-lang3.version>
<joda-time.version>2.10</joda-time.version>
@@ -0,0 +1,5 @@
package com.baeldung.jackson.xmlToJson;
public enum Color {
PINK, BLUE, YELLOW, RED;
}
@@ -0,0 +1,42 @@
package com.baeldung.jackson.xmlToJson;
public class Flower {
private String name;
private Color color;
private Integer petals;
public Flower() { }
public Flower(String name, Color color, Integer petals) {
this.name = name;
this.color = color;
this.petals = petals;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Integer getPetals() {
return petals;
}
public void setPetals(Integer petals) {
this.petals = petals;
}
}
@@ -0,0 +1,56 @@
package com.baeldung.jackson.xmlToJson;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.IOException;
public class XmlToJsonUnitTest {
@Test
public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() {
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
try {
XmlMapper xmlMapper = new XmlMapper();
Flower poppy = xmlMapper.readValue(flowerXML, Flower.class);
assertEquals(poppy.getName(), "Poppy");
assertEquals(poppy.getColor(), Color.RED);
assertEquals(poppy.getPetals(), new Integer(9));
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(poppy);
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}");
System.out.println(json);
} catch(IOException e) {
e.printStackTrace();
}
}
@Test
public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() {
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
try {
XmlMapper xmlMapper = new XmlMapper();
JsonNode node = xmlMapper.readTree(flowerXML.getBytes());
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node);
System.out.println(json);
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}");
} catch(IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,20 @@
package com.baeldung.maths;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
public class MathSinUnitTest {
@Test
public void givenAnAngleInDegrees_whenUsingToRadians_thenResultIsInRadians() {
double angleInDegrees = 30;
double sinForDegrees = Math.sin(Math.toRadians(angleInDegrees)); // 0.5
double thirtyDegreesInRadians = 1/6 * Math.PI;
double sinForRadians = Math.sin(thirtyDegreesInRadians); // 0.5
assertTrue(sinForDegrees == sinForRadians);
}
}
+1
View File
@@ -28,6 +28,7 @@
- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex)
- [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string)
- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty)
- [Get Substring from String in Java](https://www.baeldung.com/java-substring)
- [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string)
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
+1
View File
@@ -1,3 +1,4 @@
- [Jersey Filters and Interceptors](http://www.baeldung.com/jersey-filters-interceptors)
- [Jersey MVC Support](https://www.baeldung.com/jersey-mvc)
- [Bean Validation in Jersey](https://www.baeldung.com/jersey-bean-validation)
- [Set a Response Body in JAX-RS](https://www.baeldung.com/jax-rs-response)
+1
View File
@@ -11,3 +11,4 @@
- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data)
- [Guide to JMapper](https://www.baeldung.com/jmapper)
- [A Guide to Apache Crunch](https://www.baeldung.com/apache-crunch)
- [Building a Data Pipeline with Flink and Kafka](https://www.baeldung.com/kafka-flink-data-pipeline)
+3
View File
@@ -0,0 +1,3 @@
To run the maven-polyglot-json-app successfully, you first have to build the maven-polyglot-json-extension module using: mvn clean install.
Related Articles:
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<extensions>
<extension>
<groupId>com.baeldung.maven.polyglot</groupId>
<artifactId>maven-polyglot-json-extension</artifactId>
<version>1.0-SNAPSHOT</version>
</extension>
</extensions>
@@ -0,0 +1,34 @@
{
"modelVersion": "4.0.0",
"groupId": "com.baeldung.maven.polyglot",
"artifactId": "maven-polyglot-json-app",
"version": "1.0-SNAPSHOT",
"name": "Json Maven Polyglot",
"parent": {
"groupId": "org.springframework.boot",
"artifactId": "spring-boot-starter-parent",
"version": "2.0.5.RELEASE",
"relativePath": null
},
"properties": {
"project.build.sourceEncoding": "UTF-8",
"project.reporting.outputEncoding": "UTF-8",
"maven.compiler.source": "1.8",
"maven.compiler.target": "1.8",
"java.version": "1.8"
},
"dependencies": [
{
"groupId": "org.springframework.boot",
"artifactId": "spring-boot-starter-web"
}
],
"build": {
"plugins": [
{
"groupId": "org.springframework.boot",
"artifactId": "spring-boot-maven-plugin"
}
]
}
}
@@ -0,0 +1,19 @@
package com.baeldung.maven.polyglot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
@SpringBootApplication
public class MavenPolyglotApplication {
public static void main(String[] args) {
SpringApplication.run(MavenPolyglotApplication.class, args);
}
@GetMapping("/")
public String home(){
return "Hello JSON Maven Model !";
}
}
@@ -0,0 +1,109 @@
{
"modules": [],
"distributionManagement": null,
"properties": {
"project.reporting.outputEncoding": "UTF-8",
"java.version": "1.8",
"maven.compiler.source": "1.8",
"project.build.sourceEncoding": "UTF-8",
"maven.compiler.target": "1.8"
},
"dependencyManagement": null,
"dependencies": [
{
"groupId": "org.springframework.boot",
"artifactId": "spring-boot-starter-web",
"version": null,
"type": "jar",
"classifier": null,
"scope": null,
"systemPath": null,
"exclusions": [],
"optional": null,
"managementKey": "org.springframework.boot:spring-boot-starter-web:jar"
}
],
"repositories": [],
"pluginRepositories": [],
"reports": null,
"reporting": null,
"modelVersion": "4.0.0",
"parent": {
"groupId": "org.springframework.boot",
"artifactId": "spring-boot-starter-parent",
"version": "2.0.5.RELEASE",
"relativePath": "",
"id": "org.springframework.boot:spring-boot-starter-parent:pom:2.0.5.RELEASE"
},
"groupId": "com.demo.polyglot",
"artifactId": "maven-polyglot-app",
"version": "1.0.1",
"packaging": "jar",
"name": "Json Maven Polyglot",
"description": null,
"url": null,
"inceptionYear": null,
"organization": null,
"licenses": [],
"developers": [],
"contributors": [],
"mailingLists": [],
"prerequisites": null,
"scm": null,
"issueManagement": null,
"ciManagement": null,
"build": {
"plugins": [
{
"inherited": null,
"configuration": null,
"inheritanceApplied": true,
"groupId": "org.liquibase",
"artifactId": "liquibase-maven-plugin",
"version": "3.0.5",
"extensions": null,
"executions": [],
"dependencies": [],
"goals": null,
"key": "org.liquibase:liquibase-maven-plugin",
"id": "org.liquibase:liquibase-maven-plugin:3.0.5",
"executionsAsMap": {}
}
],
"pluginManagement": null,
"defaultGoal": null,
"resources": [],
"testResources": [],
"directory": null,
"finalName": null,
"filters": [],
"sourceDirectory": null,
"scriptSourceDirectory": null,
"testSourceDirectory": null,
"outputDirectory": null,
"testOutputDirectory": null,
"extensions": [],
"pluginsAsMap": {
"org.liquibase:liquibase-maven-plugin": {
"inherited": null,
"configuration": null,
"inheritanceApplied": true,
"groupId": "org.liquibase",
"artifactId": "liquibase-maven-plugin",
"version": "3.0.5",
"extensions": null,
"executions": [],
"dependencies": [],
"goals": null,
"key": "org.liquibase:liquibase-maven-plugin",
"id": "org.liquibase:liquibase-maven-plugin:3.0.5",
"executionsAsMap": {}
}
}
},
"profiles": [],
"modelEncoding": "UTF-8",
"pomFile": null,
"id": "com.demo.polyglot:maven-polyglot-app:jar:1.0.1",
"projectDirectory": null
}
@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.maven.polyglot</groupId>
<artifactId>maven-polyglot-json-extension</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<version>3.5.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-component-metadata</artifactId>
<version>1.7.1</version>
<executions>
<execution>
<goals>
<goal>generate-metadata</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

Some files were not shown because too many files have changed in this diff Show More