From 66eb5d7270fc9d7eac0a13a0a76c6612bea2d713 Mon Sep 17 00:00:00 2001 From: sameira Date: Thu, 18 Feb 2016 22:48:42 +0530 Subject: [PATCH 01/47] Added publish subscribe example using redis --- spring-data-redis/pom.xml | 124 +++++++++--------- .../spring/data/redis/config/RedisConfig.java | 31 ++++- .../data/redis/queue/MessagePublisher.java | 7 + .../redis/queue/RedisMessagePublisher.java | 28 ++++ .../redis/queue/RedisMessageSubscriber.java | 19 +++ .../data/redis/repo/StudentRepository.java | 4 +- .../data/redis/RedisMessageListenerTest.java | 51 +++++++ 7 files changed, 198 insertions(+), 66 deletions(-) create mode 100644 spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java create mode 100644 spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java create mode 100644 spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java create mode 100644 spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java diff --git a/spring-data-redis/pom.xml b/spring-data-redis/pom.xml index 98da69934c..3f9eb705f4 100644 --- a/spring-data-redis/pom.xml +++ b/spring-data-redis/pom.xml @@ -1,76 +1,76 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - org.baeldung - sprint-data-redis - 0.0.1-SNAPSHOT - jar + org.baeldung + sprint-data-redis + 0.0.1-SNAPSHOT + jar - - UTF-8 - 4.2.2.RELEASE - 1.6.2.RELEASE - 0.8.0 - + + UTF-8 + 4.2.2.RELEASE + 1.6.2.RELEASE + 0.8.0 + - - - org.springframework.data - spring-data-redis - ${spring-data-redis} - + + + org.springframework.data + spring-data-redis + ${spring-data-redis} + - - cglib - cglib-nodep - 2.2 - + + cglib + cglib-nodep + 2.2 + - - log4j - log4j - 1.2.16 - + + log4j + log4j + 1.2.16 + - - redis.clients - jedis - 2.5.1 - jar - + + redis.clients + jedis + 2.5.1 + jar + - - org.springframework - spring-core - ${spring.version} - + + org.springframework + spring-core + ${spring.version} + - - org.springframework - spring-context - ${spring.version} - + + org.springframework + spring-context + ${spring.version} + - - junit - junit - 4.12 - test - + + junit + junit + 4.12 + test + - - org.springframework - spring-test - ${spring.version} - test - + + org.springframework + spring-test + ${spring.version} + test + - - com.lordofthejars - nosqlunit-redis - ${nosqlunit.version} - + + com.lordofthejars + nosqlunit-redis + ${nosqlunit.version} + - + diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java index a7e75a438a..0b64afe56c 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java @@ -1,10 +1,16 @@ package org.baeldung.spring.data.redis.config; +import org.baeldung.spring.data.redis.queue.RedisMessageSubscriber; +import org.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import org.baeldung.spring.data.redis.queue.MessagePublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.listener.ChannelTopic; +import org.springframework.data.redis.listener.RedisMessageListenerContainer; +import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; @Configuration @ComponentScan("org.baeldung.spring.data.redis") @@ -17,8 +23,31 @@ public class RedisConfig { @Bean public RedisTemplate redisTemplate() { - final RedisTemplate< String, Object> template = new RedisTemplate(); + final RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(jedisConnectionFactory()); return template; } + + @Bean + MessageListenerAdapter messageListener() { + return new MessageListenerAdapter(new RedisMessageSubscriber()); + } + + @Bean + RedisMessageListenerContainer redisContainer() { + final RedisMessageListenerContainer container = new RedisMessageListenerContainer(); + container.setConnectionFactory(jedisConnectionFactory()); + container.addMessageListener(messageListener(), topic()); + return container; + } + + @Bean + MessagePublisher redisPublisher() { + return new RedisMessagePublisher(redisTemplate(), topic()); + } + + @Bean + ChannelTopic topic() { + return new ChannelTopic("pubsub:queue"); + } } diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java new file mode 100644 index 0000000000..a05f524f60 --- /dev/null +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java @@ -0,0 +1,7 @@ +package org.baeldung.spring.data.redis.queue; + + +public interface MessagePublisher { + + void publish(String message); +} diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java new file mode 100644 index 0000000000..4eb7f69cdb --- /dev/null +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java @@ -0,0 +1,28 @@ +package org.baeldung.spring.data.redis.queue; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.listener.ChannelTopic; +import org.springframework.stereotype.Service; + +@Service +public class RedisMessagePublisher implements MessagePublisher { + + @Autowired + private RedisTemplate redisTemplate; + @Autowired + private ChannelTopic topic; + + public RedisMessagePublisher() { + } + + public RedisMessagePublisher(RedisTemplate redisTemplate, + ChannelTopic topic) { + this.redisTemplate = redisTemplate; + this.topic = topic; + } + + public void publish(String message) { + redisTemplate.convertAndSend(topic.getTopic(), message); + } +} diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java new file mode 100644 index 0000000000..4bc60849fb --- /dev/null +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java @@ -0,0 +1,19 @@ +package org.baeldung.spring.data.redis.queue; + +import org.springframework.data.redis.connection.Message; +import org.springframework.data.redis.connection.MessageListener; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class RedisMessageSubscriber implements MessageListener { + + public static List messageList = new ArrayList(); + + public void onMessage(final Message message, final byte[] pattern) { + messageList.add(message.toString()); + System.out.println("Message received: " + message.toString()); + } +} \ No newline at end of file diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java index 9e5502f8e0..2a1f6afcce 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java @@ -1,15 +1,13 @@ package org.baeldung.spring.data.redis.repo; import org.baeldung.spring.data.redis.model.Student; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Component; import java.util.Map; public interface StudentRepository { void saveStudent(Student person); - + void updateStudent(Student student); Student findStudent(String id); diff --git a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java new file mode 100644 index 0000000000..7308424a90 --- /dev/null +++ b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java @@ -0,0 +1,51 @@ +package org.baeldung.spring.data.redis; + +import org.baeldung.spring.data.redis.config.RedisConfig; +import org.baeldung.spring.data.redis.queue.RedisMessageSubscriber; +import org.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.UUID; + +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RedisConfig.class) +public class RedisMessageListenerTest { + + + @Autowired + private RedisMessagePublisher redisMessagePublisher; + + @Test + public void testOnMessage() throws Exception { + String message = "Message " + UUID.randomUUID(); + redisMessagePublisher.publish(message); + Thread.sleep(100); + assertTrue(RedisMessageSubscriber.messageList.get(0).contains(message)); + } + + public void testOnPMessage() throws Exception { + + } + + public void testOnSubscribe() throws Exception { + + } + + public void testOnUnsubscribe() throws Exception { + + } + + public void testOnPUnsubscribe() throws Exception { + + } + + public void testOnPSubscribe() throws Exception { + + } +} \ No newline at end of file From a304aa9860f60268bdbf33f2ff8fa428fd642f2f Mon Sep 17 00:00:00 2001 From: sameira Date: Thu, 18 Feb 2016 22:49:50 +0530 Subject: [PATCH 02/47] Refined the test case --- .../data/redis/RedisMessageListenerTest.java | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java index 7308424a90..19612e0029 100644 --- a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java +++ b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java @@ -28,24 +28,4 @@ public class RedisMessageListenerTest { Thread.sleep(100); assertTrue(RedisMessageSubscriber.messageList.get(0).contains(message)); } - - public void testOnPMessage() throws Exception { - - } - - public void testOnSubscribe() throws Exception { - - } - - public void testOnUnsubscribe() throws Exception { - - } - - public void testOnPUnsubscribe() throws Exception { - - } - - public void testOnPSubscribe() throws Exception { - - } } \ No newline at end of file From 2ccdd4ecbb16184a03ed095df8a020748b3a325b Mon Sep 17 00:00:00 2001 From: sameira Date: Thu, 18 Feb 2016 22:51:35 +0530 Subject: [PATCH 03/47] Refined the test case --- .../baeldung/spring/data/redis/queue/MessagePublisher.java | 2 +- .../spring/data/redis/queue/RedisMessagePublisher.java | 6 +++--- .../spring/data/redis/RedisMessageListenerTest.java | 1 - 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java index a05f524f60..e1f2e3d4b2 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java @@ -3,5 +3,5 @@ package org.baeldung.spring.data.redis.queue; public interface MessagePublisher { - void publish(String message); + void publish(final String message); } diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java index 4eb7f69cdb..58e789daab 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java +++ b/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java @@ -16,13 +16,13 @@ public class RedisMessagePublisher implements MessagePublisher { public RedisMessagePublisher() { } - public RedisMessagePublisher(RedisTemplate redisTemplate, - ChannelTopic topic) { + public RedisMessagePublisher(final RedisTemplate redisTemplate, + final ChannelTopic topic) { this.redisTemplate = redisTemplate; this.topic = topic; } - public void publish(String message) { + public void publish(final String message) { redisTemplate.convertAndSend(topic.getTopic(), message); } } diff --git a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java index 19612e0029..f355e7f63a 100644 --- a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java +++ b/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java @@ -17,7 +17,6 @@ import static org.junit.Assert.assertTrue; @ContextConfiguration(classes = RedisConfig.class) public class RedisMessageListenerTest { - @Autowired private RedisMessagePublisher redisMessagePublisher; From a6057698e146829474a68a7eb223b88c71415bf5 Mon Sep 17 00:00:00 2001 From: ankur-singhal Date: Tue, 1 Mar 2016 15:21:06 +0530 Subject: [PATCH 04/47] XStream - Object to xml XStream - Object to xml --- xstream-introduction/.classpath | 15 +++++ xstream-introduction/.project | 14 +++++ xstream-introduction/pom.xml | 30 ++++++++++ .../initializer/SimpleXstreamInitializer.java | 19 +++++++ .../org/baeldung/pojo/AddressDetails.java | 40 ++++++++++++++ .../org/baeldung/pojo/ContactDetails.java | 28 ++++++++++ .../main/java/org/baeldung/pojo/Customer.java | 55 +++++++++++++++++++ .../baeldung/pojo/CustomerAddressDetails.java | 50 +++++++++++++++++ .../org/baeldung/pojo/CustomerPortfolio.java | 20 +++++++ .../org/baeldung/utility/MyDateConverter.java | 40 ++++++++++++++ .../utility/MySingleValueConverter.java | 29 ++++++++++ .../utility/SimpleDataGeneration.java | 37 +++++++++++++ .../src/main/resources/log4j.properties | 16 ++++++ .../utility/XStreamSimpleXmlTest.java | 46 ++++++++++++++++ 14 files changed, 439 insertions(+) create mode 100644 xstream-introduction/.classpath create mode 100644 xstream-introduction/.project create mode 100644 xstream-introduction/pom.xml create mode 100644 xstream-introduction/src/main/java/org/baeldung/initializer/SimpleXstreamInitializer.java create mode 100644 xstream-introduction/src/main/java/org/baeldung/pojo/AddressDetails.java create mode 100644 xstream-introduction/src/main/java/org/baeldung/pojo/ContactDetails.java create mode 100644 xstream-introduction/src/main/java/org/baeldung/pojo/Customer.java create mode 100644 xstream-introduction/src/main/java/org/baeldung/pojo/CustomerAddressDetails.java create mode 100644 xstream-introduction/src/main/java/org/baeldung/pojo/CustomerPortfolio.java create mode 100644 xstream-introduction/src/main/java/org/baeldung/utility/MyDateConverter.java create mode 100644 xstream-introduction/src/main/java/org/baeldung/utility/MySingleValueConverter.java create mode 100644 xstream-introduction/src/main/java/org/baeldung/utility/SimpleDataGeneration.java create mode 100644 xstream-introduction/src/main/resources/log4j.properties create mode 100644 xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java diff --git a/xstream-introduction/.classpath b/xstream-introduction/.classpath new file mode 100644 index 0000000000..138df490af --- /dev/null +++ b/xstream-introduction/.classpath @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/xstream-introduction/.project b/xstream-introduction/.project new file mode 100644 index 0000000000..cebf3c9cfa --- /dev/null +++ b/xstream-introduction/.project @@ -0,0 +1,14 @@ + + + xstream-introduction + An Introduction To XStream. NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. + + + + org.eclipse.jdt.core.javabuilder + + + + org.eclipse.jdt.core.javanature + + \ No newline at end of file diff --git a/xstream-introduction/pom.xml b/xstream-introduction/pom.xml new file mode 100644 index 0000000000..2f0f26d6f2 --- /dev/null +++ b/xstream-introduction/pom.xml @@ -0,0 +1,30 @@ + + 4.0.0 + org.baeldung + xstream-introduction + 0.0.1-SNAPSHOT + xstream-introduction + An Introduction To XStream + + + + com.thoughtworks.xstream + xstream + 1.4.5 + + + + junit + junit + 4.12 + + + + log4j + log4j + 1.2.17 + + + + \ No newline at end of file diff --git a/xstream-introduction/src/main/java/org/baeldung/initializer/SimpleXstreamInitializer.java b/xstream-introduction/src/main/java/org/baeldung/initializer/SimpleXstreamInitializer.java new file mode 100644 index 0000000000..c96392daf5 --- /dev/null +++ b/xstream-introduction/src/main/java/org/baeldung/initializer/SimpleXstreamInitializer.java @@ -0,0 +1,19 @@ +package org.baeldung.initializer; + +import com.thoughtworks.xstream.XStream; + +public class SimpleXstreamInitializer { + + private static XStream xtreamInstance; + + public static XStream getXstreamInstance() { + if (xtreamInstance == null) { + synchronized (SimpleXstreamInitializer.class) { + if (xtreamInstance == null) { + xtreamInstance = new XStream(); + } + } + } + return xtreamInstance; + } +} \ No newline at end of file diff --git a/xstream-introduction/src/main/java/org/baeldung/pojo/AddressDetails.java b/xstream-introduction/src/main/java/org/baeldung/pojo/AddressDetails.java new file mode 100644 index 0000000000..16930cb8ab --- /dev/null +++ b/xstream-introduction/src/main/java/org/baeldung/pojo/AddressDetails.java @@ -0,0 +1,40 @@ +package org.baeldung.pojo; + +import java.util.List; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("AddressDetails") +public class AddressDetails { + + private String address; + + private String zipcode; + + private List contactDetails; + + public String getZipcode() { + return zipcode; + } + + public void setZipcode(String zipcode) { + this.zipcode = zipcode; + } + + public List getContactDetails() { + return contactDetails; + } + + public void setContactDetails(List contactDetails) { + this.contactDetails = contactDetails; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + +} diff --git a/xstream-introduction/src/main/java/org/baeldung/pojo/ContactDetails.java b/xstream-introduction/src/main/java/org/baeldung/pojo/ContactDetails.java new file mode 100644 index 0000000000..1cb353414b --- /dev/null +++ b/xstream-introduction/src/main/java/org/baeldung/pojo/ContactDetails.java @@ -0,0 +1,28 @@ +package org.baeldung.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("ContactDetails") +public class ContactDetails { + + private String mobile; + + private String landline; + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getLandline() { + return landline; + } + + public void setLandline(String landline) { + this.landline = landline; + } + +} diff --git a/xstream-introduction/src/main/java/org/baeldung/pojo/Customer.java b/xstream-introduction/src/main/java/org/baeldung/pojo/Customer.java new file mode 100644 index 0000000000..aeb6e0aaf3 --- /dev/null +++ b/xstream-introduction/src/main/java/org/baeldung/pojo/Customer.java @@ -0,0 +1,55 @@ +package org.baeldung.pojo; + +import java.util.Date; +import java.util.List; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamImplicit; +import com.thoughtworks.xstream.annotations.XStreamOmitField; + +@XStreamAlias("customer") +public class Customer { + + @XStreamOmitField + private String firstName; + + private String lastName; + + private Date dob; + + @XStreamImplicit + private List contactDetailsList; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + public List getContactDetailsList() { + return contactDetailsList; + } + + public void setContactDetailsList(List contactDetailsList) { + this.contactDetailsList = contactDetailsList; + } + +} diff --git a/xstream-introduction/src/main/java/org/baeldung/pojo/CustomerAddressDetails.java b/xstream-introduction/src/main/java/org/baeldung/pojo/CustomerAddressDetails.java new file mode 100644 index 0000000000..e4ce5ae5cd --- /dev/null +++ b/xstream-introduction/src/main/java/org/baeldung/pojo/CustomerAddressDetails.java @@ -0,0 +1,50 @@ +package org.baeldung.pojo; + +import java.util.List; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("CustomerAddressDetails") +public class CustomerAddressDetails { + + private List addressDetails; + + private String firstName; + + private String lastName; + + private int age; + + 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 int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + + public List getAddressDetails() { + return addressDetails; + } + + public void setAddressDetails(List addressDetails) { + this.addressDetails = addressDetails; + } +} diff --git a/xstream-introduction/src/main/java/org/baeldung/pojo/CustomerPortfolio.java b/xstream-introduction/src/main/java/org/baeldung/pojo/CustomerPortfolio.java new file mode 100644 index 0000000000..cc65128650 --- /dev/null +++ b/xstream-introduction/src/main/java/org/baeldung/pojo/CustomerPortfolio.java @@ -0,0 +1,20 @@ +package org.baeldung.pojo; + +import java.util.List; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("CustomerPortfolio") +public class CustomerPortfolio { + + private List customerAddressDetailsList; + + public List getCustomerAddressDetailsList() { + return customerAddressDetailsList; + } + + public void setCustomerAddressDetailsList(List customerAddressDetailsList) { + this.customerAddressDetailsList = customerAddressDetailsList; + } + +} diff --git a/xstream-introduction/src/main/java/org/baeldung/utility/MyDateConverter.java b/xstream-introduction/src/main/java/org/baeldung/utility/MyDateConverter.java new file mode 100644 index 0000000000..a11b58bd12 --- /dev/null +++ b/xstream-introduction/src/main/java/org/baeldung/utility/MyDateConverter.java @@ -0,0 +1,40 @@ +package org.baeldung.utility; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.GregorianCalendar; + +import com.thoughtworks.xstream.converters.ConversionException; +import com.thoughtworks.xstream.converters.Converter; +import com.thoughtworks.xstream.converters.MarshallingContext; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import com.thoughtworks.xstream.io.HierarchicalStreamWriter; + +public class MyDateConverter implements Converter { + + private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); + + @Override + public boolean canConvert(Class clazz) { + return Date.class.isAssignableFrom(clazz); + } + + @Override + public void marshal(Object value , HierarchicalStreamWriter writer , MarshallingContext arg2) { + Date date = (Date) value; + writer.setValue(formatter.format(date)); + } + + @Override + public Object unmarshal(HierarchicalStreamReader reader , UnmarshallingContext arg1) { + GregorianCalendar calendar = new GregorianCalendar(); + try { + calendar.setTime(formatter.parse(reader.getValue())); + } catch (ParseException e) { + throw new ConversionException(e.getMessage() , e); + } + return calendar; + } +} diff --git a/xstream-introduction/src/main/java/org/baeldung/utility/MySingleValueConverter.java b/xstream-introduction/src/main/java/org/baeldung/utility/MySingleValueConverter.java new file mode 100644 index 0000000000..0cabc4fe03 --- /dev/null +++ b/xstream-introduction/src/main/java/org/baeldung/utility/MySingleValueConverter.java @@ -0,0 +1,29 @@ +package org.baeldung.utility; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.baeldung.pojo.Customer; + +import com.thoughtworks.xstream.converters.SingleValueConverter; + +public class MySingleValueConverter implements SingleValueConverter { + + @Override + public boolean canConvert(Class clazz) { + return Customer.class.isAssignableFrom(clazz); + } + + @Override + public Object fromString(String arg0) { + return null; + } + + @Override + public String toString(Object obj) { + SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); + Date date = ((Customer) obj).getDob(); + return ((Customer) obj).getFirstName() + "," + ((Customer) obj).getLastName() + "," + formatter.format(date); + } + +} diff --git a/xstream-introduction/src/main/java/org/baeldung/utility/SimpleDataGeneration.java b/xstream-introduction/src/main/java/org/baeldung/utility/SimpleDataGeneration.java new file mode 100644 index 0000000000..e6a97e5ea6 --- /dev/null +++ b/xstream-introduction/src/main/java/org/baeldung/utility/SimpleDataGeneration.java @@ -0,0 +1,37 @@ +package org.baeldung.utility; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +import org.baeldung.pojo.ContactDetails; +import org.baeldung.pojo.Customer; + +public class SimpleDataGeneration { + + public static Customer generateData() { + Customer customer = new Customer(); + Calendar cal = Calendar.getInstance(); + cal.set(1986 , 01 , 14); + customer.setDob(cal.getTime()); + customer.setFirstName("Xstream"); + customer.setLastName("Java"); + + List contactDetailsList = new ArrayList(); + + ContactDetails contactDetails1 = new ContactDetails(); + contactDetails1.setLandline("0124-2460311"); + contactDetails1.setMobile("6673543265"); + + ContactDetails contactDetails2 = new ContactDetails(); + contactDetails2.setLandline("0120-223312"); + contactDetails2.setMobile("4676543565"); + + contactDetailsList.add(contactDetails1); + contactDetailsList.add(contactDetails2); + + customer.setContactDetailsList(contactDetailsList); + return customer; + } + +} diff --git a/xstream-introduction/src/main/resources/log4j.properties b/xstream-introduction/src/main/resources/log4j.properties new file mode 100644 index 0000000000..9cdafc6bdb --- /dev/null +++ b/xstream-introduction/src/main/resources/log4j.properties @@ -0,0 +1,16 @@ +# Root logger option +log4j.rootLogger=DEBUG, file + +# Redirect log messages to console +# log4j.appender.stdout=org.apache.log4j.ConsoleAppender +# log4j.appender.stdout.Target=System.out +# log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n + +# Redirect log messages to a log file, support file rolling. +log4j.appender.file=org.apache.log4j.RollingFileAppender +log4j.appender.file.File=D:\\Test\\xstream-application.log +log4j.appender.file.MaxFileSize=5MB +log4j.appender.file.MaxBackupIndex=10 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java b/xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java new file mode 100644 index 0000000000..489960d6ca --- /dev/null +++ b/xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java @@ -0,0 +1,46 @@ +package org.baeldung.utility; + +import org.baeldung.initializer.SimpleXstreamInitializer; +import org.baeldung.pojo.AddressDetails; +import org.baeldung.pojo.ContactDetails; +import org.baeldung.pojo.Customer; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.thoughtworks.xstream.XStream; + +public class XStreamSimpleXmlTest { + + private Customer customer = null; + private String dataXml = null; + private XStream xtream = null; + + @Before + public void dataSetup() { + customer = SimpleDataGeneration.generateData(); + xtream = SimpleXstreamInitializer.getXstreamInstance(); + xtream.processAnnotations(Customer.class); + xtream.processAnnotations(AddressDetails.class); + xtream.processAnnotations(ContactDetails.class); + xtream.omitField(Customer.class , "firstName"); + xtream.registerConverter(new MyDateConverter()); + //xtream.registerConverter(new MySingleValueConverter()); + xtream.aliasField("fn", Customer.class, "firstName"); + + dataXml = xtream.toXML(customer); + System.out.println(dataXml); + } + + @Test + public void convertDataToXml() { + Assert.assertNotNull(dataXml); + } + + @Test + public void convertXmlToObject() { + customer = (Customer) xtream.fromXML(dataXml); + Assert.assertNotNull(customer); + } + +} From bd2afce4d643721af142995f1a8da67b5a3734a0 Mon Sep 17 00:00:00 2001 From: ankur-singhal Date: Tue, 1 Mar 2016 18:37:46 +0530 Subject: [PATCH 05/47] XStream - Object to xml XStream - Object to xml --- .../initializer/SimpleXstreamInitializer.java | 10 +++++----- .../utility/SimpleDataGeneration.java | 2 +- .../utility/XStreamSimpleXmlTest.java | 20 +++++++++---------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/xstream-introduction/src/main/java/org/baeldung/initializer/SimpleXstreamInitializer.java b/xstream-introduction/src/main/java/org/baeldung/initializer/SimpleXstreamInitializer.java index c96392daf5..59912539ca 100644 --- a/xstream-introduction/src/main/java/org/baeldung/initializer/SimpleXstreamInitializer.java +++ b/xstream-introduction/src/main/java/org/baeldung/initializer/SimpleXstreamInitializer.java @@ -4,16 +4,16 @@ import com.thoughtworks.xstream.XStream; public class SimpleXstreamInitializer { - private static XStream xtreamInstance; + private static XStream xstreamInstance; public static XStream getXstreamInstance() { - if (xtreamInstance == null) { + if (xstreamInstance == null) { synchronized (SimpleXstreamInitializer.class) { - if (xtreamInstance == null) { - xtreamInstance = new XStream(); + if (xstreamInstance == null) { + xstreamInstance = new XStream(); } } } - return xtreamInstance; + return xstreamInstance; } } \ No newline at end of file diff --git a/xstream-introduction/src/main/java/org/baeldung/utility/SimpleDataGeneration.java b/xstream-introduction/src/main/java/org/baeldung/utility/SimpleDataGeneration.java index e6a97e5ea6..2b2a7a8bb8 100644 --- a/xstream-introduction/src/main/java/org/baeldung/utility/SimpleDataGeneration.java +++ b/xstream-introduction/src/main/java/org/baeldung/utility/SimpleDataGeneration.java @@ -14,7 +14,7 @@ public class SimpleDataGeneration { Calendar cal = Calendar.getInstance(); cal.set(1986 , 01 , 14); customer.setDob(cal.getTime()); - customer.setFirstName("Xstream"); + customer.setFirstName("XStream"); customer.setLastName("Java"); List contactDetailsList = new ArrayList(); diff --git a/xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java b/xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java index 489960d6ca..57d0bd2b55 100644 --- a/xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java +++ b/xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java @@ -14,21 +14,21 @@ public class XStreamSimpleXmlTest { private Customer customer = null; private String dataXml = null; - private XStream xtream = null; + private XStream xstream = null; @Before public void dataSetup() { customer = SimpleDataGeneration.generateData(); - xtream = SimpleXstreamInitializer.getXstreamInstance(); - xtream.processAnnotations(Customer.class); - xtream.processAnnotations(AddressDetails.class); - xtream.processAnnotations(ContactDetails.class); - xtream.omitField(Customer.class , "firstName"); - xtream.registerConverter(new MyDateConverter()); + xstream = SimpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + xstream.processAnnotations(AddressDetails.class); + xstream.processAnnotations(ContactDetails.class); + xstream.omitField(Customer.class , "firstName"); + xstream.registerConverter(new MyDateConverter()); //xtream.registerConverter(new MySingleValueConverter()); - xtream.aliasField("fn", Customer.class, "firstName"); + xstream.aliasField("fn", Customer.class, "firstName"); - dataXml = xtream.toXML(customer); + dataXml = xstream.toXML(customer); System.out.println(dataXml); } @@ -39,7 +39,7 @@ public class XStreamSimpleXmlTest { @Test public void convertXmlToObject() { - customer = (Customer) xtream.fromXML(dataXml); + customer = (Customer) xstream.fromXML(dataXml); Assert.assertNotNull(customer); } From 8c90c744834b84dd25ced0830236e96884f047c5 Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Tue, 23 Feb 2016 12:44:13 +0300 Subject: [PATCH 06/47] Add test cases with different query types --- .../spring/data/es/config/Config.java | 20 +- .../spring/data/es/dao/ArticleRepository.java | 15 -- .../spring/data/es/model/Article.java | 33 ++- .../data/es/ElasticSearchQueryTest.java | 211 ++++++++++++++++++ 4 files changed, 248 insertions(+), 31 deletions(-) delete mode 100644 spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java create mode 100644 spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java index 78e4083a28..3857056b70 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java @@ -1,5 +1,6 @@ package com.baeldung.spring.data.es.config; +import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.node.NodeBuilder; import org.slf4j.Logger; @@ -17,20 +18,14 @@ import java.nio.file.Path; import java.nio.file.Paths; @Configuration -@EnableElasticsearchRepositories(basePackages = "com.baeldung.repository") +@EnableElasticsearchRepositories(basePackages = "com.baeldung.spring.data.es.repository") @ComponentScan(basePackages = {"com.baeldung.spring.data.es.service"}) public class Config { private static Logger logger = LoggerFactory.getLogger(Config.class); @Bean - public NodeBuilder nodeBuilder() { - return new NodeBuilder(); - } - - @Bean - public ElasticsearchOperations elasticsearchTemplate() { - + public Client client() { try { Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data"); @@ -40,14 +35,19 @@ public class Config { logger.debug(tmpDir.toAbsolutePath().toString()); - return new ElasticsearchTemplate(nodeBuilder() + return new NodeBuilder() .local(true) .settings(elasticsearchSettings.build()) .node() - .client()); + .client(); } catch (IOException ioex) { logger.error("Cannot create temp dir", ioex); throw new RuntimeException(); } } + + @Bean + public ElasticsearchOperations elasticsearchTemplate() { + return new ElasticsearchTemplate(client()); + } } diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java deleted file mode 100644 index 313eba5b36..0000000000 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.spring.data.es.dao; - -import com.baeldung.spring.data.es.model.Article; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.elasticsearch.annotations.Query; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; - -public interface ArticleRepository extends ElasticsearchRepository { - - Page
findByAuthorsName(String name, Pageable pageable); - - @Query("{\"bool\": {\"must\": [{\"match\": {\"authors.name\": \"?0\"}}]}}") - Page
findByAuthorsNameUsingCustomQuery(String name, Pageable pageable); -} diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java index dd472982ce..40db51ac13 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java @@ -1,23 +1,35 @@ package com.baeldung.spring.data.es.model; import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldIndex; -import org.springframework.data.elasticsearch.annotations.FieldType; +import org.springframework.data.elasticsearch.annotations.*; +import java.util.Arrays; import java.util.List; +import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed; +import static org.springframework.data.elasticsearch.annotations.FieldType.Nested; +import static org.springframework.data.elasticsearch.annotations.FieldType.String; + @Document(indexName = "blog", type = "article") public class Article { @Id private String id; - @Field(type = FieldType.String, index = FieldIndex.not_analyzed) + + @MultiField( + mainField = @Field(type = String), + otherFields = { + @NestedField(index = not_analyzed, dotSuffix = "verbatim", type = String) + } + ) private String title; - @Field(type = FieldType.Nested) + + @Field(type = Nested) private List authors; + @Field(type = String, index = not_analyzed) + private String[] tags; + public Article() { } @@ -49,12 +61,21 @@ public class Article { this.authors = authors; } + public String[] getTags() { + return tags; + } + + public void setTags(String... tags) { + this.tags = tags; + } + @Override public String toString() { return "Article{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", authors=" + authors + + ", tags=" + Arrays.toString(tags) + '}'; } } diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java new file mode 100644 index 0000000000..fbc18cbb4c --- /dev/null +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java @@ -0,0 +1,211 @@ +package com.baeldung.spring.data.es; + +import com.baeldung.spring.data.es.config.Config; +import com.baeldung.spring.data.es.model.Article; +import com.baeldung.spring.data.es.model.Author; +import com.baeldung.spring.data.es.service.ArticleService; +import org.elasticsearch.action.ActionFuture; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.unit.Fuzziness; +import org.elasticsearch.index.query.MultiMatchQueryBuilder; +import org.elasticsearch.index.query.QueryBuilder; +import org.elasticsearch.search.aggregations.Aggregation; +import org.elasticsearch.search.aggregations.AggregationBuilders; +import org.elasticsearch.search.aggregations.bucket.terms.StringTerms; +import org.elasticsearch.search.aggregations.bucket.terms.Terms; +import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.data.elasticsearch.core.query.SearchQuery; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static java.util.Arrays.asList; +import static java.util.stream.Collectors.toList; +import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND; +import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {Config.class}, loader = AnnotationConfigContextLoader.class) +public class ElasticSearchQueryTest { + + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; + + @Autowired + private ArticleService articleService; + + @Autowired + private Client client; + + private final Author johnSmith = new Author("John Smith"); + private final Author johnDoe = new Author("John Doe"); + + @Before + public void before() { + elasticsearchTemplate.deleteIndex(Article.class); + elasticsearchTemplate.createIndex(Article.class); + elasticsearchTemplate.putMapping(Article.class); + elasticsearchTemplate.refresh(Article.class, true); + + Article article = new Article("Spring Data Elasticsearch"); + article.setAuthors(asList(johnSmith, johnDoe)); + article.setTags("elasticsearch", "spring data"); + articleService.save(article); + + article = new Article("Search engines"); + article.setAuthors(asList(johnDoe)); + article.setTags("search engines", "tutorial"); + articleService.save(article); + + article = new Article("Second Article About Elasticsearch"); + article.setAuthors(asList(johnSmith)); + article.setTags("elasticsearch", "spring data"); + articleService.save(article); + + article = new Article("Elasticsearch Tutorial"); + article.setAuthors(asList(johnDoe)); + article.setTags("elasticsearch"); + articleService.save(article); + } + + @Test + public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title", "Search engines").operator(AND)) + .build(); + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + } + + @Test + public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title", "Engines Solutions")) + .build(); + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + assertEquals("Search engines", articles.get(0).getTitle()); + } + + @Test + public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title", "elasticsearch data")) + .build(); + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(3, articles.size()); + } + + @Test + public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch")) + .build(); + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + + searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title.verbatim", "Second Article About")) + .build(); + articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(0, articles.size()); + } + + @Test + public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() { + QueryBuilder builder = nestedQuery("authors", + boolQuery().must(termQuery("authors.name", "smith"))); + + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); + List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + + assertEquals(2, articles.size()); + } + + @Test + public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() { + TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("title"); + SearchResponse response = client.prepareSearch("blog").setTypes("article") + .addAggregation(aggregation).execute().actionGet(); + + Map results = response.getAggregations().asMap(); + StringTerms topTags = (StringTerms) results.get("top_tags"); + + List keys = topTags.getBuckets().stream().map(b -> b.getKey()).collect(toList()); + Collections.sort(keys); + assertEquals(asList("about", "article", "data", "elasticsearch", + "engines", "search", "second", "spring", "tutorial"), keys); + } + + @Test + public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() { + TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags") + .order(Terms.Order.aggregation("_count", false)); + SearchResponse response = client.prepareSearch("blog").setTypes("article") + .addAggregation(aggregation).execute().actionGet(); + + Map results = response.getAggregations().asMap(); + StringTerms topTags = (StringTerms) results.get("top_tags"); + + List keys = topTags.getBuckets().stream().map(b -> b.getKey()).collect(toList()); + assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys); + } + + @Test + public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1)) + .build(); + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + } + + @Test + public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title", "spring date elasticserch") + .operator(AND) + .fuzziness(Fuzziness.ONE) + .prefixLength(3)) + .build(); + + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + } + + @Test + public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(multiMatchQuery("tutorial") + .field("title") + .field("tags") + .type(MultiMatchQueryBuilder.Type.BEST_FIELDS)) + .build(); + + List
articles = elasticsearchTemplate + .queryForList(searchQuery, Article.class); + assertEquals(2, articles.size()); + } +} From ecc662501780e7337bc0ca0cda627bb95de3e104 Mon Sep 17 00:00:00 2001 From: Ivan Date: Fri, 4 Mar 2016 14:49:55 +0100 Subject: [PATCH 07/47] Add form tag example --- .../org/baeldung/spring/ClientWebConfig.java | 8 +-- .../baeldung/spring/ClientWebConfigJava.java | 53 +++++++++++++------ .../main/webapp/WEB-INF/view/personForm.jsp | 6 +-- .../main/webapp/WEB-INF/view/personView.jsp | 15 ------ .../src/main/webapp/WEB-INF/web.xml | 2 +- 5 files changed, 42 insertions(+), 42 deletions(-) diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/ClientWebConfig.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/ClientWebConfig.java index c4d819caa5..9705d51606 100644 --- a/spring-mvc-xml/src/main/java/org/baeldung/spring/ClientWebConfig.java +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/ClientWebConfig.java @@ -8,10 +8,10 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration public class ClientWebConfig extends WebMvcConfigurerAdapter { - public ClientWebConfig() { - super(); - } + public ClientWebConfig() { + super(); + } - // API + // API } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/ClientWebConfigJava.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/ClientWebConfigJava.java index d2b57da818..c82201880f 100644 --- a/spring-mvc-xml/src/main/java/org/baeldung/spring/ClientWebConfigJava.java +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/ClientWebConfigJava.java @@ -1,6 +1,12 @@ package org.baeldung.spring; +import java.util.Locale; +import java.util.ResourceBundle; + +import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; +import org.springframework.context.support.MessageSourceResourceBundle; +import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -11,27 +17,40 @@ import org.springframework.web.servlet.view.JstlView; //@Configuration public class ClientWebConfigJava extends WebMvcConfigurerAdapter { - public ClientWebConfigJava() { - super(); - } + public ClientWebConfigJava() { + super(); + } - // API + @Bean + public MessageSource messageSource() { - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); + final ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); + ms.setBasenames("messages"); + return ms; + } - registry.addViewController("/sample.html"); - } + @Bean + public ResourceBundle getBeanResourceBundle() { - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + final Locale locale = Locale.getDefault(); + return new MessageSourceResourceBundle(messageSource(), locale); + } - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); - return bean; - } + registry.addViewController("/sample.html"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } } \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp index 79bda7c17d..63d18a987c 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp @@ -24,7 +24,7 @@

Welcome, Enter The Person Details

- + @@ -104,10 +104,6 @@ Notes - - Select a file to upload - - diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp index 8893314d20..bd14474dfe 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personView.jsp @@ -61,20 +61,5 @@ ${person.notes} - -

Submitted File

- - - - - - - - - - - - -
OriginalFileName :${person.file.originalFilename}
Type :${person.file.contentType}
\ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml index a39c4fdd3a..4e38b2fae6 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml @@ -29,7 +29,7 @@ org.springframework.web.servlet.DispatcherServlet 1 - /tmp + C:/Users/ivan/Desktop/tmp From 934c0dda3740ae8142fadef664efcc26f7537d0f Mon Sep 17 00:00:00 2001 From: Ivan Date: Fri, 4 Mar 2016 14:51:16 +0100 Subject: [PATCH 08/47] Add form tag example --- spring-mvc-xml/src/main/webapp/WEB-INF/web.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml index 4e38b2fae6..a39c4fdd3a 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml @@ -29,7 +29,7 @@ org.springframework.web.servlet.DispatcherServlet 1 - C:/Users/ivan/Desktop/tmp + /tmp From 925f174c54672c5436f3d83d1ad43e77a9bd49ae Mon Sep 17 00:00:00 2001 From: Ivan Date: Fri, 4 Mar 2016 14:53:39 +0100 Subject: [PATCH 09/47] Add form tag example --- spring-mvc-xml/src/main/resources/webMvcConfig.xml | 7 ------- spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp | 2 +- spring-mvc-xml/src/main/webapp/WEB-INF/web.xml | 3 --- 3 files changed, 1 insertion(+), 11 deletions(-) diff --git a/spring-mvc-xml/src/main/resources/webMvcConfig.xml b/spring-mvc-xml/src/main/resources/webMvcConfig.xml index f3297fdbf6..f127cfd637 100644 --- a/spring-mvc-xml/src/main/resources/webMvcConfig.xml +++ b/spring-mvc-xml/src/main/resources/webMvcConfig.xml @@ -25,11 +25,4 @@ - - - - - \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp index 63d18a987c..2836c11668 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/personForm.jsp @@ -22,7 +22,7 @@ -

Welcome, Enter The Person Details

+

Welcome, Enter the Person Details

diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml index a39c4fdd3a..5275efdf24 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml @@ -28,9 +28,6 @@ mvc org.springframework.web.servlet.DispatcherServlet 1 - - /tmp - mvc From f5228b6935ad71e1211ae0cdb63138c4fc0622ac Mon Sep 17 00:00:00 2001 From: jmodi Date: Tue, 8 Mar 2016 23:26:05 +0530 Subject: [PATCH 10/47] First controller added --- .../com/baeldung/spring/HelloController.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 spring-mvc-xml/src/main/java/com/baeldung/spring/HelloController.java diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/HelloController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/HelloController.java new file mode 100644 index 0000000000..97d7ceb22c --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/HelloController.java @@ -0,0 +1,17 @@ +package com.baeldung.spring; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class HelloController extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + ModelAndView model = new ModelAndView("helloworld"); + model.addObject("msg", "!! Welcome to baeldung's Spring Handler Mappings Guide.
This is using SimpleUrlHandlerMapping."); + + return model; + } +} From 453b6f4b5d5f8fe1b15394abdca466eeb4392e7e Mon Sep 17 00:00:00 2001 From: jmodi Date: Sat, 12 Mar 2016 14:27:31 +0530 Subject: [PATCH 11/47] First complete commit for spring-handler-mapping --- spring-mvc-xml/.classpath | 43 ++++++++++++---- spring-mvc-xml/.project | 4 +- .../.settings/org.eclipse.jdt.core.prefs | 5 ++ .../org.eclipse.wst.common.component | 1 + .../{ => controller}/HelloController.java | 2 +- .../controller/HelloGuestController.java | 17 +++++++ .../controller/HelloWorldController.java | 17 +++++++ .../spring/controller/WelcomeController.java | 18 +++++++ .../src/main/webapp/WEB-INF/mvc-servlet.xml | 51 +++++++++++++++++++ .../src/main/webapp/WEB-INF/view/hello.jsp | 15 ++++++ .../main/webapp/WEB-INF/view/helloworld.jsp | 15 ++++++ .../src/main/webapp/WEB-INF/view/welcome.jsp | 15 ++++++ spring-mvc-xml/src/main/webapp/index.jsp | 3 ++ .../src/main/webapp/spring-handler-index.jsp | 26 ++++++++++ 14 files changed, 220 insertions(+), 12 deletions(-) rename spring-mvc-xml/src/main/java/com/baeldung/spring/{ => controller}/HelloController.java (94%) create mode 100644 spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java create mode 100644 spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java create mode 100644 spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java create mode 100644 spring-mvc-xml/src/main/webapp/WEB-INF/view/hello.jsp create mode 100644 spring-mvc-xml/src/main/webapp/WEB-INF/view/helloworld.jsp create mode 100644 spring-mvc-xml/src/main/webapp/WEB-INF/view/welcome.jsp create mode 100644 spring-mvc-xml/src/main/webapp/spring-handler-index.jsp diff --git a/spring-mvc-xml/.classpath b/spring-mvc-xml/.classpath index 6b533711d3..24a63f3df7 100644 --- a/spring-mvc-xml/.classpath +++ b/spring-mvc-xml/.classpath @@ -1,12 +1,11 @@ - + - - + @@ -17,7 +16,38 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -28,10 +58,5 @@ - - - - - diff --git a/spring-mvc-xml/.project b/spring-mvc-xml/.project index de41bcaace..e0267781eb 100644 --- a/spring-mvc-xml/.project +++ b/spring-mvc-xml/.project @@ -1,7 +1,7 @@ spring-mvc-xml - + NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. @@ -32,11 +32,11 @@ + org.eclipse.m2e.core.maven2Nature org.springframework.ide.eclipse.core.springnature org.eclipse.jem.workbench.JavaEMFNature org.eclipse.wst.common.modulecore.ModuleCoreNature org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature org.eclipse.wst.common.project.facet.core.nature org.eclipse.wst.jsdt.core.jsNature diff --git a/spring-mvc-xml/.settings/org.eclipse.jdt.core.prefs b/spring-mvc-xml/.settings/org.eclipse.jdt.core.prefs index 5ff04b9f96..c57289fc09 100644 --- a/spring-mvc-xml/.settings/org.eclipse.jdt.core.prefs +++ b/spring-mvc-xml/.settings/org.eclipse.jdt.core.prefs @@ -5,8 +5,13 @@ org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annota org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.common.component b/spring-mvc-xml/.settings/org.eclipse.wst.common.component index fc995759ac..e54e3acac9 100644 --- a/spring-mvc-xml/.settings/org.eclipse.wst.common.component +++ b/spring-mvc-xml/.settings/org.eclipse.wst.common.component @@ -4,6 +4,7 @@ + diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/HelloController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java similarity index 94% rename from spring-mvc-xml/src/main/java/com/baeldung/spring/HelloController.java rename to spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java index 97d7ceb22c..766aa6670a 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/HelloController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java @@ -1,4 +1,4 @@ -package com.baeldung.spring; +package com.baeldung.spring.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java new file mode 100644 index 0000000000..5c19dc2295 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class HelloGuestController extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + ModelAndView model = new ModelAndView("helloworld"); + model.addObject("msg", "!! Welcome to baeldung's Spring Handler Mappings Guide.
This is using ControllerClassNameHandlerMapping."); + + return model; + } +} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java new file mode 100644 index 0000000000..0659b3815d --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class HelloWorldController extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + ModelAndView model = new ModelAndView("helloworld"); + model.addObject("msg", "!! Welcome to baeldung's Spring Handler Mappings Guide.
This is using BeanNameUrlHandlerMapping."); + + return model; + } +} diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java new file mode 100644 index 0000000000..e3c8bc5a25 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class WelcomeController extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + + ModelAndView model = new ModelAndView("welcome"); + model.addObject("msg", " baeldung's Spring Handler Mappings Guide.
This is using SimpleUrlHandlerMapping."); + + return model; + } +} \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml index 4ba9642448..400c7b5e86 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -3,4 +3,55 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" > + + + + + + + + + + + + + + + + + + + welcomeController + welcomeController + helloController + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/hello.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/hello.jsp new file mode 100644 index 0000000000..2acdae9b0f --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/hello.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Hello World + + +

Hello ${msg}

+
+

+ Go to spring handler mappings homepage + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/helloworld.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/helloworld.jsp new file mode 100644 index 0000000000..2eeabbe0ac --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/helloworld.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Hello World + + +

Hello World ${msg}

+
+

+ Go to spring handler mappings homepage + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/welcome.jsp new file mode 100644 index 0000000000..348ca652ff --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/welcome.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Welcome Page + + +

Welcome to ${msg}

+
+

+ Go to spring handler mappings homepage + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/index.jsp b/spring-mvc-xml/src/main/webapp/index.jsp index 1ecfcec9d7..ef9279f6e5 100644 --- a/spring-mvc-xml/src/main/webapp/index.jsp +++ b/spring-mvc-xml/src/main/webapp/index.jsp @@ -13,6 +13,9 @@

+ \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/spring-handler-index.jsp b/spring-mvc-xml/src/main/webapp/spring-handler-index.jsp new file mode 100644 index 0000000000..d915b344cb --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/spring-handler-index.jsp @@ -0,0 +1,26 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Welcome + + +

Welcome to Spring Handler Mapping Example

+

Click below link to understand each mentioned Handler Mapping: +

+

+ 1. BeanNameUrlHandlerMapping + - Mapping by bean name
+

+ 2. SimpleUrlHandlerMapping +
+

+ 3. ControllerClassNameHandlerMapping + - Mapping by controller name
+

+ Go to spring handler mappings + homepage + + \ No newline at end of file From a243105b01a2ac9e26189da8078d4c2c44200868 Mon Sep 17 00:00:00 2001 From: Roshan Thomas Date: Sun, 13 Mar 2016 20:21:35 -0400 Subject: [PATCH 12/47] Removing HTML media type --- .../config/ContentManagementWebConfig.java | 59 +++++++++---------- .../web/controller/EmployeeController.java | 9 --- .../spring/controller/EmployeeController.java | 9 --- .../contentManagementWebMvcConfig.xml | 7 +-- 4 files changed, 32 insertions(+), 52 deletions(-) diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java index 6fd68394ea..31e223260e 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java @@ -15,39 +15,38 @@ import org.springframework.web.servlet.view.JstlView; @Configuration public class ContentManagementWebConfig extends WebMvcConfigurerAdapter { - public ContentManagementWebConfig() { - super(); - } + public ContentManagementWebConfig() { + super(); + } - // API + // API - @Override - public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - configurer.favorPathExtension(true). - favorParameter(false). - parameterName("mediaType"). - ignoreAcceptHeader(true). - useJaf(false). - defaultContentType(MediaType.TEXT_HTML). - mediaType("xml", MediaType.APPLICATION_XML). - mediaType("html", MediaType.TEXT_HTML). - mediaType("json", MediaType.APPLICATION_JSON); - } + @Override + public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { + configurer.favorPathExtension(false). + favorParameter(true). + parameterName("mediaType"). + ignoreAcceptHeader(true). + useJaf(false). + defaultContentType(MediaType.APPLICATION_JSON). + mediaType("xml", MediaType.APPLICATION_XML). + mediaType("json", MediaType.APPLICATION_JSON); + } - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/sample.html"); + } - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(0); - return bean; - } + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(0); + return bean; + } } diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java index 8a41718b8c..e18bbdbf63 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java @@ -29,15 +29,6 @@ public class EmployeeController { return employeeMap.get(Id); } - @RequestMapping(value = "/employee/{Id}", method = RequestMethod.GET) - public String getEmployeeByIdHtmlView(@PathVariable final long Id, final ModelMap model) { - model.addAttribute("name", employeeMap.get(Id).getName()); - model.addAttribute("contactNumber", employeeMap.get(Id).getContactNumber()); - model.addAttribute("id", employeeMap.get(Id).getId()); - - return "employeeView"; - } - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) { diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java index 753f243edb..eb069ebf0a 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java @@ -30,15 +30,6 @@ public class EmployeeController { return employeeMap.get(Id); } - @RequestMapping(value = "/employee/{Id}", method = RequestMethod.GET) - public String getEmployeeByIdHtmlView(@PathVariable final long Id, final ModelMap model) { - model.addAttribute("name", employeeMap.get(Id).getName()); - model.addAttribute("contactNumber", employeeMap.get(Id).getContactNumber()); - model.addAttribute("id", employeeMap.get(Id).getId()); - - return "employeeView"; - } - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) { diff --git a/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml b/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml index 0fcd85e399..49a5e7c35d 100644 --- a/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml +++ b/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml @@ -23,16 +23,15 @@ - - + + - + - From 12ce3ee247444bec034543bda0da8e4727d2143b Mon Sep 17 00:00:00 2001 From: Roshan Thomas Date: Sun, 13 Mar 2016 20:26:59 -0400 Subject: [PATCH 13/47] Revert "Removing HTML media type" This reverts commit a243105b01a2ac9e26189da8078d4c2c44200868. --- .../config/ContentManagementWebConfig.java | 59 ++++++++++--------- .../web/controller/EmployeeController.java | 9 +++ .../spring/controller/EmployeeController.java | 9 +++ .../contentManagementWebMvcConfig.xml | 7 ++- 4 files changed, 52 insertions(+), 32 deletions(-) diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java index 31e223260e..6fd68394ea 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java @@ -15,38 +15,39 @@ import org.springframework.web.servlet.view.JstlView; @Configuration public class ContentManagementWebConfig extends WebMvcConfigurerAdapter { - public ContentManagementWebConfig() { - super(); - } + public ContentManagementWebConfig() { + super(); + } - // API + // API - @Override - public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - configurer.favorPathExtension(false). - favorParameter(true). - parameterName("mediaType"). - ignoreAcceptHeader(true). - useJaf(false). - defaultContentType(MediaType.APPLICATION_JSON). - mediaType("xml", MediaType.APPLICATION_XML). - mediaType("json", MediaType.APPLICATION_JSON); - } + @Override + public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { + configurer.favorPathExtension(true). + favorParameter(false). + parameterName("mediaType"). + ignoreAcceptHeader(true). + useJaf(false). + defaultContentType(MediaType.TEXT_HTML). + mediaType("xml", MediaType.APPLICATION_XML). + mediaType("html", MediaType.TEXT_HTML). + mediaType("json", MediaType.APPLICATION_JSON); + } - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/sample.html"); + } - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(0); - return bean; - } + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(0); + return bean; + } } diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java index e18bbdbf63..8a41718b8c 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java @@ -29,6 +29,15 @@ public class EmployeeController { return employeeMap.get(Id); } + @RequestMapping(value = "/employee/{Id}", method = RequestMethod.GET) + public String getEmployeeByIdHtmlView(@PathVariable final long Id, final ModelMap model) { + model.addAttribute("name", employeeMap.get(Id).getName()); + model.addAttribute("contactNumber", employeeMap.get(Id).getContactNumber()); + model.addAttribute("id", employeeMap.get(Id).getId()); + + return "employeeView"; + } + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) { diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java index eb069ebf0a..753f243edb 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java @@ -30,6 +30,15 @@ public class EmployeeController { return employeeMap.get(Id); } + @RequestMapping(value = "/employee/{Id}", method = RequestMethod.GET) + public String getEmployeeByIdHtmlView(@PathVariable final long Id, final ModelMap model) { + model.addAttribute("name", employeeMap.get(Id).getName()); + model.addAttribute("contactNumber", employeeMap.get(Id).getContactNumber()); + model.addAttribute("id", employeeMap.get(Id).getId()); + + return "employeeView"; + } + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) { diff --git a/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml b/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml index 49a5e7c35d..0fcd85e399 100644 --- a/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml +++ b/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml @@ -23,15 +23,16 @@ - - + + - + + From 67ae14e8d41e0e34a0271b4e9a37f6a729eb851a Mon Sep 17 00:00:00 2001 From: RoshanThomas Date: Sun, 13 Mar 2016 20:29:38 -0400 Subject: [PATCH 14/47] Removing HTML media type --- .../spring/web/config/ContentManagementWebConfig.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java index 6fd68394ea..2c5b423029 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java @@ -23,14 +23,13 @@ public class ContentManagementWebConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - configurer.favorPathExtension(true). - favorParameter(false). + configurer.favorPathExtension(false). + favorParameter(true). parameterName("mediaType"). ignoreAcceptHeader(true). useJaf(false). - defaultContentType(MediaType.TEXT_HTML). + defaultContentType(MediaType.APPLICATION_JSON). mediaType("xml", MediaType.APPLICATION_XML). - mediaType("html", MediaType.TEXT_HTML). mediaType("json", MediaType.APPLICATION_JSON); } From 66f34a45035ee90e78070db62f2121701ed572ec Mon Sep 17 00:00:00 2001 From: RoshanThomas Date: Sun, 13 Mar 2016 20:30:25 -0400 Subject: [PATCH 15/47] Removing HTML media type --- .../org/baeldung/web/controller/EmployeeController.java | 9 --------- 1 file changed, 9 deletions(-) diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java index 8a41718b8c..e18bbdbf63 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java @@ -29,15 +29,6 @@ public class EmployeeController { return employeeMap.get(Id); } - @RequestMapping(value = "/employee/{Id}", method = RequestMethod.GET) - public String getEmployeeByIdHtmlView(@PathVariable final long Id, final ModelMap model) { - model.addAttribute("name", employeeMap.get(Id).getName()); - model.addAttribute("contactNumber", employeeMap.get(Id).getContactNumber()); - model.addAttribute("id", employeeMap.get(Id).getId()); - - return "employeeView"; - } - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) { From 9b0682b2fbad77bbb02e9978318811881478844a Mon Sep 17 00:00:00 2001 From: RoshanThomas Date: Sun, 13 Mar 2016 20:35:54 -0400 Subject: [PATCH 16/47] Removing HTML media type --- .../contentManagementWebMvcConfig.xml | 35 +++++++++---------- 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml b/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml index 0fcd85e399..e68c88d19d 100644 --- a/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml +++ b/spring-mvc-xml/src/main/resources/contentManagementWebMvcConfig.xml @@ -13,31 +13,30 @@ - - + class="org.springframework.web.servlet.view.InternalResourceViewResolver"> + + - - - - - - + class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> + + + + + + - - - - - - - + + + + + + - \ No newline at end of file + From b9c58d69bce3e7d4d7f304f431328409373bd975 Mon Sep 17 00:00:00 2001 From: RoshanThomas Date: Sun, 13 Mar 2016 20:38:30 -0400 Subject: [PATCH 17/47] Removing HTML media type --- .../spring/controller/EmployeeController.java | 31 ++++++------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java index 753f243edb..aa25f47a2a 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/EmployeeController.java @@ -22,35 +22,24 @@ public class EmployeeController { @RequestMapping(value = "/employee", method = RequestMethod.GET) public ModelAndView showForm() { - return new ModelAndView("employeeHome", "employee", new Employee()); + return new ModelAndView("employeeHome", "employee", new Employee()); } @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { - return employeeMap.get(Id); - } - - @RequestMapping(value = "/employee/{Id}", method = RequestMethod.GET) - public String getEmployeeByIdHtmlView(@PathVariable final long Id, final ModelMap model) { - model.addAttribute("name", employeeMap.get(Id).getName()); - model.addAttribute("contactNumber", employeeMap.get(Id).getContactNumber()); - model.addAttribute("id", employeeMap.get(Id).getId()); - - return "employeeView"; + return employeeMap.get(Id); } @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", employee.getName()); - model.addAttribute("contactNumber", employee.getContactNumber()); - model.addAttribute("id", employee.getId()); - - employeeMap.put(employee.getId(), employee); - - return "employeeView"; + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + employeeMap.put(employee.getId(), employee); + return "employeeView"; } } From 574c9f6b499101274f3e59867417f99ee47a5467 Mon Sep 17 00:00:00 2001 From: David Morley Date: Tue, 15 Mar 2016 05:35:11 -0500 Subject: [PATCH 18/47] Clean up Elasticsearch examples --- spring-data-elasticsearch/.classpath | 31 ------------------- spring-data-elasticsearch/.project | 29 ----------------- .../spring/data/es/config/Config.java | 2 +- .../spring/data/es/dao/ArticleRepository.java | 15 --------- .../data/es/repository/ArticleRepository.java | 2 ++ .../spring/data/es/ElasticSearchTest.java | 11 +++++++ 6 files changed, 14 insertions(+), 76 deletions(-) delete mode 100644 spring-data-elasticsearch/.classpath delete mode 100644 spring-data-elasticsearch/.project delete mode 100644 spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java diff --git a/spring-data-elasticsearch/.classpath b/spring-data-elasticsearch/.classpath deleted file mode 100644 index 698778fef3..0000000000 --- a/spring-data-elasticsearch/.classpath +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-data-elasticsearch/.project b/spring-data-elasticsearch/.project deleted file mode 100644 index 09b9a781ed..0000000000 --- a/spring-data-elasticsearch/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - spring-data-elasticsearch - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - - org.springframework.ide.eclipse.core.springnature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java index 78e4083a28..88b9323066 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java @@ -17,7 +17,7 @@ import java.nio.file.Path; import java.nio.file.Paths; @Configuration -@EnableElasticsearchRepositories(basePackages = "com.baeldung.repository") +@EnableElasticsearchRepositories(basePackages = "com.baeldung.spring.data.es.repository") @ComponentScan(basePackages = {"com.baeldung.spring.data.es.service"}) public class Config { diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java deleted file mode 100644 index 313eba5b36..0000000000 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/dao/ArticleRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.spring.data.es.dao; - -import com.baeldung.spring.data.es.model.Article; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.elasticsearch.annotations.Query; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; - -public interface ArticleRepository extends ElasticsearchRepository { - - Page

findByAuthorsName(String name, Pageable pageable); - - @Query("{\"bool\": {\"must\": [{\"match\": {\"authors.name\": \"?0\"}}]}}") - Page
findByAuthorsNameUsingCustomQuery(String name, Pageable pageable); -} diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java index 27628950d7..8aef865401 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/repository/ArticleRepository.java @@ -5,7 +5,9 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.stereotype.Repository; +@Repository public interface ArticleRepository extends ElasticsearchRepository { Page
findByAuthorsName(String name, Pageable pageable); diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java index 34ccfd788e..7b48772d3f 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java @@ -21,6 +21,7 @@ import java.util.List; import static java.util.Arrays.asList; import static org.elasticsearch.index.query.FilterBuilders.regexpFilter; +import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -31,6 +32,7 @@ public class ElasticSearchTest { @Autowired private ElasticsearchTemplate elasticsearchTemplate; + @Autowired private ArticleService articleService; @@ -126,4 +128,13 @@ public class ElasticSearchTest { assertEquals(count - 1, articleService.count()); } + + @Test + public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() { + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchQuery("title", "Search engines").operator(AND)) + .build(); + List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + assertEquals(1, articles.size()); + } } From ce68b89c7b265e457711bd2fbe0e7a81e50a9b2c Mon Sep 17 00:00:00 2001 From: amedviediev Date: Sun, 28 Feb 2016 19:55:39 +0200 Subject: [PATCH 19/47] Added code for "Intro to Spring Data REST" artice --- spring-data-rest/pom.xml | 62 +++++++++++++++++++ .../baeldung/SpringDataRestApplication.java | 11 ++++ .../java/com/baeldung/UserRepository.java | 12 ++++ .../main/java/com/baeldung/WebsiteUser.java | 41 ++++++++++++ .../src/main/resources/application.properties | 0 5 files changed, 126 insertions(+) create mode 100644 spring-data-rest/pom.xml create mode 100644 spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java create mode 100644 spring-data-rest/src/main/java/com/baeldung/UserRepository.java create mode 100644 spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java create mode 100644 spring-data-rest/src/main/resources/application.properties diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml new file mode 100644 index 0000000000..ad2f9ceb2d --- /dev/null +++ b/spring-data-rest/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + com.baeldung + intro-spring-data-rest + 0.0.1-SNAPSHOT + jar + + intro-spring-data-rest + Intro to Spring Data REST + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-data-rest + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java b/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java new file mode 100644 index 0000000000..6e8e62f52c --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringDataRestApplication { + public static void main(String[] args) { + SpringApplication.run(SpringDataRestApplication.class, args); + } +} diff --git a/spring-data-rest/src/main/java/com/baeldung/UserRepository.java b/spring-data-rest/src/main/java/com/baeldung/UserRepository.java new file mode 100644 index 0000000000..ebbf0d49ab --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/UserRepository.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +import java.util.List; + +@RepositoryRestResource(collectionResourceRel = "users", path = "users") +public interface UserRepository extends PagingAndSortingRepository { + List findByName(@Param("name") String name); +} diff --git a/spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java b/spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java new file mode 100644 index 0000000000..a7a35a2573 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/WebsiteUser.java @@ -0,0 +1,41 @@ +package com.baeldung; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class WebsiteUser { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String name; + private String email; + + 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; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/spring-data-rest/src/main/resources/application.properties b/spring-data-rest/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 From fee6648f5517a6307e6c234d89f65012e262fe57 Mon Sep 17 00:00:00 2001 From: David Morley Date: Wed, 16 Mar 2016 05:24:32 -0500 Subject: [PATCH 20/47] Update Maven settings for Spring Data REST example --- spring-data-rest/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml index ad2f9ceb2d..f7f28aa9f1 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -5,7 +5,7 @@ com.baeldung intro-spring-data-rest - 0.0.1-SNAPSHOT + 1.0 jar intro-spring-data-rest @@ -50,6 +50,7 @@ + ${project.artifactId} org.springframework.boot From 3198b47f81cdf930c6298981065ecce091e72b84 Mon Sep 17 00:00:00 2001 From: David Morley Date: Wed, 16 Mar 2016 05:26:37 -0500 Subject: [PATCH 21/47] Add README for Spring Data REST --- spring-data-rest/README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 spring-data-rest/README.md diff --git a/spring-data-rest/README.md b/spring-data-rest/README.md new file mode 100644 index 0000000000..c9849bd770 --- /dev/null +++ b/spring-data-rest/README.md @@ -0,0 +1,11 @@ +# About this project +This project contains examples from the [Introduction to Spring Data REST](http://www.baeldung.com/spring-data-rest-intro) article from Baeldung. + +# Running the project +The application uses Spring Boot, so it is easy to run. You can start it any of a few ways: +* Run the `main` method from `SpringDataRestApplication` +* Use the Maven Spring Boot plugin: `mvn spring-boot:run` +* Package the application as a JAR and run it using `java -jar intro-spring-data-rest.jar` + +# Viewing the running application +To view the running application, visit [http://localhost:8080](http://localhost:8080) in your browser From 9822ff35c3a23869e5a3a2c62e73959d9990e0fa Mon Sep 17 00:00:00 2001 From: David Morley Date: Wed, 16 Mar 2016 05:28:04 -0500 Subject: [PATCH 22/47] Update README for Spring Data REST tutorial --- spring-data-rest/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-data-rest/README.md b/spring-data-rest/README.md index c9849bd770..d9be83113b 100644 --- a/spring-data-rest/README.md +++ b/spring-data-rest/README.md @@ -2,7 +2,7 @@ This project contains examples from the [Introduction to Spring Data REST](http://www.baeldung.com/spring-data-rest-intro) article from Baeldung. # Running the project -The application uses Spring Boot, so it is easy to run. You can start it any of a few ways: +The application uses [Spring Boot](http://projects.spring.io/spring-boot/), so it is easy to run. You can start it any of a few ways: * Run the `main` method from `SpringDataRestApplication` * Use the Maven Spring Boot plugin: `mvn spring-boot:run` * Package the application as a JAR and run it using `java -jar intro-spring-data-rest.jar` From 7c030c696534a4e51991d784ea985eb4e2cea978 Mon Sep 17 00:00:00 2001 From: David Morley Date: Thu, 17 Mar 2016 06:09:47 -0500 Subject: [PATCH 23/47] Clean up Spring Data Redis pub/sub example --- spring-data-redis/.classpath | 31 ------------------- spring-data-redis/.project | 29 ----------------- spring-data-redis/pom.xml | 2 +- .../spring/data/redis/config/RedisConfig.java | 12 ++++--- .../spring/data/redis/model/Student.java | 2 +- .../data/redis/queue/MessagePublisher.java | 2 +- .../redis/queue/RedisMessagePublisher.java | 2 +- .../redis/queue/RedisMessageSubscriber.java | 4 +-- .../data/redis/repo/StudentRepository.java | 4 +-- .../redis/repo/StudentRepositoryImpl.java | 4 +-- .../data/redis/RedisMessageListenerTest.java | 8 ++--- .../redis/repo/StudentRepositoryTest.java | 7 ++--- 12 files changed, 24 insertions(+), 83 deletions(-) delete mode 100644 spring-data-redis/.classpath delete mode 100644 spring-data-redis/.project rename spring-data-redis/src/main/java/{org => com}/baeldung/spring/data/redis/config/RedisConfig.java (78%) rename spring-data-redis/src/main/java/{org => com}/baeldung/spring/data/redis/model/Student.java (96%) rename spring-data-redis/src/main/java/{org => com}/baeldung/spring/data/redis/queue/MessagePublisher.java (63%) rename spring-data-redis/src/main/java/{org => com}/baeldung/spring/data/redis/queue/RedisMessagePublisher.java (94%) rename spring-data-redis/src/main/java/{org => com}/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java (79%) rename spring-data-redis/src/main/java/{org => com}/baeldung/spring/data/redis/repo/StudentRepository.java (72%) rename spring-data-redis/src/main/java/{org => com}/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java (93%) rename spring-data-redis/src/test/java/{org => com}/baeldung/spring/data/redis/RedisMessageListenerTest.java (78%) rename spring-data-redis/src/test/java/{org => com}/baeldung/spring/data/redis/repo/StudentRepositoryTest.java (93%) diff --git a/spring-data-redis/.classpath b/spring-data-redis/.classpath deleted file mode 100644 index 9ae7bca0fc..0000000000 --- a/spring-data-redis/.classpath +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-data-redis/.project b/spring-data-redis/.project deleted file mode 100644 index 06547e2b9c..0000000000 --- a/spring-data-redis/.project +++ /dev/null @@ -1,29 +0,0 @@ - - - sprint-data-redis - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.springframework.ide.eclipse.core.springnature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/spring-data-redis/pom.xml b/spring-data-redis/pom.xml index ba2020e1ef..25686fca16 100644 --- a/spring-data-redis/pom.xml +++ b/spring-data-redis/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.baeldung - sprint-data-redis + spring-data-redis 1.0 jar diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java similarity index 78% rename from spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java rename to spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java index 0b64afe56c..4fd83a2bb6 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/config/RedisConfig.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java @@ -1,8 +1,8 @@ -package org.baeldung.spring.data.redis.config; +package com.baeldung.spring.data.redis.config; -import org.baeldung.spring.data.redis.queue.RedisMessageSubscriber; -import org.baeldung.spring.data.redis.queue.RedisMessagePublisher; -import org.baeldung.spring.data.redis.queue.MessagePublisher; +import com.baeldung.spring.data.redis.queue.MessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -11,9 +11,10 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; +import org.springframework.data.redis.serializer.GenericToStringSerializer; @Configuration -@ComponentScan("org.baeldung.spring.data.redis") +@ComponentScan("com.baeldung.spring.data.redis") public class RedisConfig { @Bean @@ -25,6 +26,7 @@ public class RedisConfig { public RedisTemplate redisTemplate() { final RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(jedisConnectionFactory()); + template.setValueSerializer(new GenericToStringSerializer(Object.class)); return template; } diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/model/Student.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java similarity index 96% rename from spring-data-redis/src/main/java/org/baeldung/spring/data/redis/model/Student.java rename to spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java index acc96899ce..10ba0f5ef4 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/model/Student.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/model/Student.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.redis.model; +package com.baeldung.spring.data.redis.model; import java.io.Serializable; diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java similarity index 63% rename from spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java rename to spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java index e1f2e3d4b2..9a42545d6c 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/MessagePublisher.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/MessagePublisher.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.redis.queue; +package com.baeldung.spring.data.redis.queue; public interface MessagePublisher { diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java similarity index 94% rename from spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java rename to spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java index 58e789daab..f4b3180a37 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessagePublisher.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessagePublisher.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.redis.queue; +package com.baeldung.spring.data.redis.queue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java similarity index 79% rename from spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java rename to spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java index 4bc60849fb..849e1fb59f 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/queue/RedisMessageSubscriber.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.redis.queue; +package com.baeldung.spring.data.redis.queue; import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.MessageListener; @@ -14,6 +14,6 @@ public class RedisMessageSubscriber implements MessageListener { public void onMessage(final Message message, final byte[] pattern) { messageList.add(message.toString()); - System.out.println("Message received: " + message.toString()); + System.out.println("Message received: " + new String(message.getBody())); } } \ No newline at end of file diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java similarity index 72% rename from spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java rename to spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java index 2a1f6afcce..250c227f00 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepository.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.spring.data.redis.repo; +package com.baeldung.spring.data.redis.repo; -import org.baeldung.spring.data.redis.model.Student; +import com.baeldung.spring.data.redis.model.Student; import java.util.Map; diff --git a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java similarity index 93% rename from spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java rename to spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java index 43294cae58..f13bef0f54 100644 --- a/spring-data-redis/src/main/java/org/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java +++ b/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/repo/StudentRepositoryImpl.java @@ -1,6 +1,6 @@ -package org.baeldung.spring.data.redis.repo; +package com.baeldung.spring.data.redis.repo; -import org.baeldung.spring.data.redis.model.Student; +import com.baeldung.spring.data.redis.model.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; diff --git a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java similarity index 78% rename from spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java rename to spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java index f355e7f63a..403cf990e0 100644 --- a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/RedisMessageListenerTest.java +++ b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerTest.java @@ -1,8 +1,8 @@ -package org.baeldung.spring.data.redis; +package com.baeldung.spring.data.redis; -import org.baeldung.spring.data.redis.config.RedisConfig; -import org.baeldung.spring.data.redis.queue.RedisMessageSubscriber; -import org.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import com.baeldung.spring.data.redis.config.RedisConfig; +import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; +import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/repo/StudentRepositoryTest.java b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java similarity index 93% rename from spring-data-redis/src/test/java/org/baeldung/spring/data/redis/repo/StudentRepositoryTest.java rename to spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java index 08540abd36..c32dfc7670 100644 --- a/spring-data-redis/src/test/java/org/baeldung/spring/data/redis/repo/StudentRepositoryTest.java +++ b/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryTest.java @@ -1,8 +1,7 @@ -package org.baeldung.spring.data.redis.repo; +package com.baeldung.spring.data.redis.repo; -import org.baeldung.spring.data.redis.config.RedisConfig; -import org.baeldung.spring.data.redis.model.Student; -import org.junit.Before; +import com.baeldung.spring.data.redis.config.RedisConfig; +import com.baeldung.spring.data.redis.model.Student; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; From 212596c8d396c15a160a209b4a0fd50353ebf06b Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 19 Mar 2016 20:42:08 +0200 Subject: [PATCH 24/47] spring client security --- .../.classpath | 32 +++++++++ .../.project | 48 +++++++++++++ .../pom.xml | 67 +++++++++++++++++++ .../java/org/baeldung/config/Application.java | 20 ++++++ .../java/org/baeldung/config/MvcConfig.java | 23 +++++++ .../org/baeldung/config/SecurityConfig.java | 40 +++++++++++ .../src/main/resources/application.properties | 3 + .../src/main/webapp/WEB-INF/jsp/index.jsp | 24 +++++++ .../spring-security-jsp-authorize/.classpath | 32 +++++++++ .../spring-security-jsp-authorize/.project | 48 +++++++++++++ .../spring-security-jsp-authorize/pom.xml | 67 +++++++++++++++++++ .../java/org/baeldung/config/Application.java | 20 ++++++ .../java/org/baeldung/config/MvcConfig.java | 23 +++++++ .../org/baeldung/config/SecurityConfig.java | 40 +++++++++++ .../src/main/resources/application.properties | 3 + .../src/main/webapp/WEB-INF/jsp/index.jsp | 33 +++++++++ .../spring-security-jsp-config/.classpath | 32 +++++++++ .../spring-security-jsp-config/.project | 48 +++++++++++++ .../spring-security-jsp-config/pom.xml | 67 +++++++++++++++++++ .../java/org/baeldung/config/Application.java | 20 ++++++ .../java/org/baeldung/config/MvcConfig.java | 23 +++++++ .../org/baeldung/config/SecurityConfig.java | 40 +++++++++++ .../src/main/resources/application.properties | 3 + .../src/main/webapp/WEB-INF/jsp/index.jsp | 21 ++++++ .../spring-security-mvc/.classpath | 32 +++++++++ .../spring-security-mvc/.project | 48 +++++++++++++ .../spring-security-mvc/pom.xml | 45 +++++++++++++ .../java/org/baeldung/config/Application.java | 20 ++++++ .../org/baeldung/config/SecurityConfig.java | 40 +++++++++++ .../src/main/resources/application.properties | 1 + .../.classpath | 32 +++++++++ .../.project | 48 +++++++++++++ .../pom.xml | 62 +++++++++++++++++ .../java/org/baeldung/config/Application.java | 13 ++++ .../java/org/baeldung/config/MvcConfig.java | 42 ++++++++++++ .../org/baeldung/config/SecurityConfig.java | 40 +++++++++++ .../src/main/resources/application.properties | 1 + .../src/main/resources/templates/index.html | 23 +++++++ .../.classpath | 32 +++++++++ .../.project | 48 +++++++++++++ .../pom.xml | 62 +++++++++++++++++ .../java/org/baeldung/config/Application.java | 13 ++++ .../java/org/baeldung/config/MvcConfig.java | 42 ++++++++++++ .../org/baeldung/config/SecurityConfig.java | 40 +++++++++++ .../src/main/resources/application.properties | 1 + .../src/main/resources/templates/index.html | 32 +++++++++ .../.classpath | 32 +++++++++ .../spring-security-thymeleaf-config/.project | 48 +++++++++++++ .../spring-security-thymeleaf-config/pom.xml | 62 +++++++++++++++++ .../java/org/baeldung/config/Application.java | 13 ++++ .../java/org/baeldung/config/MvcConfig.java | 42 ++++++++++++ .../org/baeldung/config/SecurityConfig.java | 40 +++++++++++ .../src/main/resources/application.properties | 1 + .../src/main/resources/templates/index.html | 21 ++++++ 54 files changed, 1753 insertions(+) create mode 100644 spring-security-client/spring-security-jsp-authentication/.classpath create mode 100644 spring-security-client/spring-security-jsp-authentication/.project create mode 100644 spring-security-client/spring-security-jsp-authentication/pom.xml create mode 100644 spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java create mode 100644 spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/MvcConfig.java create mode 100644 spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/SecurityConfig.java create mode 100644 spring-security-client/spring-security-jsp-authentication/src/main/resources/application.properties create mode 100644 spring-security-client/spring-security-jsp-authentication/src/main/webapp/WEB-INF/jsp/index.jsp create mode 100644 spring-security-client/spring-security-jsp-authorize/.classpath create mode 100644 spring-security-client/spring-security-jsp-authorize/.project create mode 100644 spring-security-client/spring-security-jsp-authorize/pom.xml create mode 100644 spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java create mode 100644 spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/MvcConfig.java create mode 100644 spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/SecurityConfig.java create mode 100644 spring-security-client/spring-security-jsp-authorize/src/main/resources/application.properties create mode 100644 spring-security-client/spring-security-jsp-authorize/src/main/webapp/WEB-INF/jsp/index.jsp create mode 100644 spring-security-client/spring-security-jsp-config/.classpath create mode 100644 spring-security-client/spring-security-jsp-config/.project create mode 100644 spring-security-client/spring-security-jsp-config/pom.xml create mode 100644 spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java create mode 100644 spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/MvcConfig.java create mode 100644 spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/SecurityConfig.java create mode 100644 spring-security-client/spring-security-jsp-config/src/main/resources/application.properties create mode 100644 spring-security-client/spring-security-jsp-config/src/main/webapp/WEB-INF/jsp/index.jsp create mode 100644 spring-security-client/spring-security-mvc/.classpath create mode 100644 spring-security-client/spring-security-mvc/.project create mode 100644 spring-security-client/spring-security-mvc/pom.xml create mode 100644 spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java create mode 100644 spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/SecurityConfig.java create mode 100644 spring-security-client/spring-security-mvc/src/main/resources/application.properties create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/.classpath create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/.project create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/pom.xml create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/application.properties create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/index.html create mode 100644 spring-security-client/spring-security-thymeleaf-authorize/.classpath create mode 100644 spring-security-client/spring-security-thymeleaf-authorize/.project create mode 100644 spring-security-client/spring-security-thymeleaf-authorize/pom.xml create mode 100644 spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java create mode 100644 spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/MvcConfig.java create mode 100644 spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/SecurityConfig.java create mode 100644 spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/application.properties create mode 100644 spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/templates/index.html create mode 100644 spring-security-client/spring-security-thymeleaf-config/.classpath create mode 100644 spring-security-client/spring-security-thymeleaf-config/.project create mode 100644 spring-security-client/spring-security-thymeleaf-config/pom.xml create mode 100644 spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java create mode 100644 spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/MvcConfig.java create mode 100644 spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/SecurityConfig.java create mode 100644 spring-security-client/spring-security-thymeleaf-config/src/main/resources/application.properties create mode 100644 spring-security-client/spring-security-thymeleaf-config/src/main/resources/templates/index.html diff --git a/spring-security-client/spring-security-jsp-authentication/.classpath b/spring-security-client/spring-security-jsp-authentication/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-client/spring-security-jsp-authentication/.project b/spring-security-client/spring-security-jsp-authentication/.project new file mode 100644 index 0000000000..6fbbb8518e --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/.project @@ -0,0 +1,48 @@ + + + spring-security-jsp-authenticate + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-jsp-authentication/pom.xml b/spring-security-client/spring-security-jsp-authentication/pom.xml new file mode 100644 index 0000000000..74de4d729b --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + com.baeldung + spring-security-jsp-authentication + 0.0.1-SNAPSHOT + war + + spring-security-jsp-authenticate + Spring Security JSP Authentication tag sample + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + javax.servlet + jstl + + + + org.springframework.security + spring-security-taglibs + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..4057a85f13 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..fa2a324146 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,23 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/resources/application.properties b/spring-security-client/spring-security-jsp-authentication/src/main/resources/application.properties new file mode 100644 index 0000000000..26a80c79f3 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port: 8081 +spring.mvc.view.prefix: /WEB-INF/jsp/ +spring.mvc.view.suffix: .jsp \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-security-client/spring-security-jsp-authentication/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..90c00e980a --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,24 @@ + <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> + + + + +Spring Security JSP Authorize + + + + + +
+ Current user name: +
+ Current user roles: +
+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/.classpath b/spring-security-client/spring-security-jsp-authorize/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-client/spring-security-jsp-authorize/.project b/spring-security-client/spring-security-jsp-authorize/.project new file mode 100644 index 0000000000..a526feb28e --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/.project @@ -0,0 +1,48 @@ + + + spring-security-jsp-authorize + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-jsp-authorize/pom.xml b/spring-security-client/spring-security-jsp-authorize/pom.xml new file mode 100644 index 0000000000..25bb21b663 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + com.baeldung + spring-security-jsp-authorize + 0.0.1-SNAPSHOT + war + + spring-security-jsp-authorize + Spring Security JSP Authorize tag sample + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + javax.servlet + jstl + + + + org.springframework.security + spring-security-taglibs + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..4057a85f13 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..fa2a324146 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,23 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/resources/application.properties b/spring-security-client/spring-security-jsp-authorize/src/main/resources/application.properties new file mode 100644 index 0000000000..26a80c79f3 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port: 8081 +spring.mvc.view.prefix: /WEB-INF/jsp/ +spring.mvc.view.suffix: .jsp \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-security-client/spring-security-jsp-authorize/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..08af845bd4 --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,33 @@ + <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> + + + + +Spring Security JSP Authorize + + + + + +
+ + Only admins can see this message + + + + Only users can see this message + +
+ + + Only users who can call "/admin" URL can see this message + +
+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/.classpath b/spring-security-client/spring-security-jsp-config/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-client/spring-security-jsp-config/.project b/spring-security-client/spring-security-jsp-config/.project new file mode 100644 index 0000000000..9afe120f66 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/.project @@ -0,0 +1,48 @@ + + + spring-security-jsp-config + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-jsp-config/pom.xml b/spring-security-client/spring-security-jsp-config/pom.xml new file mode 100644 index 0000000000..2416552d7c --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + com.baeldung + spring-security-jsp-config + 0.0.1-SNAPSHOT + war + + spring-security-jsp-config + Spring Security JSP configuration + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + javax.servlet + jstl + + + + org.springframework.security + spring-security-taglibs + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..4057a85f13 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..fa2a324146 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,23 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/src/main/resources/application.properties b/spring-security-client/spring-security-jsp-config/src/main/resources/application.properties new file mode 100644 index 0000000000..26a80c79f3 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port: 8081 +spring.mvc.view.prefix: /WEB-INF/jsp/ +spring.mvc.view.suffix: .jsp \ No newline at end of file diff --git a/spring-security-client/spring-security-jsp-config/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-security-client/spring-security-jsp-config/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..bd5ccb0c78 --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,21 @@ + + + + +Spring Security JSP + + + + + +
+ Welcome +
+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-mvc/.classpath b/spring-security-client/spring-security-mvc/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-mvc/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-client/spring-security-mvc/.project b/spring-security-client/spring-security-mvc/.project new file mode 100644 index 0000000000..d675acbf57 --- /dev/null +++ b/spring-security-client/spring-security-mvc/.project @@ -0,0 +1,48 @@ + + + spring-security-mvc + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-mvc/pom.xml b/spring-security-client/spring-security-mvc/pom.xml new file mode 100644 index 0000000000..ec3b1f1782 --- /dev/null +++ b/spring-security-client/spring-security-mvc/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + com.baeldung + spring-security-mvc + 0.0.1-SNAPSHOT + war + + spring-security-mvc + Spring Security MVC + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..4057a85f13 --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-mvc/src/main/resources/application.properties b/spring-security-client/spring-security-mvc/src/main/resources/application.properties new file mode 100644 index 0000000000..c2eee0d931 --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port: 8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/.classpath b/spring-security-client/spring-security-thymeleaf-authentication/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-client/spring-security-thymeleaf-authentication/.project b/spring-security-client/spring-security-thymeleaf-authentication/.project new file mode 100644 index 0000000000..c6b921b16c --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/.project @@ -0,0 +1,48 @@ + + + spring-security-thymeleaf-authentication + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml new file mode 100644 index 0000000000..cdbe0946f4 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + com.baeldung + spring-security-thymeleaf-authentication + 0.0.1-SNAPSHOT + war + + spring-security-thymeleaf-authentication + Spring Security thymeleaf authentication tag sample + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..bea0194b40 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,13 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..9ade60e54c --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/application.properties b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/application.properties new file mode 100644 index 0000000000..bafddced85 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/index.html b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/index.html new file mode 100644 index 0000000000..c65b5f092b --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/resources/templates/index.html @@ -0,0 +1,23 @@ + + + + +Spring Security Thymeleaf + + + + + +
+ Current user name: Bob +
+ Current user roles: [ROLE_USER, ROLE_ADMIN] +
+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/.classpath b/spring-security-client/spring-security-thymeleaf-authorize/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-client/spring-security-thymeleaf-authorize/.project b/spring-security-client/spring-security-thymeleaf-authorize/.project new file mode 100644 index 0000000000..b722d4072d --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/.project @@ -0,0 +1,48 @@ + + + spring-security-thymeleaf-authorize + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml new file mode 100644 index 0000000000..5254f1db1a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + com.baeldung + spring-security-thymeleaf-authorize + 0.0.1-SNAPSHOT + war + + spring-security-thymeleaf-authorize + Spring Security thymeleaf authorize tag sample + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..bea0194b40 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,13 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..9ade60e54c --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/application.properties b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/application.properties new file mode 100644 index 0000000000..bafddced85 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/templates/index.html b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/templates/index.html new file mode 100644 index 0000000000..fcbbfb4957 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/resources/templates/index.html @@ -0,0 +1,32 @@ + + + + +Spring Security Thymeleaf + + + + + +
+
+ Only admins can see this message +
+ +
+ Only users can see this message +
+
+ +
+ Only users who can call "/admin" URL can see this message +
+
+ + \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/.classpath b/spring-security-client/spring-security-thymeleaf-config/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-client/spring-security-thymeleaf-config/.project b/spring-security-client/spring-security-thymeleaf-config/.project new file mode 100644 index 0000000000..f1e44573c4 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/.project @@ -0,0 +1,48 @@ + + + spring-security-thymeleaf-config + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-client/spring-security-thymeleaf-config/pom.xml b/spring-security-client/spring-security-thymeleaf-config/pom.xml new file mode 100644 index 0000000000..ec145a29c8 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + com.baeldung + spring-security-thymeleaf-config + 0.0.1-SNAPSHOT + war + + spring-security-thymeleaf-config + Spring Security thymeleaf configuration sample project + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + + + diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java new file mode 100644 index 0000000000..bea0194b40 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java @@ -0,0 +1,13 @@ +package org.baeldung.config; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..9ade60e54c --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..bd6c56d38a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("john").password("123").roles("USER") + .and() + .withUser("tom").password("111").roles("ADMIN"); + // @formatter:on + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/resources/application.properties b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/application.properties new file mode 100644 index 0000000000..bafddced85 --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8081 \ No newline at end of file diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/resources/templates/index.html b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/templates/index.html new file mode 100644 index 0000000000..8e7394ad6a --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/resources/templates/index.html @@ -0,0 +1,21 @@ + + + + +Spring Security Thymeleaf + + + + + +
+ Welcome +
+ + \ No newline at end of file From 452070aa354a24f82583260048fa3a7935f6ce3a Mon Sep 17 00:00:00 2001 From: ankur-singhal Date: Sun, 20 Mar 2016 20:46:58 +0530 Subject: [PATCH 25/47] XStream- Object to Xml Closing Review comments, test cases added. --- xstream-introduction/.classpath | 15 ----- .../initializer/SimpleXstreamInitializer.java | 2 +- .../baeldung/pojo/AddressDetails.java | 2 +- .../baeldung/pojo/ContactDetails.java | 2 +- .../{org => com}/baeldung/pojo/Customer.java | 4 +- .../baeldung/pojo/CustomerAddressDetails.java | 2 +- .../baeldung/pojo/CustomerPortfolio.java | 2 +- .../baeldung/utility/MyDateConverter.java | 2 +- .../utility/MySingleValueConverter.java | 5 +- .../utility/SimpleDataGeneration.java | 6 +- .../utility/XStreamSimpleXmlTest.java | 62 +++++++++++++++++++ .../utility/XStreamSimpleXmlTest.java | 46 -------------- 12 files changed, 75 insertions(+), 75 deletions(-) delete mode 100644 xstream-introduction/.classpath rename xstream-introduction/src/main/java/{org => com}/baeldung/initializer/SimpleXstreamInitializer.java (91%) rename xstream-introduction/src/main/java/{org => com}/baeldung/pojo/AddressDetails.java (96%) rename xstream-introduction/src/main/java/{org => com}/baeldung/pojo/ContactDetails.java (94%) rename xstream-introduction/src/main/java/{org => com}/baeldung/pojo/Customer.java (95%) rename xstream-introduction/src/main/java/{org => com}/baeldung/pojo/CustomerAddressDetails.java (96%) rename xstream-introduction/src/main/java/{org => com}/baeldung/pojo/CustomerPortfolio.java (94%) rename xstream-introduction/src/main/java/{org => com}/baeldung/utility/MyDateConverter.java (97%) rename xstream-introduction/src/main/java/{org => com}/baeldung/utility/MySingleValueConverter.java (90%) rename xstream-introduction/src/main/java/{org => com}/baeldung/utility/SimpleDataGeneration.java (89%) create mode 100644 xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java delete mode 100644 xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java diff --git a/xstream-introduction/.classpath b/xstream-introduction/.classpath deleted file mode 100644 index 138df490af..0000000000 --- a/xstream-introduction/.classpath +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/xstream-introduction/src/main/java/org/baeldung/initializer/SimpleXstreamInitializer.java b/xstream-introduction/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java similarity index 91% rename from xstream-introduction/src/main/java/org/baeldung/initializer/SimpleXstreamInitializer.java rename to xstream-introduction/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java index 59912539ca..618df877b9 100644 --- a/xstream-introduction/src/main/java/org/baeldung/initializer/SimpleXstreamInitializer.java +++ b/xstream-introduction/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java @@ -1,4 +1,4 @@ -package org.baeldung.initializer; +package com.baeldung.initializer; import com.thoughtworks.xstream.XStream; diff --git a/xstream-introduction/src/main/java/org/baeldung/pojo/AddressDetails.java b/xstream-introduction/src/main/java/com/baeldung/pojo/AddressDetails.java similarity index 96% rename from xstream-introduction/src/main/java/org/baeldung/pojo/AddressDetails.java rename to xstream-introduction/src/main/java/com/baeldung/pojo/AddressDetails.java index 16930cb8ab..e9e30bf5fc 100644 --- a/xstream-introduction/src/main/java/org/baeldung/pojo/AddressDetails.java +++ b/xstream-introduction/src/main/java/com/baeldung/pojo/AddressDetails.java @@ -1,4 +1,4 @@ -package org.baeldung.pojo; +package com.baeldung.pojo; import java.util.List; diff --git a/xstream-introduction/src/main/java/org/baeldung/pojo/ContactDetails.java b/xstream-introduction/src/main/java/com/baeldung/pojo/ContactDetails.java similarity index 94% rename from xstream-introduction/src/main/java/org/baeldung/pojo/ContactDetails.java rename to xstream-introduction/src/main/java/com/baeldung/pojo/ContactDetails.java index 1cb353414b..66475b9d8e 100644 --- a/xstream-introduction/src/main/java/org/baeldung/pojo/ContactDetails.java +++ b/xstream-introduction/src/main/java/com/baeldung/pojo/ContactDetails.java @@ -1,4 +1,4 @@ -package org.baeldung.pojo; +package com.baeldung.pojo; import com.thoughtworks.xstream.annotations.XStreamAlias; diff --git a/xstream-introduction/src/main/java/org/baeldung/pojo/Customer.java b/xstream-introduction/src/main/java/com/baeldung/pojo/Customer.java similarity index 95% rename from xstream-introduction/src/main/java/org/baeldung/pojo/Customer.java rename to xstream-introduction/src/main/java/com/baeldung/pojo/Customer.java index aeb6e0aaf3..2ed11dcdab 100644 --- a/xstream-introduction/src/main/java/org/baeldung/pojo/Customer.java +++ b/xstream-introduction/src/main/java/com/baeldung/pojo/Customer.java @@ -1,4 +1,4 @@ -package org.baeldung.pojo; +package com.baeldung.pojo; import java.util.Date; import java.util.List; @@ -10,7 +10,7 @@ import com.thoughtworks.xstream.annotations.XStreamOmitField; @XStreamAlias("customer") public class Customer { - @XStreamOmitField + //@XStreamOmitField private String firstName; private String lastName; diff --git a/xstream-introduction/src/main/java/org/baeldung/pojo/CustomerAddressDetails.java b/xstream-introduction/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java similarity index 96% rename from xstream-introduction/src/main/java/org/baeldung/pojo/CustomerAddressDetails.java rename to xstream-introduction/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java index e4ce5ae5cd..30fda1b92c 100644 --- a/xstream-introduction/src/main/java/org/baeldung/pojo/CustomerAddressDetails.java +++ b/xstream-introduction/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java @@ -1,4 +1,4 @@ -package org.baeldung.pojo; +package com.baeldung.pojo; import java.util.List; diff --git a/xstream-introduction/src/main/java/org/baeldung/pojo/CustomerPortfolio.java b/xstream-introduction/src/main/java/com/baeldung/pojo/CustomerPortfolio.java similarity index 94% rename from xstream-introduction/src/main/java/org/baeldung/pojo/CustomerPortfolio.java rename to xstream-introduction/src/main/java/com/baeldung/pojo/CustomerPortfolio.java index cc65128650..6f1ce4b651 100644 --- a/xstream-introduction/src/main/java/org/baeldung/pojo/CustomerPortfolio.java +++ b/xstream-introduction/src/main/java/com/baeldung/pojo/CustomerPortfolio.java @@ -1,4 +1,4 @@ -package org.baeldung.pojo; +package com.baeldung.pojo; import java.util.List; diff --git a/xstream-introduction/src/main/java/org/baeldung/utility/MyDateConverter.java b/xstream-introduction/src/main/java/com/baeldung/utility/MyDateConverter.java similarity index 97% rename from xstream-introduction/src/main/java/org/baeldung/utility/MyDateConverter.java rename to xstream-introduction/src/main/java/com/baeldung/utility/MyDateConverter.java index a11b58bd12..564a28d1c5 100644 --- a/xstream-introduction/src/main/java/org/baeldung/utility/MyDateConverter.java +++ b/xstream-introduction/src/main/java/com/baeldung/utility/MyDateConverter.java @@ -1,4 +1,4 @@ -package org.baeldung.utility; +package com.baeldung.utility; import java.text.ParseException; import java.text.SimpleDateFormat; diff --git a/xstream-introduction/src/main/java/org/baeldung/utility/MySingleValueConverter.java b/xstream-introduction/src/main/java/com/baeldung/utility/MySingleValueConverter.java similarity index 90% rename from xstream-introduction/src/main/java/org/baeldung/utility/MySingleValueConverter.java rename to xstream-introduction/src/main/java/com/baeldung/utility/MySingleValueConverter.java index 0cabc4fe03..358d647835 100644 --- a/xstream-introduction/src/main/java/org/baeldung/utility/MySingleValueConverter.java +++ b/xstream-introduction/src/main/java/com/baeldung/utility/MySingleValueConverter.java @@ -1,10 +1,9 @@ -package org.baeldung.utility; +package com.baeldung.utility; import java.text.SimpleDateFormat; import java.util.Date; -import org.baeldung.pojo.Customer; - +import com.baeldung.pojo.Customer; import com.thoughtworks.xstream.converters.SingleValueConverter; public class MySingleValueConverter implements SingleValueConverter { diff --git a/xstream-introduction/src/main/java/org/baeldung/utility/SimpleDataGeneration.java b/xstream-introduction/src/main/java/com/baeldung/utility/SimpleDataGeneration.java similarity index 89% rename from xstream-introduction/src/main/java/org/baeldung/utility/SimpleDataGeneration.java rename to xstream-introduction/src/main/java/com/baeldung/utility/SimpleDataGeneration.java index 2b2a7a8bb8..22d0f0ce77 100644 --- a/xstream-introduction/src/main/java/org/baeldung/utility/SimpleDataGeneration.java +++ b/xstream-introduction/src/main/java/com/baeldung/utility/SimpleDataGeneration.java @@ -1,11 +1,11 @@ -package org.baeldung.utility; +package com.baeldung.utility; import java.util.ArrayList; import java.util.Calendar; import java.util.List; -import org.baeldung.pojo.ContactDetails; -import org.baeldung.pojo.Customer; +import com.baeldung.pojo.ContactDetails; +import com.baeldung.pojo.Customer; public class SimpleDataGeneration { diff --git a/xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java b/xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java new file mode 100644 index 0000000000..50d02528bd --- /dev/null +++ b/xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java @@ -0,0 +1,62 @@ +package com.baeldung.utility; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.AddressDetails; +import com.baeldung.pojo.ContactDetails; +import com.baeldung.pojo.Customer; +import com.baeldung.utility.SimpleDataGeneration; +import com.thoughtworks.xstream.XStream; + +public class XStreamSimpleXmlTest { + + private Customer customer = null; + + private String dataXml = null; + + private XStream xstream = null; + + @Before + public void dataSetup() { + customer = SimpleDataGeneration.generateData(); + xstream = SimpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + xstream.processAnnotations(AddressDetails.class); + xstream.processAnnotations(ContactDetails.class); + xstream.omitField(Customer.class , "lastName"); + xstream.registerConverter(new MyDateConverter()); + // xstream.registerConverter(new MySingleValueConverter()); + xstream.aliasField("fn" , Customer.class , "firstName"); + + dataXml = xstream.toXML(customer); + System.out.println(dataXml); + } + + @Test + public void testClassAliasedAnnotation() { + Assert.assertNotEquals(-1 , dataXml.indexOf("")); + } + + @Test + public void testFieldAliasedAnnotation() { + Assert.assertNotEquals(-1 , dataXml.indexOf("")); + } + + @Test + public void testImplicitCollection() { + Assert.assertEquals(-1 , dataXml.indexOf("contactDetailsList")); + } + + @Test + public void testDateFieldFormating() { + Assert.assertEquals("14-02-1986" , dataXml.substring(dataXml.indexOf("") + 5 , dataXml.indexOf(""))); + } + + @Test + public void testOmitField() { + Assert.assertEquals(-1 , dataXml.indexOf("lastName")); + } +} diff --git a/xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java b/xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java deleted file mode 100644 index 57d0bd2b55..0000000000 --- a/xstream-introduction/src/test/java/org/baeldung/utility/XStreamSimpleXmlTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.baeldung.utility; - -import org.baeldung.initializer.SimpleXstreamInitializer; -import org.baeldung.pojo.AddressDetails; -import org.baeldung.pojo.ContactDetails; -import org.baeldung.pojo.Customer; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.thoughtworks.xstream.XStream; - -public class XStreamSimpleXmlTest { - - private Customer customer = null; - private String dataXml = null; - private XStream xstream = null; - - @Before - public void dataSetup() { - customer = SimpleDataGeneration.generateData(); - xstream = SimpleXstreamInitializer.getXstreamInstance(); - xstream.processAnnotations(Customer.class); - xstream.processAnnotations(AddressDetails.class); - xstream.processAnnotations(ContactDetails.class); - xstream.omitField(Customer.class , "firstName"); - xstream.registerConverter(new MyDateConverter()); - //xtream.registerConverter(new MySingleValueConverter()); - xstream.aliasField("fn", Customer.class, "firstName"); - - dataXml = xstream.toXML(customer); - System.out.println(dataXml); - } - - @Test - public void convertDataToXml() { - Assert.assertNotNull(dataXml); - } - - @Test - public void convertXmlToObject() { - customer = (Customer) xstream.fromXML(dataXml); - Assert.assertNotNull(customer); - } - -} From da9f3c6f2199801339546b853a716cc319a68a25 Mon Sep 17 00:00:00 2001 From: Thai Nguyen Date: Tue, 22 Mar 2016 01:54:59 +0700 Subject: [PATCH 26/47] changes to the test methods and bean classes --- jackson/pom.xml | 2 +- .../jackson/annotation/extra/AppendBean.java | 31 --------- .../jackson/annotation/extra/AppendBeans.java | 58 +++++++++++++++++ .../annotation/extra/ExtraAnnotationTest.java | 51 ++++++++++++--- .../extra/IdentityReferenceBean.java | 33 ---------- .../extra/IdentityReferenceBeans.java | 63 +++++++++++++++++++ 6 files changed, 163 insertions(+), 75 deletions(-) delete mode 100644 jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBean.java create mode 100644 jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBeans.java delete mode 100644 jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBean.java create mode 100644 jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java diff --git a/jackson/pom.xml b/jackson/pom.xml index e9008a81a7..f63ec08b48 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -60,7 +60,7 @@ com.fasterxml.jackson.module jackson-module-jsonSchema - 2.6.0 + 2.7.2 diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBean.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBean.java deleted file mode 100644 index ec67b3c67a..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBean.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.jackson.annotation.extra; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.annotation.JsonAppend; - -@JsonAppend(attrs = {@JsonAppend.Attr(value = "appendedProperty", include = JsonInclude.Include.ALWAYS)}) -public class AppendBean { - private int id; - private String name; - - public AppendBean(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBeans.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBeans.java new file mode 100644 index 0000000000..7b75c205c9 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/AppendBeans.java @@ -0,0 +1,58 @@ +package com.baeldung.jackson.annotation.extra; + +import com.fasterxml.jackson.databind.annotation.JsonAppend; + +public class AppendBeans { + public static class BeanWithoutAppend { + private int id; + private String name; + + public BeanWithoutAppend(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + @JsonAppend(attrs = { @JsonAppend.Attr(value = "version") }) + public static class BeanWithAppend { + private int id; + private String name; + + public BeanWithAppend(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationTest.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationTest.java index db6993da0f..79aae1dd04 100644 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationTest.java @@ -1,38 +1,69 @@ package com.baeldung.jackson.annotation.extra; -import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import org.junit.Test; - +import com.baeldung.jackson.annotation.extra.AppendBeans.BeanWithAppend; +import com.baeldung.jackson.annotation.extra.AppendBeans.BeanWithoutAppend; +import com.baeldung.jackson.annotation.extra.IdentityReferenceBeans.BeanWithIdentityReference; +import com.baeldung.jackson.annotation.extra.IdentityReferenceBeans.BeanWithoutIdentityReference; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; +import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.module.jsonSchema.JsonSchema; import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper; public class ExtraAnnotationTest { + @Test + public void whenNotUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + BeanWithoutIdentityReference bean = new BeanWithoutIdentityReference(1, "Bean Without Identity Reference Annotation"); + String jsonString = mapper.writeValueAsString(bean); + + assertThat(jsonString, containsString("Bean Without Identity Reference Annotation")); + } + @Test public void whenUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); - IdentityReferenceBean bean = new IdentityReferenceBean(1, "Identity Reference Bean"); + BeanWithIdentityReference bean = new BeanWithIdentityReference(1, "Bean With Identity Reference Annotation"); String jsonString = mapper.writeValueAsString(bean); assertEquals("1", jsonString); } + @Test + public void whenNotUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + + BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation"); + ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class).withAttribute("version", "1.0"); + String jsonString = writer.writeValueAsString(bean); + + assertThat(jsonString, not(containsString("version"))); + assertThat(jsonString, not(containsString("1.0"))); + } + @Test public void whenUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); - AppendBean bean = new AppendBean(2, "Append Bean"); - String jsonString = mapper.writeValueAsString(bean); - assertThat(jsonString, containsString("appendedProperty")); + BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation"); + ObjectWriter writer = mapper.writerFor(BeanWithAppend.class).withAttribute("version", "1.0"); + String jsonString = writer.writeValueAsString(bean); + + assertThat(jsonString, containsString("version")); + assertThat(jsonString, containsString("1.0")); } @Test @@ -40,7 +71,7 @@ public class ExtraAnnotationTest { ObjectMapper mapper = new ObjectMapper(); NamingBean bean = new NamingBean(3, "Naming Bean"); String jsonString = mapper.writeValueAsString(bean); - + assertThat(jsonString, containsString("bean_name")); } @@ -51,7 +82,7 @@ public class ExtraAnnotationTest { mapper.acceptJsonFormatVisitor(PropertyDescriptionBean.class, wrapper); JsonSchema jsonSchema = wrapper.finalSchema(); String jsonString = mapper.writeValueAsString(jsonSchema); - + System.out.println(jsonString); assertThat(jsonString, containsString("This is a description of the name property")); } @@ -86,7 +117,7 @@ public class ExtraAnnotationTest { TypeIdResolverStructure.BeanContainer serializedContainer = new TypeIdResolverStructure.BeanContainer(); serializedContainer.setBeans(beans); - + ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(serializedContainer); assertThat(jsonString, containsString("bean1")); diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBean.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBean.java deleted file mode 100644 index 7f9cd0fdba..0000000000 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBean.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.jackson.annotation.extra; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.JsonIdentityReference; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") -@JsonIdentityReference(alwaysAsId = true) -public class IdentityReferenceBean { - private int id; - private String name; - - public IdentityReferenceBean(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java new file mode 100644 index 0000000000..495bb7de43 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java @@ -0,0 +1,63 @@ +package com.baeldung.jackson.annotation.extra; + +import com.fasterxml.jackson.annotation.JsonIdentityInfo; +import com.fasterxml.jackson.annotation.JsonIdentityReference; +import com.fasterxml.jackson.annotation.ObjectIdGenerators; + + +public class IdentityReferenceBeans { + @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") + public static class BeanWithoutIdentityReference { + private int id; + private String name; + + public BeanWithoutIdentityReference(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") + @JsonIdentityReference(alwaysAsId = true) + public static class BeanWithIdentityReference { + private int id; + private String name; + + public BeanWithIdentityReference(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} \ No newline at end of file From 8d398b28529fd16316f38496617894fde2bf2d05 Mon Sep 17 00:00:00 2001 From: Ivan Date: Wed, 23 Mar 2016 13:12:12 +0100 Subject: [PATCH 27/47] Add file upload example --- spring-mvc-java/.classpath | 74 ++++++------ spring-mvc-java/pom.xml | 7 ++ .../spring/web/config/ClientWebConfig.java | 112 +++++++++--------- .../web/config/MainWebAppInitializer.java | 50 ++++---- .../baeldung/spring/web/config/WebConfig.java | 15 +++ .../web/controller/FileUploadController.java | 80 +++++++++++++ .../webapp/WEB-INF/view/fileUploadForm.jsp | 47 ++++++++ .../webapp/WEB-INF/view/fileUploadView.jsp | 20 ++++ 8 files changed, 293 insertions(+), 112 deletions(-) create mode 100644 spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java create mode 100644 spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp create mode 100644 spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadView.jsp diff --git a/spring-mvc-java/.classpath b/spring-mvc-java/.classpath index 6b533711d3..a642d37ceb 100644 --- a/spring-mvc-java/.classpath +++ b/spring-mvc-java/.classpath @@ -1,37 +1,37 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index d9a578cb8c..4358e7939f 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -57,6 +57,13 @@ slf4j-log4j12 ${org.slf4j.version} + + + commons-fileupload + commons-fileupload + 1.3.1 + + junit diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java index db57b4716b..3f451f4259 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java @@ -25,69 +25,71 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration public class ClientWebConfig extends WebMvcConfigurerAdapter { - public ClientWebConfig() { - super(); - } + public ClientWebConfig() { + super(); + } - // API + // API - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } + registry.addViewController("/sample.html"); + registry.addViewController("/fileUpload.html"); + registry.addViewController("/fileUploadForm.html"); + } - @Bean - public ViewResolver thymeleafViewResolver() { - final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } + @Bean + public ViewResolver thymeleafViewResolver() { + final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(0); - return bean; - } + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(0); + return bean; + } - @Bean - @Description("Thymeleaf template resolver serving HTML 5") - public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); - templateResolver.setPrefix("/WEB-INF/templates/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); - return templateResolver; - } + @Bean + @Description("Thymeleaf template resolver serving HTML 5") + public ServletContextTemplateResolver templateResolver() { + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } - @Bean - @Description("Thymeleaf template engine with Spring integration") - public SpringTemplateEngine templateEngine() { - final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - final Set dialects = new HashSet<>(); - dialects.add(new CustomDialect()); - templateEngine.setAdditionalDialects(dialects); - return templateEngine; - } + @Bean + @Description("Thymeleaf template engine with Spring integration") + public SpringTemplateEngine templateEngine() { + final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + final Set dialects = new HashSet<>(); + dialects.add(new CustomDialect()); + templateEngine.setAdditionalDialects(dialects); + return templateEngine; + } - @Bean - @Description("Spring message resolver") - public MessageSource messageSource() { - final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); - messageSource.setBasename("messages"); - return messageSource; - } + @Bean + @Description("Spring message resolver") + public MessageSource messageSource() { + final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } } \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java index 87502e2088..9dd9ae98b0 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java @@ -14,28 +14,38 @@ import org.springframework.web.servlet.DispatcherServlet; public class MainWebAppInitializer implements WebApplicationInitializer { - /** - * Register and configure all Servlet container components necessary to power the web application. - */ - @Override - public void onStartup(final ServletContext sc) throws ServletException { - System.out.println("MainWebAppInitializer.onStartup()"); + private static final String TMP_FOLDER = "C:/Users/ivan/Desktop/tmp"; // 5 + // MB + private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB - // Create the 'root' Spring application context - final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.scan("org.baeldung.spring.web.config"); - // root.getEnvironment().setDefaultProfiles("embedded"); + /** + * Register and configure all Servlet container components necessary to power the web application. + */ + @Override + public void onStartup(final ServletContext sc) throws ServletException { - // Manages the lifecycle of the root application context - sc.addListener(new ContextLoaderListener(root)); + // Create the 'root' Spring application context + final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); + root.scan("org.baeldung.spring.web.config"); + // root.getEnvironment().setDefaultProfiles("embedded"); - // Handles requests into the application - final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext())); - appServlet.setLoadOnStartup(1); - final Set mappingConflicts = appServlet.addMapping("/"); - if (!mappingConflicts.isEmpty()) { - throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); - } - } + // Manages the lifecycle of the root application context + sc.addListener(new ContextLoaderListener(root)); + + // Handles requests into the application + final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext())); + appServlet.setLoadOnStartup(1); + + // final MultipartConfigElement multipartConfigElement = new + // MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE, + // MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); + // + // appServlet.setMultipartConfig(multipartConfigElement); + + final Set mappingConflicts = appServlet.addMapping("/"); + if (!mappingConflicts.isEmpty()) { + throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); + } + } } diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java index 58438d2976..b7d87dffbc 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java @@ -22,6 +22,21 @@ public class WebConfig extends WebMvcConfigurerAdapter { super(); } + // @Bean + // public StandardServletMultipartResolver multipartResolver() { + // return new StandardServletMultipartResolver(); + // } + + // @Bean(name = "multipartResolver") + // public CommonsMultipartResolver multipartResolver() { + // + // final CommonsMultipartResolver multipartResolver = new + // CommonsMultipartResolver(); + // multipartResolver.setMaxUploadSize(100000); + // + // return multipartResolver; + // } + @Override public void addViewControllers(final ViewControllerRegistry registry) { diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java b/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java new file mode 100644 index 0000000000..5c9d3cbef3 --- /dev/null +++ b/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java @@ -0,0 +1,80 @@ +package org.baeldung.web.controller; + +import java.io.File; +import java.io.IOException; +import java.util.Iterator; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.io.FileUtils; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +@Controller +public class FileUploadController { + + @RequestMapping(value = "/addFile1", method = RequestMethod.POST) + public String submit(@RequestParam("file") final MultipartFile file, final ModelMap modelMap) { + + modelMap.addAttribute("fileName", file.getOriginalFilename()); + modelMap.addAttribute("fileType", file.getContentType()); + + return "fileUploadView"; + } + + @RequestMapping(value = "/addFile2", method = RequestMethod.POST) + public String submit(final HttpServletRequest request, final HttpServletResponse response, + final ModelMap modelMap) { + + final String TEMP_PATH = "C:\\Users\\ivan\\Desktop\\tmp\\"; + + try { + + final DiskFileItemFactory factory = new DiskFileItemFactory(); + + // Configure a repository (to ensure a secure temp location is used) + final File repository = new File(TEMP_PATH); + factory.setRepository(repository); + + // Create a new file upload handler + final ServletFileUpload upload = new ServletFileUpload(factory); + + // Parse the request + final List items = upload.parseRequest(request); + + final Iterator iter = items.iterator(); + + while (iter.hasNext()) { + + final FileItem item = iter.next(); + + if (!item.isFormField()) { + + final File targetFile = new File(TEMP_PATH + item.getName()); + FileUtils.copyInputStreamToFile(item.getInputStream(), targetFile); + + modelMap.addAttribute("fileName", item.getName()); + modelMap.addAttribute("fileType", item.getContentType()); + } + } + + } catch (final FileUploadException e) { + e.printStackTrace(); + + } catch (final IOException e) { + e.printStackTrace(); + } + + return "fileUploadView"; + } +} diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp new file mode 100644 index 0000000000..05a7e25a02 --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp @@ -0,0 +1,47 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + + File Upload Example + + + + +

Enter The File to Upload (MultipartFile handling)

+ + + + + + + + + + + +
Select a file to upload
+ +
+ +
+ +

Enter The File to Upload (HttpServletRequest handling)

+ + + + + + + + + + + +
Select a file to upload
+ +
+ + + + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadView.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadView.jsp new file mode 100644 index 0000000000..779c26a597 --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadView.jsp @@ -0,0 +1,20 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + + + + Spring MVC File Upload + + +

Submitted File

+ + + + + + + + + +
OriginalFileName :${fileName}
Type :${fileType}
+ + \ No newline at end of file From 09a1ebfa07b9d697fc4973aa20d87700bc8aa370 Mon Sep 17 00:00:00 2001 From: Ivan Date: Wed, 23 Mar 2016 13:16:10 +0100 Subject: [PATCH 28/47] Add file upload example --- .../java/org/baeldung/web/controller/FileUploadController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java b/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java index 5c9d3cbef3..a25a620c8b 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java +++ b/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java @@ -36,7 +36,7 @@ public class FileUploadController { public String submit(final HttpServletRequest request, final HttpServletResponse response, final ModelMap modelMap) { - final String TEMP_PATH = "C:\\Users\\ivan\\Desktop\\tmp\\"; + final String TEMP_PATH = "/tmp/"; try { From e4850ec2752e04625870b50880c0a48edd0738b8 Mon Sep 17 00:00:00 2001 From: Thai Nguyen Date: Sat, 26 Mar 2016 11:40:17 +0700 Subject: [PATCH 29/47] initial commit for jooq with spring --- jooq-spring/.classpath | 36 ++++ jooq-spring/.project | 23 +++ jooq-spring/pom.xml | 159 ++++++++++++++++++ .../main/resources/intro_config.properties | 8 + .../src/main/resources/intro_schema.sql | 34 ++++ .../introduction/ExceptionTranslator.java | 19 +++ .../jooq/introduction/PersistenceContext.java | 79 +++++++++ .../baeldung/jooq/introduction/QueryTest.java | 87 ++++++++++ 8 files changed, 445 insertions(+) create mode 100644 jooq-spring/.classpath create mode 100644 jooq-spring/.project create mode 100644 jooq-spring/pom.xml create mode 100644 jooq-spring/src/main/resources/intro_config.properties create mode 100644 jooq-spring/src/main/resources/intro_schema.sql create mode 100644 jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java create mode 100644 jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java create mode 100644 jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java diff --git a/jooq-spring/.classpath b/jooq-spring/.classpath new file mode 100644 index 0000000000..e43402fa4f --- /dev/null +++ b/jooq-spring/.classpath @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jooq-spring/.project b/jooq-spring/.project new file mode 100644 index 0000000000..3c3f3d602b --- /dev/null +++ b/jooq-spring/.project @@ -0,0 +1,23 @@ + + + jooq-spring + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/jooq-spring/pom.xml b/jooq-spring/pom.xml new file mode 100644 index 0000000000..80eba86164 --- /dev/null +++ b/jooq-spring/pom.xml @@ -0,0 +1,159 @@ + + 4.0.0 + com.baeldung + jooq-spring + 0.0.1-SNAPSHOT + + + 3.7.3 + 1.4.191 + 2.4.4 + 4.2.5.RELEASE + 1.7.18 + 1.1.3 + 4.12 + + + + + + org.jooq + jooq + ${org.jooq.version} + + + + + com.h2database + h2 + ${com.h2database.version} + + + com.zaxxer + HikariCP + ${com.zaxxer.HikariCP.version} + + + + + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-jdbc + ${org.springframework.version} + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + runtime + + + ch.qos.logback + logback-classic + ${ch.qos.logback.version} + runtime + + + + + junit + junit + ${junit.version} + test + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + src/main/resources/intro_config.properties + + + + + + + + org.codehaus.mojo + sql-maven-plugin + 1.5 + + + initialize + + execute + + + ${db.driver} + ${db.url} + ${db.username} + ${db.password} + + src/main/resources/intro_schema.sql + + + + + + + com.h2database + h2 + ${com.h2database.version} + + + + + + org.jooq + jooq-codegen-maven + ${org.jooq.version} + + + generate-sources + + generate + + + + ${db.driver} + ${db.url} + ${db.username} + ${db.password} + + + + com.baeldung.jooq.introduction.db + src/test/java + + + + + + + + + \ No newline at end of file diff --git a/jooq-spring/src/main/resources/intro_config.properties b/jooq-spring/src/main/resources/intro_config.properties new file mode 100644 index 0000000000..3275089585 --- /dev/null +++ b/jooq-spring/src/main/resources/intro_config.properties @@ -0,0 +1,8 @@ +#Database Configuration +db.driver=org.h2.Driver +db.url=jdbc:h2:~/jooq +db.username=sa +db.password= + +#SQL Dialect +jooq.sql.dialect=H2 \ No newline at end of file diff --git a/jooq-spring/src/main/resources/intro_schema.sql b/jooq-spring/src/main/resources/intro_schema.sql new file mode 100644 index 0000000000..0d4bd26235 --- /dev/null +++ b/jooq-spring/src/main/resources/intro_schema.sql @@ -0,0 +1,34 @@ +DROP TABLE IF EXISTS author_book, author, book; + +CREATE TABLE author ( + id INT NOT NULL PRIMARY KEY, + first_name VARCHAR(50), + last_name VARCHAR(50) NOT NULL +); + +CREATE TABLE book ( + id INT NOT NULL PRIMARY KEY, + title VARCHAR(100) NOT NULL +); + +CREATE TABLE author_book ( + author_id INT NOT NULL, + book_id INT NOT NULL, + + PRIMARY KEY (author_id, book_id), + CONSTRAINT fk_ab_author FOREIGN KEY (author_id) REFERENCES author (id) + ON UPDATE CASCADE ON DELETE CASCADE, + CONSTRAINT fk_ab_book FOREIGN KEY (book_id) REFERENCES book (id) +); + +INSERT INTO author VALUES + (1, 'Kathy', 'Sierra'), + (2, 'Bert', 'Bates'), + (3, 'Bryan', 'Basham'); + +INSERT INTO book VALUES + (1, 'Head First Java'), + (2, 'Head First Servlets and JSP'), + (3, 'OCA/OCP Java SE 7 Programmer'); + +INSERT INTO author_book VALUES (1, 1), (1, 3), (2, 1); \ No newline at end of file diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java new file mode 100644 index 0000000000..7bee21f077 --- /dev/null +++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java @@ -0,0 +1,19 @@ +package com.baeldung.jooq.introduction; + +import org.jooq.ExecuteContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DefaultExecuteListener; + +import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator; +import org.springframework.jdbc.support.SQLExceptionTranslator; + +public class ExceptionTranslator extends DefaultExecuteListener { + private static final long serialVersionUID = 649359748808106775L; + + @Override + public void exception(ExecuteContext context) { + SQLDialect dialect = context.configuration().dialect(); + SQLExceptionTranslator translator = new SQLErrorCodeSQLExceptionTranslator(dialect.name()); + context.exception(translator.translate("Access database using jOOQ", context.sql(), context.sqlException())); + } +} \ No newline at end of file diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java new file mode 100644 index 0000000000..4bcf3a527e --- /dev/null +++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java @@ -0,0 +1,79 @@ +package com.baeldung.jooq.introduction; + +import javax.sql.DataSource; +import com.zaxxer.hikari.HikariDataSource; + +import org.jooq.SQLDialect; +import org.jooq.impl.DataSourceConnectionProvider; +import org.jooq.impl.DefaultConfiguration; +import org.jooq.impl.DefaultDSLContext; +import org.jooq.impl.DefaultExecuteListenerProvider; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@ComponentScan({ "com.baeldung.jooq.introduction.db.public_.tables" }) +@EnableTransactionManagement +@PropertySource("classpath:intro_config.properties") +public class PersistenceContext { + @Autowired + private Environment environment; + + @Bean + public DataSource dataSource() { + HikariDataSource dataSource = new HikariDataSource(); + + dataSource.setDriverClassName(environment.getRequiredProperty("db.driver")); + dataSource.setJdbcUrl(environment.getRequiredProperty("db.url")); + dataSource.setUsername(environment.getRequiredProperty("db.username")); + dataSource.setPassword(environment.getRequiredProperty("db.password")); + + return dataSource; + } + + @Bean + public TransactionAwareDataSourceProxy transactionAwareDataSource() { + return new TransactionAwareDataSourceProxy(dataSource()); + } + + @Bean + public DataSourceTransactionManager transactionManager() { + return new DataSourceTransactionManager(dataSource()); + } + + @Bean + public DataSourceConnectionProvider connectionProvider() { + return new DataSourceConnectionProvider(transactionAwareDataSource()); + } + + @Bean + public ExceptionTranslator exceptionTransformer() { + return new ExceptionTranslator(); + } + + @Bean + public DefaultDSLContext dsl() { + return new DefaultDSLContext(configuration()); + } + + @Bean + public DefaultConfiguration configuration() { + DefaultConfiguration jooqConfiguration = new DefaultConfiguration(); + jooqConfiguration.set(connectionProvider()); + jooqConfiguration.set(new DefaultExecuteListenerProvider(exceptionTransformer())); + + String sqlDialectName = environment.getRequiredProperty("jooq.sql.dialect"); + SQLDialect dialect = SQLDialect.valueOf(sqlDialectName); + jooqConfiguration.set(dialect); + + return jooqConfiguration; + } +} \ No newline at end of file diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java new file mode 100644 index 0000000000..34be23bf2a --- /dev/null +++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java @@ -0,0 +1,87 @@ +package com.baeldung.jooq.introduction; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.jooq.DSLContext; +import org.jooq.Record3; +import org.jooq.Result; +import org.jooq.impl.DSL; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.jooq.introduction.db.public_.tables.Author; +import com.baeldung.jooq.introduction.db.public_.tables.AuthorBook; +import com.baeldung.jooq.introduction.db.public_.tables.Book; + +@ContextConfiguration(classes = PersistenceContext.class) +@Transactional(transactionManager = "transactionManager") +@RunWith(SpringJUnit4ClassRunner.class) +public class QueryTest { + @Autowired + private DSLContext create; + + Author author = Author.AUTHOR; + Book book = Book.BOOK; + AuthorBook authorBook = AuthorBook.AUTHOR_BOOK; + + @Test + public void givenValidData_whenInserting_thenSucceed() { + create.insertInto(author).set(author.ID, 4).set(author.FIRST_NAME, "Herbert").set(author.LAST_NAME, "Schildt").execute(); + create.insertInto(book).set(book.ID, 4).set(book.TITLE, "A Beginner's Guide").execute(); + create.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 4).execute(); + Result> result = create.select(author.ID, author.LAST_NAME, DSL.count()).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID)) + .groupBy(author.LAST_NAME).fetch(); + + assertEquals(3, result.size()); + assertEquals("Sierra", result.getValue(0, author.LAST_NAME)); + assertEquals(Integer.valueOf(2), result.getValue(0, DSL.count())); + assertEquals("Schildt", result.getValue(2, author.LAST_NAME)); + assertEquals(Integer.valueOf(1), result.getValue(2, DSL.count())); + } + + @Test(expected = DataAccessException.class) + public void givenInvalidData_whenInserting_thenFail() { + create.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute(); + } + + @Test + public void givenValidData_whenUpdating_thenSucceed() { + create.update(author).set(author.LAST_NAME, "Baeldung").where(author.ID.equal(3)).execute(); + create.update(book).set(book.TITLE, "Building your REST API with Spring").where(book.ID.equal(3)).execute(); + create.insertInto(authorBook).set(authorBook.AUTHOR_ID, 3).set(authorBook.BOOK_ID, 3).execute(); + Result> result = create.select(author.ID, author.LAST_NAME, book.TITLE).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID)).where(author.ID.equal(3)) + .fetch(); + + assertEquals(1, result.size()); + assertEquals(Integer.valueOf(3), result.getValue(0, author.ID)); + assertEquals("Baeldung", result.getValue(0, author.LAST_NAME)); + assertEquals("Building your REST API with Spring", result.getValue(0, book.TITLE)); + } + + @Test(expected = DataAccessException.class) + public void givenInvalidData_whenUpdating_thenFail() { + create.update(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute(); + } + + @Test + public void givenValidData_whenDeleting_thenSucceed() { + create.delete(author).where(author.ID.lt(3)).execute(); + Result> result = create.select(author.ID, author.FIRST_NAME, author.LAST_NAME).from(author).fetch(); + + assertEquals(1, result.size()); + assertEquals("Bryan", result.getValue(0, author.FIRST_NAME)); + assertEquals("Basham", result.getValue(0, author.LAST_NAME)); + } + + @Test(expected = DataAccessException.class) + public void givenInvalidData_whenDeleting_thenFail() { + create.delete(book).where(book.ID.equal(1)).execute(); + } +} \ No newline at end of file From c879a9dc74a7931a23db9d607d37c63d712f719d Mon Sep 17 00:00:00 2001 From: David Morley Date: Mon, 28 Mar 2016 06:03:56 -0500 Subject: [PATCH 30/47] Change output directory for jOOQ codegen --- jooq-spring/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jooq-spring/pom.xml b/jooq-spring/pom.xml index 80eba86164..5465b86736 100644 --- a/jooq-spring/pom.xml +++ b/jooq-spring/pom.xml @@ -147,7 +147,7 @@ com.baeldung.jooq.introduction.db - src/test/java + src/main/java From 8892b7bc65ff00295d87afad34cee3a8d8b08a0c Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 29 Mar 2016 22:04:42 +0200 Subject: [PATCH 31/47] custom expression handler --- spring-security-custom-permission/.classpath | 32 +++ spring-security-custom-permission/.project | 48 +++++ spring-security-custom-permission/pom.xml | 107 +++++++++ .../main/java/org/baeldung/Application.java | 12 ++ .../baeldung/config/MethodSecurityConfig.java | 21 ++ .../java/org/baeldung/config/MvcConfig.java | 42 ++++ .../org/baeldung/config/SecurityConfig.java | 43 ++++ .../org/baeldung/persistence/SetupData.java | 89 ++++++++ .../dao/OrganizationRepository.java | 10 + .../persistence/dao/PrivilegeRepository.java | 10 + .../persistence/dao/RoleRepository.java | 9 + .../persistence/dao/UserRepository.java | 10 + .../org/baeldung/persistence/model/Foo.java | 94 ++++++++ .../persistence/model/Organization.java | 95 ++++++++ .../baeldung/persistence/model/Privilege.java | 95 ++++++++ .../org/baeldung/persistence/model/Role.java | 121 +++++++++++ .../org/baeldung/persistence/model/User.java | 198 +++++++++++++++++ ...CustomMethodSecurityExpressionHandler.java | 22 ++ .../CustomMethodSecurityExpressionRoot.java | 50 +++++ .../security/CustomPermissionEvaluator.java | 47 ++++ .../security/MySecurityExpressionRoot.java | 203 ++++++++++++++++++ .../security/MyUserDetailsService.java | 31 +++ .../java/org/baeldung/web/MainController.java | 57 +++++ .../src/main/resources/application.properties | 9 + .../src/main/resources/templates/index.html | 21 ++ .../test/java/org/baeldung/web/LiveTest.java | 67 ++++++ 26 files changed, 1543 insertions(+) create mode 100644 spring-security-custom-permission/.classpath create mode 100644 spring-security-custom-permission/.project create mode 100644 spring-security-custom-permission/pom.xml create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/Application.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/config/MethodSecurityConfig.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/config/MvcConfig.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/OrganizationRepository.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/RoleRepository.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Foo.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Organization.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Privilege.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Role.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionHandler.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java create mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java create mode 100644 spring-security-custom-permission/src/main/resources/application.properties create mode 100644 spring-security-custom-permission/src/main/resources/templates/index.html create mode 100644 spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java diff --git a/spring-security-custom-permission/.classpath b/spring-security-custom-permission/.classpath new file mode 100644 index 0000000000..0cad5db2d0 --- /dev/null +++ b/spring-security-custom-permission/.classpath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-security-custom-permission/.project b/spring-security-custom-permission/.project new file mode 100644 index 0000000000..06b5975e98 --- /dev/null +++ b/spring-security-custom-permission/.project @@ -0,0 +1,48 @@ + + + spring-security-custom-permission + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/spring-security-custom-permission/pom.xml b/spring-security-custom-permission/pom.xml new file mode 100644 index 0000000000..6f460f1751 --- /dev/null +++ b/spring-security-custom-permission/pom.xml @@ -0,0 +1,107 @@ + + + 4.0.0 + + com.baeldung + spring-security-custom-permission + 0.0.1-SNAPSHOT + war + + spring-security-custom-permission + Spring Security custom permission + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + + + + + + junit + junit + test + + + + org.hamcrest + hamcrest-core + test + + + + org.hamcrest + hamcrest-library + test + + + + com.jayway.restassured + rest-assured + ${rest-assured.version} + test + + + commons-logging + commons-logging + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + 2.4.0 + + + diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/Application.java b/spring-security-custom-permission/src/main/java/org/baeldung/Application.java new file mode 100644 index 0000000000..a9d6f3b8b1 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/Application.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/MethodSecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/MethodSecurityConfig.java new file mode 100644 index 0000000000..c4624e85e0 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/MethodSecurityConfig.java @@ -0,0 +1,21 @@ +package org.baeldung.config; + +import org.baeldung.security.CustomMethodSecurityExpressionHandler; +import org.baeldung.security.CustomPermissionEvaluator; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; + +@Configuration +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { + + @Override + protected MethodSecurityExpressionHandler createExpressionHandler() { + // final DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); + final CustomMethodSecurityExpressionHandler expressionHandler = new CustomMethodSecurityExpressionHandler(); + expressionHandler.setPermissionEvaluator(new CustomPermissionEvaluator()); + return expressionHandler; + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/MvcConfig.java new file mode 100644 index 0000000000..9ade60e54c --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } + + @Override + public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + registry.addViewController("/").setViewName("forward:/index"); + registry.addViewController("/index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } +} \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java new file mode 100644 index 0000000000..b365744bea --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/config/SecurityConfig.java @@ -0,0 +1,43 @@ +package org.baeldung.config; + +import org.baeldung.security.MyUserDetailsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +@ComponentScan("org.baeldung.security") +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private MyUserDetailsService userDetailsService; + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService); + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/resources/**"); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers("/login").permitAll() + .antMatchers("/admin").hasRole("ADMIN") + .anyRequest().authenticated() + .and().formLogin().permitAll() + .and().csrf().disable(); + ; + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java new file mode 100644 index 0000000000..fa6d4c42ee --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java @@ -0,0 +1,89 @@ +package org.baeldung.persistence; + +import java.util.Arrays; +import java.util.HashSet; + +import javax.annotation.PostConstruct; + +import org.baeldung.persistence.dao.OrganizationRepository; +import org.baeldung.persistence.dao.PrivilegeRepository; +import org.baeldung.persistence.dao.RoleRepository; +import org.baeldung.persistence.dao.UserRepository; +import org.baeldung.persistence.model.Organization; +import org.baeldung.persistence.model.Privilege; +import org.baeldung.persistence.model.Role; +import org.baeldung.persistence.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class SetupData { + @Autowired + private UserRepository userRepository; + + @Autowired + private RoleRepository roleRepository; + + @Autowired + private PrivilegeRepository privilegeRepository; + + @Autowired + private OrganizationRepository organizationRepository; + + @PostConstruct + public void init() { + initPrivileges(); + initRoles(); + initOrganizations(); + initUsers(); + } + + private void initUsers() { + final Role role1 = roleRepository.findByName("USER_ROLE"); + final Role role2 = roleRepository.findByName("ADMIN_ROLE"); + // + final User user1 = new User(); + user1.setUsername("john"); + user1.setPassword("123"); + user1.setRoles(new HashSet(Arrays.asList(role1))); + user1.setOrganization(organizationRepository.findByName("FirstOrg")); + userRepository.save(user1); + // + final User user2 = new User(); + user2.setUsername("tom"); + user2.setPassword("111"); + user2.setRoles(new HashSet(Arrays.asList(role2))); + user2.setOrganization(organizationRepository.findByName("SecondOrg")); + userRepository.save(user2); + } + + private void initOrganizations() { + final Organization org1 = new Organization("FirstOrg"); + organizationRepository.save(org1); + // + final Organization org2 = new Organization("SecondOrg"); + organizationRepository.save(org2); + + } + + private void initRoles() { + final Privilege privilege1 = privilegeRepository.findByName("FOO_READ_PRIVILEGE"); + final Privilege privilege2 = privilegeRepository.findByName("FOO_WRITE_PRIVILEGE"); + // + final Role role1 = new Role("USER_ROLE"); + role1.setPrivileges(new HashSet(Arrays.asList(privilege1))); + roleRepository.save(role1); + // + final Role role2 = new Role("ADMIN_ROLE"); + role2.setPrivileges(new HashSet(Arrays.asList(privilege1, privilege2))); + roleRepository.save(role2); + } + + private void initPrivileges() { + final Privilege privilege1 = new Privilege("FOO_READ_PRIVILEGE"); + privilegeRepository.save(privilege1); + // + final Privilege privilege2 = new Privilege("FOO_WRITE_PRIVILEGE"); + privilegeRepository.save(privilege2); + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/OrganizationRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/OrganizationRepository.java new file mode 100644 index 0000000000..a20d24057b --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/OrganizationRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.Organization; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface OrganizationRepository extends JpaRepository { + + public Organization findByName(String name); + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java new file mode 100644 index 0000000000..edf9002c3d --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.Privilege; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PrivilegeRepository extends JpaRepository { + + public Privilege findByName(String name); + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/RoleRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/RoleRepository.java new file mode 100644 index 0000000000..408720fe9c --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/RoleRepository.java @@ -0,0 +1,9 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.Role; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface RoleRepository extends JpaRepository { + public Role findByName(String name); + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java new file mode 100644 index 0000000000..679dd6c363 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/UserRepository.java @@ -0,0 +1,10 @@ +package org.baeldung.persistence.dao; + +import org.baeldung.persistence.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { + + User findByUsername(final String username); + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Foo.java new file mode 100644 index 0000000000..29c19cf22e --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Foo.java @@ -0,0 +1,94 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false) + private String name; + + // + + public Foo() { + super(); + } + + public Foo(String name) { + super(); + this.name = name; + } + + // + + 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 String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Foo other = (Foo) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Organization.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Organization.java new file mode 100644 index 0000000000..645285b5e9 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Organization.java @@ -0,0 +1,95 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Organization { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String name; + + // + + public Organization() { + super(); + } + + public Organization(String name) { + super(); + this.name = name; + } + + // + + 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 String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Organization [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Organization other = (Organization) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Privilege.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Privilege.java new file mode 100644 index 0000000000..ff3ae62c25 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Privilege.java @@ -0,0 +1,95 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Privilege { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String name; + + // + + public Privilege() { + super(); + } + + public Privilege(String name) { + super(); + this.name = name; + } + + // + + 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 String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Privilege [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Privilege other = (Privilege) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Role.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Role.java new file mode 100644 index 0000000000..f4589315b9 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Role.java @@ -0,0 +1,121 @@ +package org.baeldung.persistence.model; + +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; + +@Entity +public class Role { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String name; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "roles_privileges", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")) + private Set privileges; + + // + + public Role() { + super(); + } + + public Role(String name) { + super(); + this.name = name; + } + + // + + 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; + } + + public Set getPrivileges() { + return privileges; + } + + public void setPrivileges(Set privileges) { + this.privileges = privileges; + } + + // + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Role [id=").append(id).append(", name=").append(name).append(", privileges=").append(privileges).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + result = (prime * result) + ((privileges == null) ? 0 : privileges.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Role other = (Role) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + if (privileges == null) { + if (other.privileges != null) { + return false; + } + } else if (!privileges.equals(other.privileges)) { + return false; + } + return true; + } + +} \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java new file mode 100644 index 0000000000..995c62d08f --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java @@ -0,0 +1,198 @@ +package org.baeldung.persistence.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +@Entity +public class User implements UserDetails { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(nullable = false, unique = true) + private String username; + + private String password; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) + private Set roles; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "organization_id", referencedColumnName = "id") + private Organization organization; + + // + + public User() { + super(); + } + + // + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Override + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Set getRoles() { + return roles; + } + + public void setRoles(Set roles) { + this.roles = roles; + } + + public Organization getOrganization() { + return organization; + } + + public void setOrganization(Organization organization) { + this.organization = organization; + } + + // + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append(", roles=").append(roles).append(", organization=").append(organization).append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + ((id == null) ? 0 : id.hashCode()); + result = (prime * result) + ((organization == null) ? 0 : organization.hashCode()); + result = (prime * result) + ((password == null) ? 0 : password.hashCode()); + result = (prime * result) + ((roles == null) ? 0 : roles.hashCode()); + result = (prime * result) + ((username == null) ? 0 : username.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final User other = (User) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + if (organization == null) { + if (other.organization != null) { + return false; + } + } else if (!organization.equals(other.organization)) { + return false; + } + if (password == null) { + if (other.password != null) { + return false; + } + } else if (!password.equals(other.password)) { + return false; + } + if (roles == null) { + if (other.roles != null) { + return false; + } + } else if (!roles.equals(other.roles)) { + return false; + } + if (username == null) { + if (other.username != null) { + return false; + } + } else if (!username.equals(other.username)) { + return false; + } + return true; + } + + // + + @Override + public Collection getAuthorities() { + final List authorities = new ArrayList(); + for (final Role role : this.getRoles()) { + for (final Privilege privilege : role.getPrivileges()) { + authorities.add(new SimpleGrantedAuthority(privilege.getName())); + } + } + return authorities; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionHandler.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionHandler.java new file mode 100644 index 0000000000..e040a0b109 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionHandler.java @@ -0,0 +1,22 @@ +package org.baeldung.security; + +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; +import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; +import org.springframework.security.authentication.AuthenticationTrustResolver; +import org.springframework.security.authentication.AuthenticationTrustResolverImpl; +import org.springframework.security.core.Authentication; + +public class CustomMethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler { + private final AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); + + @Override + protected MethodSecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, MethodInvocation invocation) { + // final CustomMethodSecurityExpressionRoot root = new CustomMethodSecurityExpressionRoot(authentication); + final MySecurityExpressionRoot root = new MySecurityExpressionRoot(authentication); + root.setPermissionEvaluator(getPermissionEvaluator()); + root.setTrustResolver(this.trustResolver); + root.setRoleHierarchy(getRoleHierarchy()); + return root; + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java new file mode 100644 index 0000000000..a3f4644592 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java @@ -0,0 +1,50 @@ +package org.baeldung.security; + +import org.baeldung.persistence.model.User; +import org.springframework.security.access.expression.SecurityExpressionRoot; +import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; +import org.springframework.security.core.Authentication; + +public class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations { + + private Object filterObject; + private Object returnObject; + + public CustomMethodSecurityExpressionRoot(Authentication authentication) { + super(authentication); + } + + // + public boolean isMember(Long OrganizationId) { + final User user = (User) this.getPrincipal(); + return user.getOrganization().getId().longValue() == OrganizationId.longValue(); + } + + // + + @Override + public Object getFilterObject() { + return this.filterObject; + } + + @Override + public Object getReturnObject() { + return this.returnObject; + } + + @Override + public Object getThis() { + return this; + } + + @Override + public void setFilterObject(Object obj) { + this.filterObject = obj; + } + + @Override + public void setReturnObject(Object obj) { + this.returnObject = obj; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java new file mode 100644 index 0000000000..e81f9f8939 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java @@ -0,0 +1,47 @@ +package org.baeldung.security; + +import java.io.Serializable; + +import org.springframework.security.access.PermissionEvaluator; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; + +public class CustomPermissionEvaluator implements PermissionEvaluator { + + @Override + public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) { + System.out.println(auth); + if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)) { + return false; + } + String targetType = ""; + if (targetDomainObject instanceof String) { + targetType = targetDomainObject.toString().toUpperCase(); + } else { + targetType = targetDomainObject.getClass().getSimpleName().toUpperCase(); + System.out.println(targetType); + } + return hasPrivilege(auth, targetType, permission.toString().toUpperCase()); + } + + @Override + public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) { + if ((auth == null) || (targetType == null) || !(permission instanceof String)) { + return false; + } + return hasPrivilege(auth, targetType.toUpperCase(), permission.toString().toUpperCase()); + } + + private boolean hasPrivilege(Authentication auth, String targetType, String permission) { + for (final GrantedAuthority grantedAuth : auth.getAuthorities()) { + System.out.println("here " + grantedAuth); + if (grantedAuth.getAuthority().startsWith(targetType)) { + if (grantedAuth.getAuthority().contains(permission)) { + return true; + } + } + } + return false; + } + +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java new file mode 100644 index 0000000000..a09d166798 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java @@ -0,0 +1,203 @@ +package org.baeldung.security; + +import java.io.Serializable; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import org.baeldung.persistence.model.User; +import org.springframework.security.access.PermissionEvaluator; +import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; +import org.springframework.security.access.hierarchicalroles.RoleHierarchy; +import org.springframework.security.authentication.AuthenticationTrustResolver; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; + +public class MySecurityExpressionRoot implements MethodSecurityExpressionOperations { + protected final Authentication authentication; + private AuthenticationTrustResolver trustResolver; + private RoleHierarchy roleHierarchy; + private Set roles; + private String defaultRolePrefix = "ROLE_"; + + public final boolean permitAll = true; + public final boolean denyAll = false; + private PermissionEvaluator permissionEvaluator; + public final String read = "read"; + public final String write = "write"; + public final String create = "create"; + public final String delete = "delete"; + public final String admin = "administration"; + + // + + private Object filterObject; + private Object returnObject; + + public MySecurityExpressionRoot(Authentication authentication) { + if (authentication == null) { + throw new IllegalArgumentException("Authentication object cannot be null"); + } + this.authentication = authentication; + } + + @Override + public final boolean hasAuthority(String authority) { + throw new RuntimeException("method hasAuthority() not allowed"); + } + + @Override + public final boolean hasAnyAuthority(String... authorities) { + return hasAnyAuthorityName(null, authorities); + } + + @Override + public final boolean hasRole(String role) { + return hasAnyRole(role); + } + + @Override + public final boolean hasAnyRole(String... roles) { + return hasAnyAuthorityName(defaultRolePrefix, roles); + } + + private boolean hasAnyAuthorityName(String prefix, String... roles) { + final Set roleSet = getAuthoritySet(); + + for (final String role : roles) { + final String defaultedRole = getRoleWithDefaultPrefix(prefix, role); + if (roleSet.contains(defaultedRole)) { + return true; + } + } + + return false; + } + + @Override + public final Authentication getAuthentication() { + return authentication; + } + + @Override + public final boolean permitAll() { + return true; + } + + @Override + public final boolean denyAll() { + return false; + } + + @Override + public final boolean isAnonymous() { + return trustResolver.isAnonymous(authentication); + } + + @Override + public final boolean isAuthenticated() { + return !isAnonymous(); + } + + @Override + public final boolean isRememberMe() { + return trustResolver.isRememberMe(authentication); + } + + @Override + public final boolean isFullyAuthenticated() { + return !trustResolver.isAnonymous(authentication) && !trustResolver.isRememberMe(authentication); + } + + public Object getPrincipal() { + return authentication.getPrincipal(); + } + + public void setTrustResolver(AuthenticationTrustResolver trustResolver) { + this.trustResolver = trustResolver; + } + + public void setRoleHierarchy(RoleHierarchy roleHierarchy) { + this.roleHierarchy = roleHierarchy; + } + + public void setDefaultRolePrefix(String defaultRolePrefix) { + this.defaultRolePrefix = defaultRolePrefix; + } + + private Set getAuthoritySet() { + if (roles == null) { + roles = new HashSet(); + Collection userAuthorities = authentication.getAuthorities(); + + if (roleHierarchy != null) { + userAuthorities = roleHierarchy.getReachableGrantedAuthorities(userAuthorities); + } + + roles = AuthorityUtils.authorityListToSet(userAuthorities); + } + + return roles; + } + + @Override + public boolean hasPermission(Object target, Object permission) { + return permissionEvaluator.hasPermission(authentication, target, permission); + } + + @Override + public boolean hasPermission(Object targetId, String targetType, Object permission) { + return permissionEvaluator.hasPermission(authentication, (Serializable) targetId, targetType, permission); + } + + public void setPermissionEvaluator(PermissionEvaluator permissionEvaluator) { + this.permissionEvaluator = permissionEvaluator; + } + + private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) { + if (role == null) { + return role; + } + if ((defaultRolePrefix == null) || (defaultRolePrefix.length() == 0)) { + return role; + } + if (role.startsWith(defaultRolePrefix)) { + return role; + } + return defaultRolePrefix + role; + } + + // + public boolean isMember(Long OrganizationId) { + final User user = (User) this.getPrincipal(); + return user.getOrganization().getId().longValue() == OrganizationId.longValue(); + } + + // + + @Override + public Object getFilterObject() { + return this.filterObject; + } + + @Override + public Object getReturnObject() { + return this.returnObject; + } + + @Override + public Object getThis() { + return this; + } + + @Override + public void setFilterObject(Object obj) { + this.filterObject = obj; + } + + @Override + public void setReturnObject(Object obj) { + this.returnObject = obj; + } +} \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java new file mode 100644 index 0000000000..19276a906e --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -0,0 +1,31 @@ +package org.baeldung.security; + +import org.baeldung.persistence.dao.UserRepository; +import org.baeldung.persistence.model.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + private UserRepository userRepository; + + public MyUserDetailsService() { + super(); + } + + // API + + @Override + public UserDetails loadUserByUsername(final String username) { + final User user = userRepository.findByUsername(username); + if (user == null) { + throw new UsernameNotFoundException(username); + } + return user; + } +} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java b/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java new file mode 100644 index 0000000000..7e279907c6 --- /dev/null +++ b/spring-security-custom-permission/src/main/java/org/baeldung/web/MainController.java @@ -0,0 +1,57 @@ +package org.baeldung.web; + +import org.baeldung.persistence.dao.OrganizationRepository; +import org.baeldung.persistence.model.Foo; +import org.baeldung.persistence.model.Organization; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +@Controller +public class MainController { + + @Autowired + private OrganizationRepository organizationRepository; + + @PreAuthorize("hasPermission('Foo', 'read')") + @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") + @ResponseBody + public Foo findById(@PathVariable final long id) { + return new Foo("Sample"); + } + + @PreAuthorize("hasPermission(#foo, 'write')") + @RequestMapping(method = RequestMethod.POST, value = "/foos") + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo create(@RequestBody final Foo foo) { + return foo; + } + + // + + @PreAuthorize("hasAuthority('FOO_READ_PRIVILEGE')") + @RequestMapping(method = RequestMethod.GET, value = "/foos") + @ResponseBody + public Foo findFooByName(@RequestParam final String name) { + return new Foo(name); + } + + // + + @PreAuthorize("isMember(#id)") + @RequestMapping(method = RequestMethod.GET, value = "/organizations/{id}") + @ResponseBody + public Organization findOrgById(@PathVariable final long id) { + return organizationRepository.findOne(id); + } + +} diff --git a/spring-security-custom-permission/src/main/resources/application.properties b/spring-security-custom-permission/src/main/resources/application.properties new file mode 100644 index 0000000000..0b40f62fa9 --- /dev/null +++ b/spring-security-custom-permission/src/main/resources/application.properties @@ -0,0 +1,9 @@ +server.port=8081 +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1 +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.database=H2 +spring.jpa.show-sql=false +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/resources/templates/index.html b/spring-security-custom-permission/src/main/resources/templates/index.html new file mode 100644 index 0000000000..8e7394ad6a --- /dev/null +++ b/spring-security-custom-permission/src/main/resources/templates/index.html @@ -0,0 +1,21 @@ + + + + +Spring Security Thymeleaf + + + + + +
+ Welcome +
+ + \ No newline at end of file diff --git a/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java new file mode 100644 index 0000000000..80b1390083 --- /dev/null +++ b/spring-security-custom-permission/src/test/java/org/baeldung/web/LiveTest.java @@ -0,0 +1,67 @@ +package org.baeldung.web; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.baeldung.persistence.model.Foo; +import org.junit.Test; +import org.springframework.http.MediaType; + +import com.jayway.restassured.RestAssured; +import com.jayway.restassured.authentication.FormAuthConfig; +import com.jayway.restassured.response.Response; +import com.jayway.restassured.specification.RequestSpecification; + +public class LiveTest { + + private final FormAuthConfig formAuthConfig = new FormAuthConfig("http://localhost:8081/login", "username", "password"); + + @Test + public void givenUserWithReadPrivilegeAndHasPermission_whenGetFooById_thenOK() { + final Response response = givenAuth("john", "123").get("http://localhost:8081/foos/1"); + assertEquals(200, response.getStatusCode()); + assertTrue(response.asString().contains("id")); + } + + @Test + public void givenUserWithNoWritePrivilegeAndHasPermission_whenPostFoo_thenForbidden() { + final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8081/foos"); + assertEquals(403, response.getStatusCode()); + } + + @Test + public void givenUserWithWritePrivilegeAndHasPermission_whenPostFoo_thenOk() { + final Response response = givenAuth("tom", "111").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8081/foos"); + assertEquals(201, response.getStatusCode()); + assertTrue(response.asString().contains("id")); + } + + // + + @Test + public void givenUserMemberInOrganization_whenGetOrganization_thenOK() { + final Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/1"); + assertEquals(200, response.getStatusCode()); + assertTrue(response.asString().contains("id")); + } + + @Test + public void givenUserMemberNotInOrganization_whenGetOrganization_thenForbidden() { + final Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/2"); + assertEquals(403, response.getStatusCode()); + } + + // + + @Test + public void givenDisabledSecurityExpression_whenGetFooByName_thenError() { + final Response response = givenAuth("john", "123").get("http://localhost:8081/foos?name=sample"); + assertEquals(500, response.getStatusCode()); + assertTrue(response.asString().contains("method hasAuthority() not allowed")); + } + + // + private RequestSpecification givenAuth(String username, String password) { + return RestAssured.given().auth().form(username, password, formAuthConfig); + } +} \ No newline at end of file From b7d0b2947a0bffd2c89639425dd5a7b6bd91d4cb Mon Sep 17 00:00:00 2001 From: Ivan Date: Wed, 30 Mar 2016 15:06:37 +0200 Subject: [PATCH 32/47] Add file upload example --- .../spring/web/config/ClientWebConfig.java | 2 - .../web/config/MainWebAppInitializer.java | 3 +- .../baeldung/spring/web/config/WebConfig.java | 18 ++--- .../web/controller/FileUploadController.java | 70 +++---------------- .../webapp/WEB-INF/view/fileUploadForm.jsp | 22 ++++-- .../webapp/WEB-INF/view/fileUploadView.jsp | 22 +++++- 6 files changed, 55 insertions(+), 82 deletions(-) diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java index 3f451f4259..6084943ddd 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java @@ -36,8 +36,6 @@ public class ClientWebConfig extends WebMvcConfigurerAdapter { super.addViewControllers(registry); registry.addViewController("/sample.html"); - registry.addViewController("/fileUpload.html"); - registry.addViewController("/fileUploadForm.html"); } @Bean diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java index 9dd9ae98b0..ad37bbec5e 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java @@ -14,8 +14,7 @@ import org.springframework.web.servlet.DispatcherServlet; public class MainWebAppInitializer implements WebApplicationInitializer { - private static final String TMP_FOLDER = "C:/Users/ivan/Desktop/tmp"; // 5 - // MB + private static final String TMP_FOLDER = "C:/Users/ivan/Desktop/tmp"; private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB /** diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java index b7d87dffbc..cd9ae582d8 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java @@ -4,6 +4,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; @@ -27,15 +28,14 @@ public class WebConfig extends WebMvcConfigurerAdapter { // return new StandardServletMultipartResolver(); // } - // @Bean(name = "multipartResolver") - // public CommonsMultipartResolver multipartResolver() { - // - // final CommonsMultipartResolver multipartResolver = new - // CommonsMultipartResolver(); - // multipartResolver.setMaxUploadSize(100000); - // - // return multipartResolver; - // } + @Bean(name = "multipartResolver") + public CommonsMultipartResolver multipartResolver() { + + final CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(100000); + + return multipartResolver; + } @Override public void addViewControllers(final ViewControllerRegistry registry) { diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java b/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java index a25a620c8b..6f557adf0f 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java +++ b/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java @@ -1,18 +1,5 @@ package org.baeldung.web.controller; -import java.io.File; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; @@ -23,58 +10,23 @@ import org.springframework.web.multipart.MultipartFile; @Controller public class FileUploadController { - @RequestMapping(value = "/addFile1", method = RequestMethod.POST) + @RequestMapping(value = "/fileUpload", method = RequestMethod.GET) + public String displayForm() { + + return "fileUploadForm"; + } + + @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public String submit(@RequestParam("file") final MultipartFile file, final ModelMap modelMap) { - modelMap.addAttribute("fileName", file.getOriginalFilename()); - modelMap.addAttribute("fileType", file.getContentType()); - + modelMap.addAttribute("file", file); return "fileUploadView"; } - @RequestMapping(value = "/addFile2", method = RequestMethod.POST) - public String submit(final HttpServletRequest request, final HttpServletResponse response, - final ModelMap modelMap) { - - final String TEMP_PATH = "/tmp/"; - - try { - - final DiskFileItemFactory factory = new DiskFileItemFactory(); - - // Configure a repository (to ensure a secure temp location is used) - final File repository = new File(TEMP_PATH); - factory.setRepository(repository); - - // Create a new file upload handler - final ServletFileUpload upload = new ServletFileUpload(factory); - - // Parse the request - final List items = upload.parseRequest(request); - - final Iterator iter = items.iterator(); - - while (iter.hasNext()) { - - final FileItem item = iter.next(); - - if (!item.isFormField()) { - - final File targetFile = new File(TEMP_PATH + item.getName()); - FileUtils.copyInputStreamToFile(item.getInputStream(), targetFile); - - modelMap.addAttribute("fileName", item.getName()); - modelMap.addAttribute("fileType", item.getContentType()); - } - } - - } catch (final FileUploadException e) { - e.printStackTrace(); - - } catch (final IOException e) { - e.printStackTrace(); - } + @RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST) + public String submit(@RequestParam("files") final MultipartFile[] files, final ModelMap modelMap) { + modelMap.addAttribute("files", files); return "fileUploadView"; } } diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp index 05a7e25a02..371acdc0ed 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp @@ -8,13 +8,13 @@ -

Enter The File to Upload (MultipartFile handling)

+

Enter The File to Upload

- + - + @@ -24,16 +24,24 @@ -
+
-

Enter The File to Upload (HttpServletRequest handling)

+

Enter The Files to Upload (Multiple files)

- +
Select a file to uploadSelect a file to upload (Single file)
- + + + + + + + + + diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadView.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadView.jsp index 779c26a597..d6f748c6af 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadView.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadView.jsp @@ -5,16 +5,32 @@ Spring MVC File Upload -

Submitted File

+ +

Submitted File (Single)

Select a file to upload
Select a file to upload
Select a file to upload
- + - +
OriginalFileName :${fileName}${file.originalFilename}
Type :${fileType}${file.contentType}
+
+ +

Submitted Files (Multiple)

+ + + + + + + + + + + +
OriginalFileName :${file.originalFilename}
Type :${file.contentType}
\ No newline at end of file From 697c349f2909de380b141ea53d8ddd67ecfaec8f Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 30 Mar 2016 19:15:58 +0200 Subject: [PATCH 33/47] remove role from hierarchy --- .../org/baeldung/persistence/SetupData.java | 27 +--- .../persistence/dao/RoleRepository.java | 9 -- .../org/baeldung/persistence/model/Role.java | 121 ------------------ .../org/baeldung/persistence/model/User.java | 87 ++++++------- 4 files changed, 46 insertions(+), 198 deletions(-) delete mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/RoleRepository.java delete mode 100644 spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Role.java diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java index fa6d4c42ee..47616ca61a 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/SetupData.java @@ -7,11 +7,9 @@ import javax.annotation.PostConstruct; import org.baeldung.persistence.dao.OrganizationRepository; import org.baeldung.persistence.dao.PrivilegeRepository; -import org.baeldung.persistence.dao.RoleRepository; import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.model.Organization; import org.baeldung.persistence.model.Privilege; -import org.baeldung.persistence.model.Role; import org.baeldung.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -21,9 +19,6 @@ public class SetupData { @Autowired private UserRepository userRepository; - @Autowired - private RoleRepository roleRepository; - @Autowired private PrivilegeRepository privilegeRepository; @@ -33,26 +28,25 @@ public class SetupData { @PostConstruct public void init() { initPrivileges(); - initRoles(); initOrganizations(); initUsers(); } private void initUsers() { - final Role role1 = roleRepository.findByName("USER_ROLE"); - final Role role2 = roleRepository.findByName("ADMIN_ROLE"); + final Privilege privilege1 = privilegeRepository.findByName("FOO_READ_PRIVILEGE"); + final Privilege privilege2 = privilegeRepository.findByName("FOO_WRITE_PRIVILEGE"); // final User user1 = new User(); user1.setUsername("john"); user1.setPassword("123"); - user1.setRoles(new HashSet(Arrays.asList(role1))); + user1.setPrivileges(new HashSet(Arrays.asList(privilege1))); user1.setOrganization(organizationRepository.findByName("FirstOrg")); userRepository.save(user1); // final User user2 = new User(); user2.setUsername("tom"); user2.setPassword("111"); - user2.setRoles(new HashSet(Arrays.asList(role2))); + user2.setPrivileges(new HashSet(Arrays.asList(privilege1, privilege2))); user2.setOrganization(organizationRepository.findByName("SecondOrg")); userRepository.save(user2); } @@ -66,19 +60,6 @@ public class SetupData { } - private void initRoles() { - final Privilege privilege1 = privilegeRepository.findByName("FOO_READ_PRIVILEGE"); - final Privilege privilege2 = privilegeRepository.findByName("FOO_WRITE_PRIVILEGE"); - // - final Role role1 = new Role("USER_ROLE"); - role1.setPrivileges(new HashSet(Arrays.asList(privilege1))); - roleRepository.save(role1); - // - final Role role2 = new Role("ADMIN_ROLE"); - role2.setPrivileges(new HashSet(Arrays.asList(privilege1, privilege2))); - roleRepository.save(role2); - } - private void initPrivileges() { final Privilege privilege1 = new Privilege("FOO_READ_PRIVILEGE"); privilegeRepository.save(privilege1); diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/RoleRepository.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/RoleRepository.java deleted file mode 100644 index 408720fe9c..0000000000 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/dao/RoleRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.Role; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface RoleRepository extends JpaRepository { - public Role findByName(String name); - -} diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Role.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Role.java deleted file mode 100644 index f4589315b9..0000000000 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/Role.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.baeldung.persistence.model; - -import java.util.Set; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; - -@Entity -public class Role { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Column(nullable = false, unique = true) - private String name; - - @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "roles_privileges", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")) - private Set privileges; - - // - - public Role() { - super(); - } - - public Role(String name) { - super(); - this.name = name; - } - - // - - 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; - } - - public Set getPrivileges() { - return privileges; - } - - public void setPrivileges(Set privileges) { - this.privileges = privileges; - } - - // - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Role [id=").append(id).append(", name=").append(name).append(", privileges=").append(privileges).append("]"); - return builder.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + ((id == null) ? 0 : id.hashCode()); - result = (prime * result) + ((name == null) ? 0 : name.hashCode()); - result = (prime * result) + ((privileges == null) ? 0 : privileges.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Role other = (Role) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (privileges == null) { - if (other.privileges != null) { - return false; - } - } else if (!privileges.equals(other.privileges)) { - return false; - } - return true; - } - -} \ No newline at end of file diff --git a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java index 995c62d08f..86b81cdcee 100644 --- a/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-security-custom-permission/src/main/java/org/baeldung/persistence/model/User.java @@ -35,8 +35,8 @@ public class User implements UserDetails { private String password; @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) - private Set roles; + @JoinTable(name = "users_privileges", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")) + private Set privileges; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "organization_id", referencedColumnName = "id") @@ -75,12 +75,12 @@ public class User implements UserDetails { this.password = password; } - public Set getRoles() { - return roles; + public Set getPrivileges() { + return privileges; } - public void setRoles(Set roles) { - this.roles = roles; + public void setPrivileges(Set privileges) { + this.privileges = privileges; } public Organization getOrganization() { @@ -93,10 +93,41 @@ public class User implements UserDetails { // + @Override + public Collection getAuthorities() { + final List authorities = new ArrayList(); + for (final Privilege privilege : this.getPrivileges()) { + authorities.add(new SimpleGrantedAuthority(privilege.getName())); + } + return authorities; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + // + @Override public String toString() { final StringBuilder builder = new StringBuilder(); - builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append(", roles=").append(roles).append(", organization=").append(organization).append("]"); + builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append(", privileges=").append(privileges).append(", organization=").append(organization).append("]"); return builder.toString(); } @@ -107,7 +138,7 @@ public class User implements UserDetails { result = (prime * result) + ((id == null) ? 0 : id.hashCode()); result = (prime * result) + ((organization == null) ? 0 : organization.hashCode()); result = (prime * result) + ((password == null) ? 0 : password.hashCode()); - result = (prime * result) + ((roles == null) ? 0 : roles.hashCode()); + result = (prime * result) + ((privileges == null) ? 0 : privileges.hashCode()); result = (prime * result) + ((username == null) ? 0 : username.hashCode()); return result; } @@ -145,11 +176,11 @@ public class User implements UserDetails { } else if (!password.equals(other.password)) { return false; } - if (roles == null) { - if (other.roles != null) { + if (privileges == null) { + if (other.privileges != null) { return false; } - } else if (!roles.equals(other.roles)) { + } else if (!privileges.equals(other.privileges)) { return false; } if (username == null) { @@ -161,38 +192,4 @@ public class User implements UserDetails { } return true; } - - // - - @Override - public Collection getAuthorities() { - final List authorities = new ArrayList(); - for (final Role role : this.getRoles()) { - for (final Privilege privilege : role.getPrivileges()) { - authorities.add(new SimpleGrantedAuthority(privilege.getName())); - } - } - return authorities; - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isEnabled() { - return true; - } - } From f7594ee89cd7f919ab96bac7456238e94cc40c2f Mon Sep 17 00:00:00 2001 From: ankur-singhal Date: Thu, 31 Mar 2016 17:50:47 +0530 Subject: [PATCH 34/47] XStream-XML to Object XStream-XML to Object --- xstream-xmlToObject/.project | 23 ++++++++ .../data-file-alias-field-complex.xml | 15 +++++ xstream-xmlToObject/data-file-alias-field.xml | 5 ++ .../data-file-alias-implicit-collection.xml | 13 ++++ xstream-xmlToObject/data-file-alias.xml | 5 ++ .../data-file-ignore-field.xml | 6 ++ xstream-xmlToObject/data-file.xml | 5 ++ xstream-xmlToObject/pom.xml | 36 +++++++++++ .../baeldung/annotation/pojo/Customer.java | 46 +++++++++++++++ .../annotation/pojo/CustomerOmitField.java | 50 ++++++++++++++++ .../baeldung/complex/pojo/ContactDetails.java | 46 +++++++++++++++ .../com/baeldung/complex/pojo/Customer.java | 57 ++++++++++++++++++ .../collection/pojo/ContactDetails.java | 46 +++++++++++++++ .../implicit/collection/pojo/Customer.java | 59 +++++++++++++++++++ .../initializer/SimpleXstreamInitializer.java | 19 ++++++ .../main/java/com/baeldung/pojo/Customer.java | 42 +++++++++++++ .../utility/SimpleDataGeneration.java | 19 ++++++ .../src/main/resources/log4j.properties | 16 +++++ .../ComplexXmlToObjectAnnotationTest.java | 38 ++++++++++++ ...lexXmlToObjectAttributeCollectionTest.java | 42 +++++++++++++ .../ComplexXmlToObjectCollectionTest.java | 39 ++++++++++++ .../pojo/test/XmlToObjectAliasTest.java | 37 ++++++++++++ .../pojo/test/XmlToObjectAnnotationTest.java | 38 ++++++++++++ .../pojo/test/XmlToObjectFieldAliasTest.java | 39 ++++++++++++ .../test/XmlToObjectIgnoreFieldsTest.java | 38 ++++++++++++ .../baeldung/pojo/test/XmlToObjectTest.java | 46 +++++++++++++++ 26 files changed, 825 insertions(+) create mode 100644 xstream-xmlToObject/.project create mode 100644 xstream-xmlToObject/data-file-alias-field-complex.xml create mode 100644 xstream-xmlToObject/data-file-alias-field.xml create mode 100644 xstream-xmlToObject/data-file-alias-implicit-collection.xml create mode 100644 xstream-xmlToObject/data-file-alias.xml create mode 100644 xstream-xmlToObject/data-file-ignore-field.xml create mode 100644 xstream-xmlToObject/data-file.xml create mode 100644 xstream-xmlToObject/pom.xml create mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/Customer.java create mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java create mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/ContactDetails.java create mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/Customer.java create mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java create mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java create mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java create mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/pojo/Customer.java create mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/utility/SimpleDataGeneration.java create mode 100644 xstream-xmlToObject/src/main/resources/log4j.properties create mode 100644 xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java create mode 100644 xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java create mode 100644 xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java create mode 100644 xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java create mode 100644 xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java create mode 100644 xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java create mode 100644 xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java create mode 100644 xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java diff --git a/xstream-xmlToObject/.project b/xstream-xmlToObject/.project new file mode 100644 index 0000000000..133b92d690 --- /dev/null +++ b/xstream-xmlToObject/.project @@ -0,0 +1,23 @@ + + + xstream-xmlToObject + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/xstream-xmlToObject/data-file-alias-field-complex.xml b/xstream-xmlToObject/data-file-alias-field-complex.xml new file mode 100644 index 0000000000..2235aa7044 --- /dev/null +++ b/xstream-xmlToObject/data-file-alias-field-complex.xml @@ -0,0 +1,15 @@ + + XStream + Java + 1986-02-14 04:14:05.874 UTC + + + 6673543265 + 0124-2460311 + + + 4676543565 + 0120-223312 + + + \ No newline at end of file diff --git a/xstream-xmlToObject/data-file-alias-field.xml b/xstream-xmlToObject/data-file-alias-field.xml new file mode 100644 index 0000000000..9bc1d0990a --- /dev/null +++ b/xstream-xmlToObject/data-file-alias-field.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file diff --git a/xstream-xmlToObject/data-file-alias-implicit-collection.xml b/xstream-xmlToObject/data-file-alias-implicit-collection.xml new file mode 100644 index 0000000000..d8731900b9 --- /dev/null +++ b/xstream-xmlToObject/data-file-alias-implicit-collection.xml @@ -0,0 +1,13 @@ + + XStream + Java + 1986-02-14 04:14:20.541 UTC + + 6673543265 + 0124-2460311 + + + 4676543565 + 0120-223312 + + \ No newline at end of file diff --git a/xstream-xmlToObject/data-file-alias.xml b/xstream-xmlToObject/data-file-alias.xml new file mode 100644 index 0000000000..964157f1dd --- /dev/null +++ b/xstream-xmlToObject/data-file-alias.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file diff --git a/xstream-xmlToObject/data-file-ignore-field.xml b/xstream-xmlToObject/data-file-ignore-field.xml new file mode 100644 index 0000000000..865e93d4b4 --- /dev/null +++ b/xstream-xmlToObject/data-file-ignore-field.xml @@ -0,0 +1,6 @@ + + XStream + Java + 1986-02-14 04:14:20.541 UTC + XStream Java + \ No newline at end of file diff --git a/xstream-xmlToObject/data-file.xml b/xstream-xmlToObject/data-file.xml new file mode 100644 index 0000000000..59f2ea1cca --- /dev/null +++ b/xstream-xmlToObject/data-file.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file diff --git a/xstream-xmlToObject/pom.xml b/xstream-xmlToObject/pom.xml new file mode 100644 index 0000000000..4828ccb569 --- /dev/null +++ b/xstream-xmlToObject/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + + com.baeldung + xstream-xmlToObject + 0.0.1-SNAPSHOT + jar + + xstream-xmlToObject + http://maven.apache.org + + + UTF-8 + + + + + com.thoughtworks.xstream + xstream + 1.4.5 + + + + junit + junit + 4.12 + + + + log4j + log4j + 1.2.17 + + + diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/Customer.java b/xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/Customer.java new file mode 100644 index 0000000000..42d1d039b0 --- /dev/null +++ b/xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/Customer.java @@ -0,0 +1,46 @@ +package com.baeldung.annotation.pojo; + +import java.util.Date; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("customer") +public class Customer { + + @XStreamAlias("fn") + private String firstName; + + private String lastName; + + private Date dob; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + + ", dob=" + dob + "]"; + } +} diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java b/xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java new file mode 100644 index 0000000000..881d7a5fc7 --- /dev/null +++ b/xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java @@ -0,0 +1,50 @@ +package com.baeldung.annotation.pojo; + +import java.util.Date; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamOmitField; + + +@XStreamAlias("customer") +public class CustomerOmitField { + + @XStreamOmitField + private String firstName; + + private String lastName; + + private Date dob; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + @Override + public String toString() { + return "CustomerOmitAnnotation [firstName=" + firstName + ", lastName=" + + lastName + ", dob=" + dob + "]"; + } + + +} diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/ContactDetails.java b/xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/ContactDetails.java new file mode 100644 index 0000000000..88e721a84b --- /dev/null +++ b/xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/ContactDetails.java @@ -0,0 +1,46 @@ +package com.baeldung.complex.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("ContactDetails") +public class ContactDetails { + + private String mobile; + + private String landline; + + @XStreamAsAttribute + private String contactType; + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getLandline() { + return landline; + } + + public void setLandline(String landline) { + this.landline = landline; + } + + public String getContactType() { + return contactType; + } + + public void setContactType(String contactType) { + this.contactType = contactType; + } + + @Override + public String toString() { + return "ContactDetails [mobile=" + mobile + ", landline=" + landline + + ", contactType=" + contactType + "]"; + } + +} diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/Customer.java b/xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/Customer.java new file mode 100644 index 0000000000..0cc3160c03 --- /dev/null +++ b/xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/Customer.java @@ -0,0 +1,57 @@ +package com.baeldung.complex.pojo; + +import java.util.Date; +import java.util.List; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("customer") +public class Customer { + + private String firstName; + + private String lastName; + + private Date dob; + + private List contactDetailsList; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + public List getContactDetailsList() { + return contactDetailsList; + } + + public void setContactDetailsList(List contactDetailsList) { + this.contactDetailsList = contactDetailsList; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + + "]"; + } +} diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java b/xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java new file mode 100644 index 0000000000..6d6a63bd7a --- /dev/null +++ b/xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java @@ -0,0 +1,46 @@ +package com.baeldung.implicit.collection.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("ContactDetails") +public class ContactDetails { + + private String mobile; + + private String landline; + + @XStreamAsAttribute + private String contactType; + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getLandline() { + return landline; + } + + public void setLandline(String landline) { + this.landline = landline; + } + + public String getContactType() { + return contactType; + } + + public void setContactType(String contactType) { + this.contactType = contactType; + } + + @Override + public String toString() { + return "ContactDetails [mobile=" + mobile + ", landline=" + landline + + ", contactType=" + contactType + "]"; + } + +} diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java b/xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java new file mode 100644 index 0000000000..acbeff165e --- /dev/null +++ b/xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java @@ -0,0 +1,59 @@ +package com.baeldung.implicit.collection.pojo; + +import java.util.Date; +import java.util.List; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamImplicit; + +@XStreamAlias("customer") +public class Customer { + + private String firstName; + + private String lastName; + + private Date dob; + + @XStreamImplicit + private List contactDetailsList; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + public List getContactDetailsList() { + return contactDetailsList; + } + + public void setContactDetailsList(List contactDetailsList) { + this.contactDetailsList = contactDetailsList; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + + "]"; + } +} diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java b/xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java new file mode 100644 index 0000000000..8281678bab --- /dev/null +++ b/xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java @@ -0,0 +1,19 @@ +package com.baeldung.initializer; + +import com.thoughtworks.xstream.XStream; + +public class SimpleXstreamInitializer { + + private static XStream xtreamInstance; + + public static XStream getXstreamInstance() { + if (xtreamInstance == null) { + synchronized (SimpleXstreamInitializer.class) { + if (xtreamInstance == null) { + xtreamInstance = new XStream(); + } + } + } + return xtreamInstance; + } +} \ No newline at end of file diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/pojo/Customer.java b/xstream-xmlToObject/src/main/java/com/baeldung/pojo/Customer.java new file mode 100644 index 0000000000..affed65fff --- /dev/null +++ b/xstream-xmlToObject/src/main/java/com/baeldung/pojo/Customer.java @@ -0,0 +1,42 @@ +package com.baeldung.pojo; + +import java.util.Date; + +public class Customer { + + private String firstName; + + private String lastName; + + private Date dob; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + + ", dob=" + dob + "]"; + } +} diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/utility/SimpleDataGeneration.java b/xstream-xmlToObject/src/main/java/com/baeldung/utility/SimpleDataGeneration.java new file mode 100644 index 0000000000..14ca25952f --- /dev/null +++ b/xstream-xmlToObject/src/main/java/com/baeldung/utility/SimpleDataGeneration.java @@ -0,0 +1,19 @@ +package com.baeldung.utility; + +import java.util.Calendar; + +import com.baeldung.pojo.Customer; + +public class SimpleDataGeneration { + + public static Customer generateData() { + Customer customer = new Customer(); + Calendar cal = Calendar.getInstance(); + cal.set(1986 , 01 , 14); + customer.setDob(cal.getTime()); + customer.setFirstName("Xstream"); + customer.setLastName("Java"); + + return customer; + } +} diff --git a/xstream-xmlToObject/src/main/resources/log4j.properties b/xstream-xmlToObject/src/main/resources/log4j.properties new file mode 100644 index 0000000000..9cdafc6bdb --- /dev/null +++ b/xstream-xmlToObject/src/main/resources/log4j.properties @@ -0,0 +1,16 @@ +# Root logger option +log4j.rootLogger=DEBUG, file + +# Redirect log messages to console +# log4j.appender.stdout=org.apache.log4j.ConsoleAppender +# log4j.appender.stdout.Target=System.out +# log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n + +# Redirect log messages to a log file, support file rolling. +log4j.appender.file=org.apache.log4j.RollingFileAppender +log4j.appender.file.File=D:\\Test\\xstream-application.log +log4j.appender.file.MaxFileSize=5MB +log4j.appender.file.MaxBackupIndex=10 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java new file mode 100644 index 0000000000..dff671b6a6 --- /dev/null +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java @@ -0,0 +1,38 @@ +package com.baeldung.pojo.test; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.complex.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; + +public class ComplexXmlToObjectAnnotationTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + xstream = SimpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + FileReader reader = new FileReader(new File("data-file-alias-field-complex.xml")); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getContactDetailsList()); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java new file mode 100644 index 0000000000..4494cc833d --- /dev/null +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java @@ -0,0 +1,42 @@ +package com.baeldung.pojo.test; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.implicit.collection.pojo.ContactDetails; +import com.baeldung.implicit.collection.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; + +public class ComplexXmlToObjectAttributeCollectionTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + xstream = SimpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + FileReader reader = new FileReader(new File("data-file-alias-implicit-collection.xml")); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getContactDetailsList()); + for(ContactDetails contactDetails : customer.getContactDetailsList()){ + Assert.assertNotNull(contactDetails.getContactType()); + } + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java new file mode 100644 index 0000000000..b72ba44eb5 --- /dev/null +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java @@ -0,0 +1,39 @@ +package com.baeldung.pojo.test; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.implicit.collection.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; + +public class ComplexXmlToObjectCollectionTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + xstream = SimpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + FileReader reader = new FileReader(new File("data-file-alias-implicit-collection.xml")); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getContactDetailsList()); + System.out.println(customer); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java new file mode 100644 index 0000000000..884071542e --- /dev/null +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java @@ -0,0 +1,37 @@ +package com.baeldung.pojo.test; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.XStream; + +public class XmlToObjectAliasTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + xstream = SimpleXstreamInitializer.getXstreamInstance(); + xstream.alias("customer" , Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + FileReader reader = new FileReader(new File("data-file-alias.xml")); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java new file mode 100644 index 0000000000..09bed7d24f --- /dev/null +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java @@ -0,0 +1,38 @@ +package com.baeldung.pojo.test; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.annotation.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; + +public class XmlToObjectAnnotationTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + xstream = SimpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + FileReader reader = new FileReader(new File("data-file-alias-field.xml")); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getFirstName()); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java new file mode 100644 index 0000000000..c613a6517c --- /dev/null +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java @@ -0,0 +1,39 @@ +package com.baeldung.pojo.test; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.XStream; + +public class XmlToObjectFieldAliasTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + xstream = SimpleXstreamInitializer.getXstreamInstance(); + xstream.alias("customer" , Customer.class); + xstream.aliasField("fn", Customer.class, "firstName"); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + FileReader reader = new FileReader(new File("data-file-alias-field.xml")); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getFirstName()); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java new file mode 100644 index 0000000000..aa88918402 --- /dev/null +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java @@ -0,0 +1,38 @@ +package com.baeldung.pojo.test; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.XStream; + +public class XmlToObjectIgnoreFieldsTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + xstream = SimpleXstreamInitializer.getXstreamInstance(); + xstream.alias("customer" , Customer.class); + xstream.ignoreUnknownElements(); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + FileReader reader = new FileReader(new File("data-file-ignore-field.xml")); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + System.out.println(customer); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java new file mode 100644 index 0000000000..cb7fc49b33 --- /dev/null +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java @@ -0,0 +1,46 @@ +package com.baeldung.pojo.test; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.baeldung.utility.SimpleDataGeneration; +import com.thoughtworks.xstream.XStream; + +public class XmlToObjectTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + xstream = SimpleXstreamInitializer.getXstreamInstance(); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + FileReader reader = new FileReader(new File("data-file.xml")); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void convertXmlToObjectFromString() { + Customer customer = SimpleDataGeneration.generateData(); + String dataXml = xstream.toXML(customer); + Customer convertedCustomer = (Customer) xstream.fromXML(dataXml); + Assert.assertNotNull(convertedCustomer); + } + + +} From c1566e58518a8adcf3d2814d17618268def45820 Mon Sep 17 00:00:00 2001 From: Thai Nguyen Date: Thu, 31 Mar 2016 20:02:10 +0700 Subject: [PATCH 35/47] remove connection pooling --- jooq-spring/pom.xml | 6 ------ .../jooq/introduction/PersistenceContext.java | 13 +++++-------- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/jooq-spring/pom.xml b/jooq-spring/pom.xml index 5465b86736..76198c4993 100644 --- a/jooq-spring/pom.xml +++ b/jooq-spring/pom.xml @@ -8,7 +8,6 @@ 3.7.3 1.4.191 - 2.4.4 4.2.5.RELEASE 1.7.18 1.1.3 @@ -29,11 +28,6 @@ h2 ${com.h2database.version}
- - com.zaxxer - HikariCP - ${com.zaxxer.HikariCP.version} - diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java index 4bcf3a527e..ee34c00679 100644 --- a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java +++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java @@ -1,14 +1,12 @@ package com.baeldung.jooq.introduction; import javax.sql.DataSource; -import com.zaxxer.hikari.HikariDataSource; - +import org.h2.jdbcx.JdbcDataSource; import org.jooq.SQLDialect; import org.jooq.impl.DataSourceConnectionProvider; import org.jooq.impl.DefaultConfiguration; import org.jooq.impl.DefaultDSLContext; import org.jooq.impl.DefaultExecuteListenerProvider; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -29,11 +27,10 @@ public class PersistenceContext { @Bean public DataSource dataSource() { - HikariDataSource dataSource = new HikariDataSource(); - - dataSource.setDriverClassName(environment.getRequiredProperty("db.driver")); - dataSource.setJdbcUrl(environment.getRequiredProperty("db.url")); - dataSource.setUsername(environment.getRequiredProperty("db.username")); + JdbcDataSource dataSource = new JdbcDataSource(); + + dataSource.setUrl(environment.getRequiredProperty("db.url")); + dataSource.setUser(environment.getRequiredProperty("db.username")); dataSource.setPassword(environment.getRequiredProperty("db.password")); return dataSource; From f214e0a285ee153f04ba84867550a43b0afea3d4 Mon Sep 17 00:00:00 2001 From: ankur-singhal Date: Fri, 1 Apr 2016 17:43:37 +0530 Subject: [PATCH 36/47] Xstream - XML to Object xml moved to resources folder, test cases fixed --- xstream-xmlToObject/.project | 33 +++++++------------ .../initializer/SimpleXstreamInitializer.java | 4 +-- .../ComplexXmlToObjectAnnotationTest.java | 7 ++-- ...lexXmlToObjectAttributeCollectionTest.java | 11 ++++--- .../ComplexXmlToObjectCollectionTest.java | 7 ++-- .../pojo/test/XmlToObjectAliasTest.java | 7 ++-- .../pojo/test/XmlToObjectAnnotationTest.java | 7 ++-- .../pojo/test/XmlToObjectFieldAliasTest.java | 7 ++-- .../test/XmlToObjectIgnoreFieldsTest.java | 7 ++-- .../baeldung/pojo/test/XmlToObjectTest.java | 7 ++-- .../data-file-alias-field-complex.xml | 15 +++++++++ .../test/resources/data-file-alias-field.xml | 5 +++ .../data-file-alias-implicit-collection.xml | 13 ++++++++ .../src/test/resources/data-file-alias.xml | 5 +++ .../test/resources/data-file-ignore-field.xml | 6 ++++ .../src/test/resources/data-file.xml | 5 +++ 16 files changed, 97 insertions(+), 49 deletions(-) create mode 100644 xstream-xmlToObject/src/test/resources/data-file-alias-field-complex.xml create mode 100644 xstream-xmlToObject/src/test/resources/data-file-alias-field.xml create mode 100644 xstream-xmlToObject/src/test/resources/data-file-alias-implicit-collection.xml create mode 100644 xstream-xmlToObject/src/test/resources/data-file-alias.xml create mode 100644 xstream-xmlToObject/src/test/resources/data-file-ignore-field.xml create mode 100644 xstream-xmlToObject/src/test/resources/data-file.xml diff --git a/xstream-xmlToObject/.project b/xstream-xmlToObject/.project index 133b92d690..4e1a3f6e92 100644 --- a/xstream-xmlToObject/.project +++ b/xstream-xmlToObject/.project @@ -1,23 +1,14 @@ - xstream-xmlToObject - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - + xstream-xmlToObject + NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. + + + + org.eclipse.jdt.core.javabuilder + + + + org.eclipse.jdt.core.javanature + + \ No newline at end of file diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java b/xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java index 8281678bab..d7dc3f7a81 100644 --- a/xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java +++ b/xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java @@ -4,9 +4,9 @@ import com.thoughtworks.xstream.XStream; public class SimpleXstreamInitializer { - private static XStream xtreamInstance; + private XStream xtreamInstance; - public static XStream getXstreamInstance() { + public XStream getXstreamInstance() { if (xtreamInstance == null) { synchronized (SimpleXstreamInitializer.class) { if (xtreamInstance == null) { diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java index dff671b6a6..10f59e843b 100644 --- a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java @@ -1,6 +1,5 @@ package com.baeldung.pojo.test; -import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -18,14 +17,16 @@ public class ComplexXmlToObjectAnnotationTest { @Before public void dataSetup() { - xstream = SimpleXstreamInitializer.getXstreamInstance(); + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); xstream.processAnnotations(Customer.class); } @Test public void convertXmlToObjectFromFile() { try { - FileReader reader = new FileReader(new File("data-file-alias-field-complex.xml")); + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field-complex.xml").getFile()); Customer customer = (Customer) xstream.fromXML(reader); Assert.assertNotNull(customer); Assert.assertNotNull(customer.getContactDetailsList()); diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java index 4494cc833d..876a407f76 100644 --- a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java @@ -1,6 +1,5 @@ package com.baeldung.pojo.test; -import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -8,8 +7,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import com.baeldung.implicit.collection.pojo.ContactDetails; -import com.baeldung.implicit.collection.pojo.Customer; +import com.baeldung.complex.pojo.ContactDetails; +import com.baeldung.complex.pojo.Customer; import com.baeldung.initializer.SimpleXstreamInitializer; import com.thoughtworks.xstream.XStream; @@ -19,14 +18,16 @@ public class ComplexXmlToObjectAttributeCollectionTest { @Before public void dataSetup() { - xstream = SimpleXstreamInitializer.getXstreamInstance(); + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); xstream.processAnnotations(Customer.class); } @Test public void convertXmlToObjectFromFile() { try { - FileReader reader = new FileReader(new File("data-file-alias-implicit-collection.xml")); + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field-complex.xml").getFile()); Customer customer = (Customer) xstream.fromXML(reader); Assert.assertNotNull(customer); Assert.assertNotNull(customer.getContactDetailsList()); diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java index b72ba44eb5..1656d2f230 100644 --- a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java @@ -1,6 +1,5 @@ package com.baeldung.pojo.test; -import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -18,14 +17,16 @@ public class ComplexXmlToObjectCollectionTest { @Before public void dataSetup() { - xstream = SimpleXstreamInitializer.getXstreamInstance(); + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); xstream.processAnnotations(Customer.class); } @Test public void convertXmlToObjectFromFile() { try { - FileReader reader = new FileReader(new File("data-file-alias-implicit-collection.xml")); + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-implicit-collection.xml").getFile()); Customer customer = (Customer) xstream.fromXML(reader); Assert.assertNotNull(customer); Assert.assertNotNull(customer.getContactDetailsList()); diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java index 884071542e..cc6d945254 100644 --- a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java @@ -1,6 +1,5 @@ package com.baeldung.pojo.test; -import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -18,14 +17,16 @@ public class XmlToObjectAliasTest { @Before public void dataSetup() { - xstream = SimpleXstreamInitializer.getXstreamInstance(); + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); xstream.alias("customer" , Customer.class); } @Test public void convertXmlToObjectFromFile() { try { - FileReader reader = new FileReader(new File("data-file-alias.xml")); + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias.xml").getFile()); Customer customer = (Customer) xstream.fromXML(reader); Assert.assertNotNull(customer); diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java index 09bed7d24f..f2012e2b12 100644 --- a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java @@ -1,6 +1,5 @@ package com.baeldung.pojo.test; -import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -18,14 +17,16 @@ public class XmlToObjectAnnotationTest { @Before public void dataSetup() { - xstream = SimpleXstreamInitializer.getXstreamInstance(); + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); xstream.processAnnotations(Customer.class); } @Test public void convertXmlToObjectFromFile() { try { - FileReader reader = new FileReader(new File("data-file-alias-field.xml")); + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field.xml").getFile()); Customer customer = (Customer) xstream.fromXML(reader); Assert.assertNotNull(customer); Assert.assertNotNull(customer.getFirstName()); diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java index c613a6517c..c4bba86265 100644 --- a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java @@ -1,6 +1,5 @@ package com.baeldung.pojo.test; -import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -18,7 +17,8 @@ public class XmlToObjectFieldAliasTest { @Before public void dataSetup() { - xstream = SimpleXstreamInitializer.getXstreamInstance(); + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); xstream.alias("customer" , Customer.class); xstream.aliasField("fn", Customer.class, "firstName"); } @@ -26,7 +26,8 @@ public class XmlToObjectFieldAliasTest { @Test public void convertXmlToObjectFromFile() { try { - FileReader reader = new FileReader(new File("data-file-alias-field.xml")); + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field.xml").getFile()); Customer customer = (Customer) xstream.fromXML(reader); Assert.assertNotNull(customer); Assert.assertNotNull(customer.getFirstName()); diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java index aa88918402..ca31a22b94 100644 --- a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java @@ -1,6 +1,5 @@ package com.baeldung.pojo.test; -import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -18,7 +17,8 @@ public class XmlToObjectIgnoreFieldsTest { @Before public void dataSetup() { - xstream = SimpleXstreamInitializer.getXstreamInstance(); + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); xstream.alias("customer" , Customer.class); xstream.ignoreUnknownElements(); } @@ -26,7 +26,8 @@ public class XmlToObjectIgnoreFieldsTest { @Test public void convertXmlToObjectFromFile() { try { - FileReader reader = new FileReader(new File("data-file-ignore-field.xml")); + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-ignore-field.xml").getFile()); Customer customer = (Customer) xstream.fromXML(reader); Assert.assertNotNull(customer); System.out.println(customer); diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java index cb7fc49b33..e24e54aea4 100644 --- a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java +++ b/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java @@ -1,6 +1,5 @@ package com.baeldung.pojo.test; -import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -19,13 +18,15 @@ public class XmlToObjectTest { @Before public void dataSetup() { - xstream = SimpleXstreamInitializer.getXstreamInstance(); + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); } @Test public void convertXmlToObjectFromFile() { try { - FileReader reader = new FileReader(new File("data-file.xml")); + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file.xml").getFile()); Customer customer = (Customer) xstream.fromXML(reader); Assert.assertNotNull(customer); diff --git a/xstream-xmlToObject/src/test/resources/data-file-alias-field-complex.xml b/xstream-xmlToObject/src/test/resources/data-file-alias-field-complex.xml new file mode 100644 index 0000000000..2235aa7044 --- /dev/null +++ b/xstream-xmlToObject/src/test/resources/data-file-alias-field-complex.xml @@ -0,0 +1,15 @@ + + XStream + Java + 1986-02-14 04:14:05.874 UTC + + + 6673543265 + 0124-2460311 + + + 4676543565 + 0120-223312 + + + \ No newline at end of file diff --git a/xstream-xmlToObject/src/test/resources/data-file-alias-field.xml b/xstream-xmlToObject/src/test/resources/data-file-alias-field.xml new file mode 100644 index 0000000000..9bc1d0990a --- /dev/null +++ b/xstream-xmlToObject/src/test/resources/data-file-alias-field.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file diff --git a/xstream-xmlToObject/src/test/resources/data-file-alias-implicit-collection.xml b/xstream-xmlToObject/src/test/resources/data-file-alias-implicit-collection.xml new file mode 100644 index 0000000000..d8731900b9 --- /dev/null +++ b/xstream-xmlToObject/src/test/resources/data-file-alias-implicit-collection.xml @@ -0,0 +1,13 @@ + + XStream + Java + 1986-02-14 04:14:20.541 UTC + + 6673543265 + 0124-2460311 + + + 4676543565 + 0120-223312 + + \ No newline at end of file diff --git a/xstream-xmlToObject/src/test/resources/data-file-alias.xml b/xstream-xmlToObject/src/test/resources/data-file-alias.xml new file mode 100644 index 0000000000..964157f1dd --- /dev/null +++ b/xstream-xmlToObject/src/test/resources/data-file-alias.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file diff --git a/xstream-xmlToObject/src/test/resources/data-file-ignore-field.xml b/xstream-xmlToObject/src/test/resources/data-file-ignore-field.xml new file mode 100644 index 0000000000..865e93d4b4 --- /dev/null +++ b/xstream-xmlToObject/src/test/resources/data-file-ignore-field.xml @@ -0,0 +1,6 @@ + + XStream + Java + 1986-02-14 04:14:20.541 UTC + XStream Java + \ No newline at end of file diff --git a/xstream-xmlToObject/src/test/resources/data-file.xml b/xstream-xmlToObject/src/test/resources/data-file.xml new file mode 100644 index 0000000000..59f2ea1cca --- /dev/null +++ b/xstream-xmlToObject/src/test/resources/data-file.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file From cbc3d119a5882d9aa5dd4b09faa214078869858b Mon Sep 17 00:00:00 2001 From: ankur-singhal Date: Fri, 1 Apr 2016 17:56:04 +0530 Subject: [PATCH 37/47] Xstream - xml to object removing input xml from root folders --- .../data-file-alias-field-complex.xml | 15 --------------- xstream-xmlToObject/data-file-alias-field.xml | 5 ----- .../data-file-alias-implicit-collection.xml | 13 ------------- xstream-xmlToObject/data-file-alias.xml | 5 ----- xstream-xmlToObject/data-file-ignore-field.xml | 6 ------ xstream-xmlToObject/data-file.xml | 5 ----- 6 files changed, 49 deletions(-) delete mode 100644 xstream-xmlToObject/data-file-alias-field-complex.xml delete mode 100644 xstream-xmlToObject/data-file-alias-field.xml delete mode 100644 xstream-xmlToObject/data-file-alias-implicit-collection.xml delete mode 100644 xstream-xmlToObject/data-file-alias.xml delete mode 100644 xstream-xmlToObject/data-file-ignore-field.xml delete mode 100644 xstream-xmlToObject/data-file.xml diff --git a/xstream-xmlToObject/data-file-alias-field-complex.xml b/xstream-xmlToObject/data-file-alias-field-complex.xml deleted file mode 100644 index 2235aa7044..0000000000 --- a/xstream-xmlToObject/data-file-alias-field-complex.xml +++ /dev/null @@ -1,15 +0,0 @@ - - XStream - Java - 1986-02-14 04:14:05.874 UTC - - - 6673543265 - 0124-2460311 - - - 4676543565 - 0120-223312 - - - \ No newline at end of file diff --git a/xstream-xmlToObject/data-file-alias-field.xml b/xstream-xmlToObject/data-file-alias-field.xml deleted file mode 100644 index 9bc1d0990a..0000000000 --- a/xstream-xmlToObject/data-file-alias-field.xml +++ /dev/null @@ -1,5 +0,0 @@ - - XStream - Java - 1986-02-14 03:46:16.381 UTC - \ No newline at end of file diff --git a/xstream-xmlToObject/data-file-alias-implicit-collection.xml b/xstream-xmlToObject/data-file-alias-implicit-collection.xml deleted file mode 100644 index d8731900b9..0000000000 --- a/xstream-xmlToObject/data-file-alias-implicit-collection.xml +++ /dev/null @@ -1,13 +0,0 @@ - - XStream - Java - 1986-02-14 04:14:20.541 UTC - - 6673543265 - 0124-2460311 - - - 4676543565 - 0120-223312 - - \ No newline at end of file diff --git a/xstream-xmlToObject/data-file-alias.xml b/xstream-xmlToObject/data-file-alias.xml deleted file mode 100644 index 964157f1dd..0000000000 --- a/xstream-xmlToObject/data-file-alias.xml +++ /dev/null @@ -1,5 +0,0 @@ - - XStream - Java - 1986-02-14 03:46:16.381 UTC - \ No newline at end of file diff --git a/xstream-xmlToObject/data-file-ignore-field.xml b/xstream-xmlToObject/data-file-ignore-field.xml deleted file mode 100644 index 865e93d4b4..0000000000 --- a/xstream-xmlToObject/data-file-ignore-field.xml +++ /dev/null @@ -1,6 +0,0 @@ - - XStream - Java - 1986-02-14 04:14:20.541 UTC - XStream Java - \ No newline at end of file diff --git a/xstream-xmlToObject/data-file.xml b/xstream-xmlToObject/data-file.xml deleted file mode 100644 index 59f2ea1cca..0000000000 --- a/xstream-xmlToObject/data-file.xml +++ /dev/null @@ -1,5 +0,0 @@ - - XStream - Java - 1986-02-14 03:46:16.381 UTC - \ No newline at end of file From 2f9524ae8e08e5ce7974f2ee3cd3a2b4d62b2144 Mon Sep 17 00:00:00 2001 From: David Morley Date: Sun, 3 Apr 2016 04:59:27 -0500 Subject: [PATCH 38/47] Clean up jOOQ examples --- .../baeldung/jooq/introduction/QueryTest.java | 44 +++++++++---------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java index 34be23bf2a..bc12dff5a0 100644 --- a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java +++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java @@ -1,31 +1,29 @@ package com.baeldung.jooq.introduction; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.junit.runner.RunWith; - +import com.baeldung.jooq.introduction.db.public_.tables.Author; +import com.baeldung.jooq.introduction.db.public_.tables.AuthorBook; +import com.baeldung.jooq.introduction.db.public_.tables.Book; import org.jooq.DSLContext; import org.jooq.Record3; import org.jooq.Result; import org.jooq.impl.DSL; - +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; -import com.baeldung.jooq.introduction.db.public_.tables.Author; -import com.baeldung.jooq.introduction.db.public_.tables.AuthorBook; -import com.baeldung.jooq.introduction.db.public_.tables.Book; +import static org.junit.Assert.assertEquals; @ContextConfiguration(classes = PersistenceContext.class) @Transactional(transactionManager = "transactionManager") @RunWith(SpringJUnit4ClassRunner.class) public class QueryTest { + @Autowired - private DSLContext create; + private DSLContext dsl; Author author = Author.AUTHOR; Book book = Book.BOOK; @@ -33,10 +31,10 @@ public class QueryTest { @Test public void givenValidData_whenInserting_thenSucceed() { - create.insertInto(author).set(author.ID, 4).set(author.FIRST_NAME, "Herbert").set(author.LAST_NAME, "Schildt").execute(); - create.insertInto(book).set(book.ID, 4).set(book.TITLE, "A Beginner's Guide").execute(); - create.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 4).execute(); - Result> result = create.select(author.ID, author.LAST_NAME, DSL.count()).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID)) + dsl.insertInto(author).set(author.ID, 4).set(author.FIRST_NAME, "Herbert").set(author.LAST_NAME, "Schildt").execute(); + dsl.insertInto(book).set(book.ID, 4).set(book.TITLE, "A Beginner's Guide").execute(); + dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 4).execute(); + Result> result = dsl.select(author.ID, author.LAST_NAME, DSL.count()).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID)) .groupBy(author.LAST_NAME).fetch(); assertEquals(3, result.size()); @@ -48,15 +46,15 @@ public class QueryTest { @Test(expected = DataAccessException.class) public void givenInvalidData_whenInserting_thenFail() { - create.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute(); + dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute(); } @Test public void givenValidData_whenUpdating_thenSucceed() { - create.update(author).set(author.LAST_NAME, "Baeldung").where(author.ID.equal(3)).execute(); - create.update(book).set(book.TITLE, "Building your REST API with Spring").where(book.ID.equal(3)).execute(); - create.insertInto(authorBook).set(authorBook.AUTHOR_ID, 3).set(authorBook.BOOK_ID, 3).execute(); - Result> result = create.select(author.ID, author.LAST_NAME, book.TITLE).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID)).where(author.ID.equal(3)) + dsl.update(author).set(author.LAST_NAME, "Baeldung").where(author.ID.equal(3)).execute(); + dsl.update(book).set(book.TITLE, "Building your REST API with Spring").where(book.ID.equal(3)).execute(); + dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 3).set(authorBook.BOOK_ID, 3).execute(); + Result> result = dsl.select(author.ID, author.LAST_NAME, book.TITLE).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID)).where(author.ID.equal(3)) .fetch(); assertEquals(1, result.size()); @@ -67,13 +65,13 @@ public class QueryTest { @Test(expected = DataAccessException.class) public void givenInvalidData_whenUpdating_thenFail() { - create.update(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute(); + dsl.update(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute(); } @Test public void givenValidData_whenDeleting_thenSucceed() { - create.delete(author).where(author.ID.lt(3)).execute(); - Result> result = create.select(author.ID, author.FIRST_NAME, author.LAST_NAME).from(author).fetch(); + dsl.delete(author).where(author.ID.lt(3)).execute(); + Result> result = dsl.select(author.ID, author.FIRST_NAME, author.LAST_NAME).from(author).fetch(); assertEquals(1, result.size()); assertEquals("Bryan", result.getValue(0, author.FIRST_NAME)); @@ -82,6 +80,6 @@ public class QueryTest { @Test(expected = DataAccessException.class) public void givenInvalidData_whenDeleting_thenFail() { - create.delete(book).where(book.ID.equal(1)).execute(); + dsl.delete(book).where(book.ID.equal(1)).execute(); } } \ No newline at end of file From 9b262c9381eca09f00c1e48abad52be33275e11c Mon Sep 17 00:00:00 2001 From: DOHA Date: Sun, 3 Apr 2016 19:13:25 +0200 Subject: [PATCH 39/47] add java configuration --- .../baeldung/spring/SecSecurityConfig.java | 51 +++++++++++++++- .../src/main/webapp/WEB-INF/web.xml | 9 ++- ...SimpleUrlAuthenticationSuccessHandler.java | 2 +- .../baeldung/spring/SecSecurityConfig.java | 58 ++++++++++++++++++- .../src/main/webapp/WEB-INF/web.xml | 13 ++--- .../config/parent/SecurityConfig.java | 31 +++++++++- 6 files changed, 142 insertions(+), 22 deletions(-) diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 4da114c78b..08cb09384b 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,14 +1,59 @@ package org.baeldung.spring; +import org.baeldung.security.CustomLogoutSuccessHandler; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; +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.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; @Configuration -@ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecSecurityConfig { +// @ImportResource({ "classpath:webSecurityConfig.xml" }) +@EnableWebSecurity +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public SecSecurityConfig() { super(); } + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("user1").password("user1Pass").roles("USER") + .and() + .withUser("user2").password("user2Pass").roles("USER"); + // @formatter:on + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/anonymous*").anonymous() + .antMatchers("/login*").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/perform_login") + .defaultSuccessUrl("/homepage.html",true) + .failureUrl("/login.html?error=true") + .and() + .logout() + .logoutUrl("/perform_logout") + .deleteCookies("JSESSIONID") + .logoutSuccessHandler(logoutSuccessHandler()); + // @formatter:on + } + + @Bean + public LogoutSuccessHandler logoutSuccessHandler() { + return new CustomLogoutSuccessHandler(); + } + } diff --git a/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml index f13ae48c7e..0a0a340995 100644 --- a/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-mvc-login/src/main/webapp/WEB-INF/web.xml @@ -1,9 +1,8 @@ - + Spring MVC Application diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 19f1ca76a6..19f49ea59d 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -21,7 +21,7 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - protected MySimpleUrlAuthenticationSuccessHandler() { + public MySimpleUrlAuthenticationSuccessHandler() { super(); } diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 4da114c78b..c62b795e01 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,14 +1,66 @@ package org.baeldung.spring; +import org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; +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.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.security.web.session.HttpSessionEventPublisher; @Configuration -@ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecSecurityConfig { +// @ImportResource({ "classpath:webSecurityConfig.xml" }) +@EnableWebSecurity +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public SecSecurityConfig() { super(); } + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.inMemoryAuthentication() + .withUser("user1").password("user1Pass").roles("USER") + .and() + .withUser("admin1").password("admin1Pass").roles("ADMIN"); + // @formatter:on + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/anonymous*").anonymous() + .antMatchers("/login*").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/login") + .successHandler(successHandler()) + .failureUrl("/login.html?error=true") + .and() + .logout().deleteCookies("JSESSIONID") + .and() + .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400) + .and() + .sessionManagement().invalidSessionUrl("/invalidSession.html").maximumSessions(2).expiredUrl("/sessionExpired.html"); + + // @formatter:on + } + + private AuthenticationSuccessHandler successHandler() { + return new MySimpleUrlAuthenticationSuccessHandler(); + } + + @Bean + public HttpSessionEventPublisher httpSessionEventPublisher() { + return new HttpSessionEventPublisher(); + } + } diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml index 45b49b2a91..57826fadac 100644 --- a/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml @@ -1,9 +1,8 @@ - + Spring MVC Session Application @@ -13,9 +12,9 @@ org.baeldung.web.SessionListenerWithMetrics - + diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java index ee9b0868e7..67d9abbae5 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java @@ -1,16 +1,41 @@ package org.baeldung.config.parent; +import org.baeldung.security.CustomAuthenticationProvider; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; +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.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration -@ImportResource({ "classpath:webSecurityConfig.xml" }) +// @ImportResource({ "classpath:webSecurityConfig.xml" }) +@EnableWebSecurity @ComponentScan("org.baeldung.security") -public class SecurityConfig { +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private CustomAuthenticationProvider authProvider; public SecurityConfig() { super(); } + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(authProvider); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .authorizeRequests().anyRequest().authenticated() + .and() + .httpBasic(); + // @formatter:on + } + + } From 68e20baeede810aa6878d4d1648682727be1f619 Mon Sep 17 00:00:00 2001 From: David Morley Date: Sun, 3 Apr 2016 15:28:16 -0500 Subject: [PATCH 40/47] Clean up Spring Handler Mapping examples --- spring-mvc-xml/.classpath | 62 ------------ ...e.wst.jsdt.core.javascriptValidator.launch | 7 -- spring-mvc-xml/.project | 43 --------- spring-mvc-xml/.settings/.jsdtscope | 12 --- .../.settings/org.eclipse.jdt.core.prefs | 96 ------------------- .../.settings/org.eclipse.jdt.ui.prefs | 55 ----------- .../.settings/org.eclipse.m2e.core.prefs | 4 - .../.settings/org.eclipse.m2e.wtp.prefs | 2 - .../org.eclipse.wst.common.component | 11 --- ....eclipse.wst.common.project.facet.core.xml | 6 -- ...rg.eclipse.wst.jsdt.ui.superType.container | 1 - .../org.eclipse.wst.jsdt.ui.superType.name | 1 - .../org.eclipse.wst.validation.prefs | 15 --- .../org.eclipse.wst.ws.service.policy.prefs | 2 - spring-mvc-xml/.springBeans | 14 --- .../spring/controller/HelloController.java | 4 +- .../controller/HelloGuestController.java | 3 +- .../controller/HelloWorldController.java | 3 +- .../spring/controller/WelcomeController.java | 3 +- .../src/main/webapp/WEB-INF/mvc-servlet.xml | 84 ++++++++-------- spring-mvc-xml/src/main/webapp/index.jsp | 4 +- .../src/main/webapp/spring-handler-index.jsp | 30 +++--- 22 files changed, 63 insertions(+), 399 deletions(-) delete mode 100644 spring-mvc-xml/.classpath delete mode 100644 spring-mvc-xml/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch delete mode 100644 spring-mvc-xml/.project delete mode 100644 spring-mvc-xml/.settings/.jsdtscope delete mode 100644 spring-mvc-xml/.settings/org.eclipse.jdt.core.prefs delete mode 100644 spring-mvc-xml/.settings/org.eclipse.jdt.ui.prefs delete mode 100644 spring-mvc-xml/.settings/org.eclipse.m2e.core.prefs delete mode 100644 spring-mvc-xml/.settings/org.eclipse.m2e.wtp.prefs delete mode 100644 spring-mvc-xml/.settings/org.eclipse.wst.common.component delete mode 100644 spring-mvc-xml/.settings/org.eclipse.wst.common.project.facet.core.xml delete mode 100644 spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.container delete mode 100644 spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.name delete mode 100644 spring-mvc-xml/.settings/org.eclipse.wst.validation.prefs delete mode 100644 spring-mvc-xml/.settings/org.eclipse.wst.ws.service.policy.prefs delete mode 100644 spring-mvc-xml/.springBeans diff --git a/spring-mvc-xml/.classpath b/spring-mvc-xml/.classpath deleted file mode 100644 index 24a63f3df7..0000000000 --- a/spring-mvc-xml/.classpath +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-mvc-xml/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/spring-mvc-xml/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/spring-mvc-xml/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/spring-mvc-xml/.project b/spring-mvc-xml/.project deleted file mode 100644 index e0267781eb..0000000000 --- a/spring-mvc-xml/.project +++ /dev/null @@ -1,43 +0,0 @@ - - - spring-mvc-xml - NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - org.springframework.ide.eclipse.core.springnature - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.eclipse.jdt.core.javanature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - diff --git a/spring-mvc-xml/.settings/.jsdtscope b/spring-mvc-xml/.settings/.jsdtscope deleted file mode 100644 index b46b9207a8..0000000000 --- a/spring-mvc-xml/.settings/.jsdtscope +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-mvc-xml/.settings/org.eclipse.jdt.core.prefs b/spring-mvc-xml/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index c57289fc09..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,96 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=error -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=error -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/spring-mvc-xml/.settings/org.eclipse.jdt.ui.prefs b/spring-mvc-xml/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,55 +0,0 @@ -#Sat Jan 21 23:04:06 EET 2012 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=true -sp_cleanup.make_parameters_final=true -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/spring-mvc-xml/.settings/org.eclipse.m2e.core.prefs b/spring-mvc-xml/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/spring-mvc-xml/.settings/org.eclipse.m2e.wtp.prefs b/spring-mvc-xml/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.common.component b/spring-mvc-xml/.settings/org.eclipse.wst.common.component deleted file mode 100644 index e54e3acac9..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-mvc-xml/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 9ca0d1c1b7..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.container b/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.name b/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.validation.prefs b/spring-mvc-xml/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index 0d0aee4f72..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -1,15 +0,0 @@ -DELEGATES_PREFERENCE=delegateValidatorList -USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.402.v201212031633 -disabled=06target -eclipse.preferences.version=1 -override=true -suspend=false -vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01 -vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01 -vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02 -vf.version=3 diff --git a/spring-mvc-xml/.settings/org.eclipse.wst.ws.service.policy.prefs b/spring-mvc-xml/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/spring-mvc-xml/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/spring-mvc-xml/.springBeans b/spring-mvc-xml/.springBeans deleted file mode 100644 index 7623a7e888..0000000000 --- a/spring-mvc-xml/.springBeans +++ /dev/null @@ -1,14 +0,0 @@ - - - 1 - - - - - - - src/main/webapp/WEB-INF/mvc-servlet.xml - - - - diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java index 766aa6670a..cc9d66d4d4 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloController.java @@ -7,10 +7,12 @@ import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class HelloController extends AbstractController { + @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "!! Welcome to baeldung's Spring Handler Mappings Guide.
This is using SimpleUrlHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + + " using SimpleUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java index 5c19dc2295..614888ae42 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloGuestController.java @@ -10,7 +10,8 @@ public class HelloGuestController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "!! Welcome to baeldung's Spring Handler Mappings Guide.
This is using ControllerClassNameHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + + " using ControllerClassNameHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java index 0659b3815d..6ed3d06ab7 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/HelloWorldController.java @@ -10,7 +10,8 @@ public class HelloWorldController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloworld"); - model.addObject("msg", "!! Welcome to baeldung's Spring Handler Mappings Guide.
This is using BeanNameUrlHandlerMapping."); + model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.
This request was mapped" + + " using BeanNameUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java index e3c8bc5a25..5459481674 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/WelcomeController.java @@ -11,7 +11,8 @@ public class WelcomeController extends AbstractController { protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("welcome"); - model.addObject("msg", " baeldung's Spring Handler Mappings Guide.
This is using SimpleUrlHandlerMapping."); + model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.
This request was mapped" + + " using SimpleUrlHandlerMapping."); return model; } diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml index 400c7b5e86..6cefb21961 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -1,57 +1,57 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> - - - - + + + + - - + + - + - - + + - - - - - welcomeController - welcomeController - helloController - - - - + + + + + welcomeController + welcomeController + helloController + + + + - - - + + + - - - - - + + + + + - - + + - - - + + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/index.jsp b/spring-mvc-xml/src/main/webapp/index.jsp index ef9279f6e5..ce7b3107d8 100644 --- a/spring-mvc-xml/src/main/webapp/index.jsp +++ b/spring-mvc-xml/src/main/webapp/index.jsp @@ -12,9 +12,7 @@

Spring MVC Examples

- diff --git a/spring-mvc-xml/src/main/webapp/spring-handler-index.jsp b/spring-mvc-xml/src/main/webapp/spring-handler-index.jsp index d915b344cb..0fdd51d1ec 100644 --- a/spring-mvc-xml/src/main/webapp/spring-handler-index.jsp +++ b/spring-mvc-xml/src/main/webapp/spring-handler-index.jsp @@ -1,26 +1,18 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - -Welcome + + Welcome -

Welcome to Spring Handler Mapping Example

-

Click below link to understand each mentioned Handler Mapping: -

-

- 1. BeanNameUrlHandlerMapping - - Mapping by bean name
-

- 2. SimpleUrlHandlerMapping -
-

- 3. ControllerClassNameHandlerMapping - - Mapping by controller name
-

- Go to spring handler mappings - homepage +

Spring Handler Mapping Examples

+

Click each link below to see how the request is mapped using the specified mapping: +

+
    +
  1. BeanNameUrlHandlerMapping - Mapping by bean name
  2. +
  3. SimpleUrlHandlerMapping
  4. +
  5. ControllerClassNameHandlerMapping - Mapping by controller name
  6. +
+Home \ No newline at end of file From dd61036a31a8ebac3087fe94fd58c0bd2bef5df4 Mon Sep 17 00:00:00 2001 From: ankur-singhal Date: Mon, 4 Apr 2016 11:27:07 +0530 Subject: [PATCH 41/47] XStream-Introduction Merging changes for Article XML - to Object --- .../baeldung/annotation/pojo/Customer.java | 0 .../annotation/pojo/CustomerOmitField.java | 0 .../baeldung/complex/pojo/ContactDetails.java | 0 .../com/baeldung/complex/pojo/Customer.java | 0 .../collection/pojo/ContactDetails.java | 0 .../implicit/collection/pojo/Customer.java | 0 .../initializer/SimpleXstreamInitializer.java | 12 +++--- .../main/java/com/baeldung/pojo/Customer.java | 6 ++- .../ComplexXmlToObjectAnnotationTest.java | 0 ...lexXmlToObjectAttributeCollectionTest.java | 0 .../ComplexXmlToObjectCollectionTest.java | 2 +- .../pojo/test/XmlToObjectAliasTest.java | 0 .../pojo/test/XmlToObjectAnnotationTest.java | 0 .../pojo/test/XmlToObjectFieldAliasTest.java | 0 .../test/XmlToObjectIgnoreFieldsTest.java | 2 +- .../baeldung/pojo/test/XmlToObjectTest.java | 0 .../utility/XStreamSimpleXmlTest.java | 5 +-- .../data-file-alias-field-complex.xml | 0 .../test/resources/data-file-alias-field.xml | 0 .../data-file-alias-implicit-collection.xml | 0 .../src/test/resources/data-file-alias.xml | 0 .../test/resources/data-file-ignore-field.xml | 0 .../src/test/resources/data-file.xml | 0 xstream-xmlToObject/.project | 14 ------- xstream-xmlToObject/pom.xml | 36 ---------------- .../initializer/SimpleXstreamInitializer.java | 19 --------- .../main/java/com/baeldung/pojo/Customer.java | 42 ------------------- .../utility/SimpleDataGeneration.java | 19 --------- .../src/main/resources/log4j.properties | 16 ------- 29 files changed, 14 insertions(+), 159 deletions(-) rename {xstream-xmlToObject => xstream-introduction}/src/main/java/com/baeldung/annotation/pojo/Customer.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/main/java/com/baeldung/complex/pojo/ContactDetails.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/main/java/com/baeldung/complex/pojo/Customer.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java (96%) rename {xstream-xmlToObject => xstream-introduction}/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java (96%) rename {xstream-xmlToObject => xstream-introduction}/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/resources/data-file-alias-field-complex.xml (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/resources/data-file-alias-field.xml (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/resources/data-file-alias-implicit-collection.xml (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/resources/data-file-alias.xml (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/resources/data-file-ignore-field.xml (100%) rename {xstream-xmlToObject => xstream-introduction}/src/test/resources/data-file.xml (100%) delete mode 100644 xstream-xmlToObject/.project delete mode 100644 xstream-xmlToObject/pom.xml delete mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java delete mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/pojo/Customer.java delete mode 100644 xstream-xmlToObject/src/main/java/com/baeldung/utility/SimpleDataGeneration.java delete mode 100644 xstream-xmlToObject/src/main/resources/log4j.properties diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/Customer.java b/xstream-introduction/src/main/java/com/baeldung/annotation/pojo/Customer.java similarity index 100% rename from xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/Customer.java rename to xstream-introduction/src/main/java/com/baeldung/annotation/pojo/Customer.java diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java b/xstream-introduction/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java similarity index 100% rename from xstream-xmlToObject/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java rename to xstream-introduction/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/ContactDetails.java b/xstream-introduction/src/main/java/com/baeldung/complex/pojo/ContactDetails.java similarity index 100% rename from xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/ContactDetails.java rename to xstream-introduction/src/main/java/com/baeldung/complex/pojo/ContactDetails.java diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/Customer.java b/xstream-introduction/src/main/java/com/baeldung/complex/pojo/Customer.java similarity index 100% rename from xstream-xmlToObject/src/main/java/com/baeldung/complex/pojo/Customer.java rename to xstream-introduction/src/main/java/com/baeldung/complex/pojo/Customer.java diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java b/xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java similarity index 100% rename from xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java rename to xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java b/xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java similarity index 100% rename from xstream-xmlToObject/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java rename to xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java diff --git a/xstream-introduction/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java b/xstream-introduction/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java index 618df877b9..d7dc3f7a81 100644 --- a/xstream-introduction/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java +++ b/xstream-introduction/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java @@ -4,16 +4,16 @@ import com.thoughtworks.xstream.XStream; public class SimpleXstreamInitializer { - private static XStream xstreamInstance; + private XStream xtreamInstance; - public static XStream getXstreamInstance() { - if (xstreamInstance == null) { + public XStream getXstreamInstance() { + if (xtreamInstance == null) { synchronized (SimpleXstreamInitializer.class) { - if (xstreamInstance == null) { - xstreamInstance = new XStream(); + if (xtreamInstance == null) { + xtreamInstance = new XStream(); } } } - return xstreamInstance; + return xtreamInstance; } } \ No newline at end of file diff --git a/xstream-introduction/src/main/java/com/baeldung/pojo/Customer.java b/xstream-introduction/src/main/java/com/baeldung/pojo/Customer.java index 2ed11dcdab..9bed3394ef 100644 --- a/xstream-introduction/src/main/java/com/baeldung/pojo/Customer.java +++ b/xstream-introduction/src/main/java/com/baeldung/pojo/Customer.java @@ -5,12 +5,10 @@ import java.util.List; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit; -import com.thoughtworks.xstream.annotations.XStreamOmitField; @XStreamAlias("customer") public class Customer { - //@XStreamOmitField private String firstName; private String lastName; @@ -52,4 +50,8 @@ public class Customer { this.contactDetailsList = contactDetailsList; } + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]"; + } } diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java similarity index 100% rename from xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java rename to xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java similarity index 100% rename from xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java rename to xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java similarity index 96% rename from xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java rename to xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java index 1656d2f230..d701fc153b 100644 --- a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java +++ b/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java @@ -30,7 +30,7 @@ public class ComplexXmlToObjectCollectionTest { Customer customer = (Customer) xstream.fromXML(reader); Assert.assertNotNull(customer); Assert.assertNotNull(customer.getContactDetailsList()); - System.out.println(customer); + //System.out.println(customer); } catch (IOException e) { e.printStackTrace(); diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java similarity index 100% rename from xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java rename to xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java similarity index 100% rename from xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java rename to xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java similarity index 100% rename from xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java rename to xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java similarity index 96% rename from xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java rename to xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java index ca31a22b94..cb13bb9570 100644 --- a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java +++ b/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java @@ -30,7 +30,7 @@ public class XmlToObjectIgnoreFieldsTest { FileReader reader = new FileReader(classLoader.getResource("data-file-ignore-field.xml").getFile()); Customer customer = (Customer) xstream.fromXML(reader); Assert.assertNotNull(customer); - System.out.println(customer); + //System.out.println(customer); } catch (IOException e) { e.printStackTrace(); } diff --git a/xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java similarity index 100% rename from xstream-xmlToObject/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java rename to xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java diff --git a/xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java b/xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java index 50d02528bd..ea60e68743 100644 --- a/xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java +++ b/xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java @@ -22,7 +22,8 @@ public class XStreamSimpleXmlTest { @Before public void dataSetup() { customer = SimpleDataGeneration.generateData(); - xstream = SimpleXstreamInitializer.getXstreamInstance(); + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); xstream.processAnnotations(Customer.class); xstream.processAnnotations(AddressDetails.class); xstream.processAnnotations(ContactDetails.class); @@ -30,9 +31,7 @@ public class XStreamSimpleXmlTest { xstream.registerConverter(new MyDateConverter()); // xstream.registerConverter(new MySingleValueConverter()); xstream.aliasField("fn" , Customer.class , "firstName"); - dataXml = xstream.toXML(customer); - System.out.println(dataXml); } @Test diff --git a/xstream-xmlToObject/src/test/resources/data-file-alias-field-complex.xml b/xstream-introduction/src/test/resources/data-file-alias-field-complex.xml similarity index 100% rename from xstream-xmlToObject/src/test/resources/data-file-alias-field-complex.xml rename to xstream-introduction/src/test/resources/data-file-alias-field-complex.xml diff --git a/xstream-xmlToObject/src/test/resources/data-file-alias-field.xml b/xstream-introduction/src/test/resources/data-file-alias-field.xml similarity index 100% rename from xstream-xmlToObject/src/test/resources/data-file-alias-field.xml rename to xstream-introduction/src/test/resources/data-file-alias-field.xml diff --git a/xstream-xmlToObject/src/test/resources/data-file-alias-implicit-collection.xml b/xstream-introduction/src/test/resources/data-file-alias-implicit-collection.xml similarity index 100% rename from xstream-xmlToObject/src/test/resources/data-file-alias-implicit-collection.xml rename to xstream-introduction/src/test/resources/data-file-alias-implicit-collection.xml diff --git a/xstream-xmlToObject/src/test/resources/data-file-alias.xml b/xstream-introduction/src/test/resources/data-file-alias.xml similarity index 100% rename from xstream-xmlToObject/src/test/resources/data-file-alias.xml rename to xstream-introduction/src/test/resources/data-file-alias.xml diff --git a/xstream-xmlToObject/src/test/resources/data-file-ignore-field.xml b/xstream-introduction/src/test/resources/data-file-ignore-field.xml similarity index 100% rename from xstream-xmlToObject/src/test/resources/data-file-ignore-field.xml rename to xstream-introduction/src/test/resources/data-file-ignore-field.xml diff --git a/xstream-xmlToObject/src/test/resources/data-file.xml b/xstream-introduction/src/test/resources/data-file.xml similarity index 100% rename from xstream-xmlToObject/src/test/resources/data-file.xml rename to xstream-introduction/src/test/resources/data-file.xml diff --git a/xstream-xmlToObject/.project b/xstream-xmlToObject/.project deleted file mode 100644 index 4e1a3f6e92..0000000000 --- a/xstream-xmlToObject/.project +++ /dev/null @@ -1,14 +0,0 @@ - - - xstream-xmlToObject - NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. - - - - org.eclipse.jdt.core.javabuilder - - - - org.eclipse.jdt.core.javanature - - \ No newline at end of file diff --git a/xstream-xmlToObject/pom.xml b/xstream-xmlToObject/pom.xml deleted file mode 100644 index 4828ccb569..0000000000 --- a/xstream-xmlToObject/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - 4.0.0 - - com.baeldung - xstream-xmlToObject - 0.0.1-SNAPSHOT - jar - - xstream-xmlToObject - http://maven.apache.org - - - UTF-8 - - - - - com.thoughtworks.xstream - xstream - 1.4.5 - - - - junit - junit - 4.12 - - - - log4j - log4j - 1.2.17 - - - diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java b/xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java deleted file mode 100644 index d7dc3f7a81..0000000000 --- a/xstream-xmlToObject/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.initializer; - -import com.thoughtworks.xstream.XStream; - -public class SimpleXstreamInitializer { - - private XStream xtreamInstance; - - public XStream getXstreamInstance() { - if (xtreamInstance == null) { - synchronized (SimpleXstreamInitializer.class) { - if (xtreamInstance == null) { - xtreamInstance = new XStream(); - } - } - } - return xtreamInstance; - } -} \ No newline at end of file diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/pojo/Customer.java b/xstream-xmlToObject/src/main/java/com/baeldung/pojo/Customer.java deleted file mode 100644 index affed65fff..0000000000 --- a/xstream-xmlToObject/src/main/java/com/baeldung/pojo/Customer.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.pojo; - -import java.util.Date; - -public class Customer { - - private String firstName; - - private String lastName; - - private Date dob; - - 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 Date getDob() { - return dob; - } - - public void setDob(Date dob) { - this.dob = dob; - } - - @Override - public String toString() { - return "Customer [firstName=" + firstName + ", lastName=" + lastName - + ", dob=" + dob + "]"; - } -} diff --git a/xstream-xmlToObject/src/main/java/com/baeldung/utility/SimpleDataGeneration.java b/xstream-xmlToObject/src/main/java/com/baeldung/utility/SimpleDataGeneration.java deleted file mode 100644 index 14ca25952f..0000000000 --- a/xstream-xmlToObject/src/main/java/com/baeldung/utility/SimpleDataGeneration.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.utility; - -import java.util.Calendar; - -import com.baeldung.pojo.Customer; - -public class SimpleDataGeneration { - - public static Customer generateData() { - Customer customer = new Customer(); - Calendar cal = Calendar.getInstance(); - cal.set(1986 , 01 , 14); - customer.setDob(cal.getTime()); - customer.setFirstName("Xstream"); - customer.setLastName("Java"); - - return customer; - } -} diff --git a/xstream-xmlToObject/src/main/resources/log4j.properties b/xstream-xmlToObject/src/main/resources/log4j.properties deleted file mode 100644 index 9cdafc6bdb..0000000000 --- a/xstream-xmlToObject/src/main/resources/log4j.properties +++ /dev/null @@ -1,16 +0,0 @@ -# Root logger option -log4j.rootLogger=DEBUG, file - -# Redirect log messages to console -# log4j.appender.stdout=org.apache.log4j.ConsoleAppender -# log4j.appender.stdout.Target=System.out -# log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n - -# Redirect log messages to a log file, support file rolling. -log4j.appender.file=org.apache.log4j.RollingFileAppender -log4j.appender.file.File=D:\\Test\\xstream-application.log -log4j.appender.file.MaxFileSize=5MB -log4j.appender.file.MaxBackupIndex=10 -log4j.appender.file.layout=org.apache.log4j.PatternLayout -log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file From ed629e7a49f36ad0ec7dd40b22396f59e06efb39 Mon Sep 17 00:00:00 2001 From: David Morley Date: Mon, 4 Apr 2016 05:18:35 -0500 Subject: [PATCH 42/47] Clean up XStream examples --- xstream-introduction/.project | 14 ----- .../baeldung/annotation/pojo/Customer.java | 46 -------------- .../annotation/pojo/CustomerOmitField.java | 50 --------------- .../baeldung/complex/pojo/ContactDetails.java | 46 -------------- .../com/baeldung/complex/pojo/Customer.java | 57 ----------------- .../collection/pojo/ContactDetails.java | 46 -------------- .../implicit/collection/pojo/Customer.java | 59 ------------------ .../initializer/SimpleXstreamInitializer.java | 19 ------ .../com/baeldung/pojo/AddressDetails.java | 40 ------------ .../com/baeldung/pojo/ContactDetails.java | 28 --------- .../main/java/com/baeldung/pojo/Customer.java | 57 ----------------- .../baeldung/pojo/CustomerAddressDetails.java | 50 --------------- .../com/baeldung/pojo/CustomerPortfolio.java | 20 ------ .../com/baeldung/utility/MyDateConverter.java | 40 ------------ .../utility/MySingleValueConverter.java | 28 --------- .../utility/SimpleDataGeneration.java | 37 ----------- .../ComplexXmlToObjectAnnotationTest.java | 39 ------------ ...lexXmlToObjectAttributeCollectionTest.java | 43 ------------- .../ComplexXmlToObjectCollectionTest.java | 40 ------------ .../pojo/test/XmlToObjectAliasTest.java | 38 ------------ .../pojo/test/XmlToObjectAnnotationTest.java | 39 ------------ .../pojo/test/XmlToObjectFieldAliasTest.java | 40 ------------ .../test/XmlToObjectIgnoreFieldsTest.java | 39 ------------ .../baeldung/pojo/test/XmlToObjectTest.java | 47 -------------- .../utility/XStreamSimpleXmlTest.java | 61 ------------------- .../data-file-alias-field-complex.xml | 15 ----- .../test/resources/data-file-alias-field.xml | 5 -- .../data-file-alias-implicit-collection.xml | 13 ---- .../src/test/resources/data-file-alias.xml | 5 -- .../test/resources/data-file-ignore-field.xml | 6 -- .../src/test/resources/data-file.xml | 5 -- {xstream-introduction => xstream}/pom.xml | 14 +++++ .../baeldung/annotation/pojo/Customer.java | 46 ++++++++++++++ .../annotation/pojo/CustomerOmitField.java | 50 +++++++++++++++ .../baeldung/complex/pojo/ContactDetails.java | 46 ++++++++++++++ .../com/baeldung/complex/pojo/Customer.java | 57 +++++++++++++++++ .../collection/pojo/ContactDetails.java | 46 ++++++++++++++ .../implicit/collection/pojo/Customer.java | 59 ++++++++++++++++++ .../initializer/SimpleXstreamInitializer.java | 19 ++++++ .../com/baeldung/pojo/AddressDetails.java | 40 ++++++++++++ .../com/baeldung/pojo/ContactDetails.java | 28 +++++++++ .../main/java/com/baeldung/pojo/Customer.java | 57 +++++++++++++++++ .../baeldung/pojo/CustomerAddressDetails.java | 50 +++++++++++++++ .../com/baeldung/pojo/CustomerPortfolio.java | 20 ++++++ .../com/baeldung/utility/MyDateConverter.java | 40 ++++++++++++ .../utility/MySingleValueConverter.java | 28 +++++++++ .../utility/SimpleDataGeneration.java | 37 +++++++++++ .../src/main/resources/log4j.properties | 0 .../ComplexXmlToObjectAnnotationTest.java | 38 ++++++++++++ ...lexXmlToObjectAttributeCollectionTest.java | 42 +++++++++++++ .../ComplexXmlToObjectCollectionTest.java | 39 ++++++++++++ .../pojo/test/XmlToObjectAliasTest.java | 37 +++++++++++ .../pojo/test/XmlToObjectAnnotationTest.java | 38 ++++++++++++ .../pojo/test/XmlToObjectFieldAliasTest.java | 39 ++++++++++++ .../test/XmlToObjectIgnoreFieldsTest.java | 38 ++++++++++++ .../baeldung/pojo/test/XmlToObjectTest.java | 46 ++++++++++++++ .../utility/XStreamSimpleXmlTest.java | 57 +++++++++++++++++ .../data-file-alias-field-complex.xml | 15 +++++ .../test/resources/data-file-alias-field.xml | 5 ++ .../data-file-alias-implicit-collection.xml | 13 ++++ .../src/test/resources/data-file-alias.xml | 5 ++ .../test/resources/data-file-ignore-field.xml | 6 ++ xstream/src/test/resources/data-file.xml | 5 ++ 63 files changed, 1060 insertions(+), 1072 deletions(-) delete mode 100644 xstream-introduction/.project delete mode 100644 xstream-introduction/src/main/java/com/baeldung/annotation/pojo/Customer.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/complex/pojo/ContactDetails.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/complex/pojo/Customer.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/pojo/AddressDetails.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/pojo/ContactDetails.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/pojo/Customer.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/pojo/CustomerPortfolio.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/utility/MyDateConverter.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/utility/MySingleValueConverter.java delete mode 100644 xstream-introduction/src/main/java/com/baeldung/utility/SimpleDataGeneration.java delete mode 100644 xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java delete mode 100644 xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java delete mode 100644 xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java delete mode 100644 xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java delete mode 100644 xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java delete mode 100644 xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java delete mode 100644 xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java delete mode 100644 xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java delete mode 100644 xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java delete mode 100644 xstream-introduction/src/test/resources/data-file-alias-field-complex.xml delete mode 100644 xstream-introduction/src/test/resources/data-file-alias-field.xml delete mode 100644 xstream-introduction/src/test/resources/data-file-alias-implicit-collection.xml delete mode 100644 xstream-introduction/src/test/resources/data-file-alias.xml delete mode 100644 xstream-introduction/src/test/resources/data-file-ignore-field.xml delete mode 100644 xstream-introduction/src/test/resources/data-file.xml rename {xstream-introduction => xstream}/pom.xml (75%) create mode 100644 xstream/src/main/java/com/baeldung/annotation/pojo/Customer.java create mode 100644 xstream/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java create mode 100644 xstream/src/main/java/com/baeldung/complex/pojo/ContactDetails.java create mode 100644 xstream/src/main/java/com/baeldung/complex/pojo/Customer.java create mode 100644 xstream/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java create mode 100644 xstream/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java create mode 100644 xstream/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java create mode 100644 xstream/src/main/java/com/baeldung/pojo/AddressDetails.java create mode 100644 xstream/src/main/java/com/baeldung/pojo/ContactDetails.java create mode 100644 xstream/src/main/java/com/baeldung/pojo/Customer.java create mode 100644 xstream/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java create mode 100644 xstream/src/main/java/com/baeldung/pojo/CustomerPortfolio.java create mode 100644 xstream/src/main/java/com/baeldung/utility/MyDateConverter.java create mode 100644 xstream/src/main/java/com/baeldung/utility/MySingleValueConverter.java create mode 100644 xstream/src/main/java/com/baeldung/utility/SimpleDataGeneration.java rename {xstream-introduction => xstream}/src/main/resources/log4j.properties (100%) create mode 100644 xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java create mode 100644 xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java create mode 100644 xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java create mode 100644 xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java create mode 100644 xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java create mode 100644 xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java create mode 100644 xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java create mode 100644 xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java create mode 100644 xstream/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java create mode 100644 xstream/src/test/resources/data-file-alias-field-complex.xml create mode 100644 xstream/src/test/resources/data-file-alias-field.xml create mode 100644 xstream/src/test/resources/data-file-alias-implicit-collection.xml create mode 100644 xstream/src/test/resources/data-file-alias.xml create mode 100644 xstream/src/test/resources/data-file-ignore-field.xml create mode 100644 xstream/src/test/resources/data-file.xml diff --git a/xstream-introduction/.project b/xstream-introduction/.project deleted file mode 100644 index cebf3c9cfa..0000000000 --- a/xstream-introduction/.project +++ /dev/null @@ -1,14 +0,0 @@ - - - xstream-introduction - An Introduction To XStream. NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. - - - - org.eclipse.jdt.core.javabuilder - - - - org.eclipse.jdt.core.javanature - - \ No newline at end of file diff --git a/xstream-introduction/src/main/java/com/baeldung/annotation/pojo/Customer.java b/xstream-introduction/src/main/java/com/baeldung/annotation/pojo/Customer.java deleted file mode 100644 index 42d1d039b0..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/annotation/pojo/Customer.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.annotation.pojo; - -import java.util.Date; - -import com.thoughtworks.xstream.annotations.XStreamAlias; - -@XStreamAlias("customer") -public class Customer { - - @XStreamAlias("fn") - private String firstName; - - private String lastName; - - private Date dob; - - 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 Date getDob() { - return dob; - } - - public void setDob(Date dob) { - this.dob = dob; - } - - @Override - public String toString() { - return "Customer [firstName=" + firstName + ", lastName=" + lastName - + ", dob=" + dob + "]"; - } -} diff --git a/xstream-introduction/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java b/xstream-introduction/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java deleted file mode 100644 index 881d7a5fc7..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.annotation.pojo; - -import java.util.Date; - -import com.thoughtworks.xstream.annotations.XStreamAlias; -import com.thoughtworks.xstream.annotations.XStreamOmitField; - - -@XStreamAlias("customer") -public class CustomerOmitField { - - @XStreamOmitField - private String firstName; - - private String lastName; - - private Date dob; - - 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 Date getDob() { - return dob; - } - - public void setDob(Date dob) { - this.dob = dob; - } - - @Override - public String toString() { - return "CustomerOmitAnnotation [firstName=" + firstName + ", lastName=" - + lastName + ", dob=" + dob + "]"; - } - - -} diff --git a/xstream-introduction/src/main/java/com/baeldung/complex/pojo/ContactDetails.java b/xstream-introduction/src/main/java/com/baeldung/complex/pojo/ContactDetails.java deleted file mode 100644 index 88e721a84b..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/complex/pojo/ContactDetails.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.complex.pojo; - -import com.thoughtworks.xstream.annotations.XStreamAlias; -import com.thoughtworks.xstream.annotations.XStreamAsAttribute; - -@XStreamAlias("ContactDetails") -public class ContactDetails { - - private String mobile; - - private String landline; - - @XStreamAsAttribute - private String contactType; - - public String getMobile() { - return mobile; - } - - public void setMobile(String mobile) { - this.mobile = mobile; - } - - public String getLandline() { - return landline; - } - - public void setLandline(String landline) { - this.landline = landline; - } - - public String getContactType() { - return contactType; - } - - public void setContactType(String contactType) { - this.contactType = contactType; - } - - @Override - public String toString() { - return "ContactDetails [mobile=" + mobile + ", landline=" + landline - + ", contactType=" + contactType + "]"; - } - -} diff --git a/xstream-introduction/src/main/java/com/baeldung/complex/pojo/Customer.java b/xstream-introduction/src/main/java/com/baeldung/complex/pojo/Customer.java deleted file mode 100644 index 0cc3160c03..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/complex/pojo/Customer.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.complex.pojo; - -import java.util.Date; -import java.util.List; - -import com.thoughtworks.xstream.annotations.XStreamAlias; - -@XStreamAlias("customer") -public class Customer { - - private String firstName; - - private String lastName; - - private Date dob; - - private List contactDetailsList; - - 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 Date getDob() { - return dob; - } - - public void setDob(Date dob) { - this.dob = dob; - } - - public List getContactDetailsList() { - return contactDetailsList; - } - - public void setContactDetailsList(List contactDetailsList) { - this.contactDetailsList = contactDetailsList; - } - - @Override - public String toString() { - return "Customer [firstName=" + firstName + ", lastName=" + lastName - + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList - + "]"; - } -} diff --git a/xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java b/xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java deleted file mode 100644 index 6d6a63bd7a..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.implicit.collection.pojo; - -import com.thoughtworks.xstream.annotations.XStreamAlias; -import com.thoughtworks.xstream.annotations.XStreamAsAttribute; - -@XStreamAlias("ContactDetails") -public class ContactDetails { - - private String mobile; - - private String landline; - - @XStreamAsAttribute - private String contactType; - - public String getMobile() { - return mobile; - } - - public void setMobile(String mobile) { - this.mobile = mobile; - } - - public String getLandline() { - return landline; - } - - public void setLandline(String landline) { - this.landline = landline; - } - - public String getContactType() { - return contactType; - } - - public void setContactType(String contactType) { - this.contactType = contactType; - } - - @Override - public String toString() { - return "ContactDetails [mobile=" + mobile + ", landline=" + landline - + ", contactType=" + contactType + "]"; - } - -} diff --git a/xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java b/xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java deleted file mode 100644 index acbeff165e..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.implicit.collection.pojo; - -import java.util.Date; -import java.util.List; - -import com.thoughtworks.xstream.annotations.XStreamAlias; -import com.thoughtworks.xstream.annotations.XStreamImplicit; - -@XStreamAlias("customer") -public class Customer { - - private String firstName; - - private String lastName; - - private Date dob; - - @XStreamImplicit - private List contactDetailsList; - - 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 Date getDob() { - return dob; - } - - public void setDob(Date dob) { - this.dob = dob; - } - - public List getContactDetailsList() { - return contactDetailsList; - } - - public void setContactDetailsList(List contactDetailsList) { - this.contactDetailsList = contactDetailsList; - } - - @Override - public String toString() { - return "Customer [firstName=" + firstName + ", lastName=" + lastName - + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList - + "]"; - } -} diff --git a/xstream-introduction/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java b/xstream-introduction/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java deleted file mode 100644 index d7dc3f7a81..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.initializer; - -import com.thoughtworks.xstream.XStream; - -public class SimpleXstreamInitializer { - - private XStream xtreamInstance; - - public XStream getXstreamInstance() { - if (xtreamInstance == null) { - synchronized (SimpleXstreamInitializer.class) { - if (xtreamInstance == null) { - xtreamInstance = new XStream(); - } - } - } - return xtreamInstance; - } -} \ No newline at end of file diff --git a/xstream-introduction/src/main/java/com/baeldung/pojo/AddressDetails.java b/xstream-introduction/src/main/java/com/baeldung/pojo/AddressDetails.java deleted file mode 100644 index e9e30bf5fc..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/pojo/AddressDetails.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.pojo; - -import java.util.List; - -import com.thoughtworks.xstream.annotations.XStreamAlias; - -@XStreamAlias("AddressDetails") -public class AddressDetails { - - private String address; - - private String zipcode; - - private List contactDetails; - - public String getZipcode() { - return zipcode; - } - - public void setZipcode(String zipcode) { - this.zipcode = zipcode; - } - - public List getContactDetails() { - return contactDetails; - } - - public void setContactDetails(List contactDetails) { - this.contactDetails = contactDetails; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - -} diff --git a/xstream-introduction/src/main/java/com/baeldung/pojo/ContactDetails.java b/xstream-introduction/src/main/java/com/baeldung/pojo/ContactDetails.java deleted file mode 100644 index 66475b9d8e..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/pojo/ContactDetails.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.pojo; - -import com.thoughtworks.xstream.annotations.XStreamAlias; - -@XStreamAlias("ContactDetails") -public class ContactDetails { - - private String mobile; - - private String landline; - - public String getMobile() { - return mobile; - } - - public void setMobile(String mobile) { - this.mobile = mobile; - } - - public String getLandline() { - return landline; - } - - public void setLandline(String landline) { - this.landline = landline; - } - -} diff --git a/xstream-introduction/src/main/java/com/baeldung/pojo/Customer.java b/xstream-introduction/src/main/java/com/baeldung/pojo/Customer.java deleted file mode 100644 index 9bed3394ef..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/pojo/Customer.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.pojo; - -import java.util.Date; -import java.util.List; - -import com.thoughtworks.xstream.annotations.XStreamAlias; -import com.thoughtworks.xstream.annotations.XStreamImplicit; - -@XStreamAlias("customer") -public class Customer { - - private String firstName; - - private String lastName; - - private Date dob; - - @XStreamImplicit - private List contactDetailsList; - - 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 Date getDob() { - return dob; - } - - public void setDob(Date dob) { - this.dob = dob; - } - - public List getContactDetailsList() { - return contactDetailsList; - } - - public void setContactDetailsList(List contactDetailsList) { - this.contactDetailsList = contactDetailsList; - } - - @Override - public String toString() { - return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]"; - } -} diff --git a/xstream-introduction/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java b/xstream-introduction/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java deleted file mode 100644 index 30fda1b92c..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.pojo; - -import java.util.List; - -import com.thoughtworks.xstream.annotations.XStreamAlias; - -@XStreamAlias("CustomerAddressDetails") -public class CustomerAddressDetails { - - private List addressDetails; - - private String firstName; - - private String lastName; - - private int age; - - 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 int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - - public List getAddressDetails() { - return addressDetails; - } - - public void setAddressDetails(List addressDetails) { - this.addressDetails = addressDetails; - } -} diff --git a/xstream-introduction/src/main/java/com/baeldung/pojo/CustomerPortfolio.java b/xstream-introduction/src/main/java/com/baeldung/pojo/CustomerPortfolio.java deleted file mode 100644 index 6f1ce4b651..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/pojo/CustomerPortfolio.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.pojo; - -import java.util.List; - -import com.thoughtworks.xstream.annotations.XStreamAlias; - -@XStreamAlias("CustomerPortfolio") -public class CustomerPortfolio { - - private List customerAddressDetailsList; - - public List getCustomerAddressDetailsList() { - return customerAddressDetailsList; - } - - public void setCustomerAddressDetailsList(List customerAddressDetailsList) { - this.customerAddressDetailsList = customerAddressDetailsList; - } - -} diff --git a/xstream-introduction/src/main/java/com/baeldung/utility/MyDateConverter.java b/xstream-introduction/src/main/java/com/baeldung/utility/MyDateConverter.java deleted file mode 100644 index 564a28d1c5..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/utility/MyDateConverter.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.utility; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.GregorianCalendar; - -import com.thoughtworks.xstream.converters.ConversionException; -import com.thoughtworks.xstream.converters.Converter; -import com.thoughtworks.xstream.converters.MarshallingContext; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import com.thoughtworks.xstream.io.HierarchicalStreamWriter; - -public class MyDateConverter implements Converter { - - private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); - - @Override - public boolean canConvert(Class clazz) { - return Date.class.isAssignableFrom(clazz); - } - - @Override - public void marshal(Object value , HierarchicalStreamWriter writer , MarshallingContext arg2) { - Date date = (Date) value; - writer.setValue(formatter.format(date)); - } - - @Override - public Object unmarshal(HierarchicalStreamReader reader , UnmarshallingContext arg1) { - GregorianCalendar calendar = new GregorianCalendar(); - try { - calendar.setTime(formatter.parse(reader.getValue())); - } catch (ParseException e) { - throw new ConversionException(e.getMessage() , e); - } - return calendar; - } -} diff --git a/xstream-introduction/src/main/java/com/baeldung/utility/MySingleValueConverter.java b/xstream-introduction/src/main/java/com/baeldung/utility/MySingleValueConverter.java deleted file mode 100644 index 358d647835..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/utility/MySingleValueConverter.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.utility; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.baeldung.pojo.Customer; -import com.thoughtworks.xstream.converters.SingleValueConverter; - -public class MySingleValueConverter implements SingleValueConverter { - - @Override - public boolean canConvert(Class clazz) { - return Customer.class.isAssignableFrom(clazz); - } - - @Override - public Object fromString(String arg0) { - return null; - } - - @Override - public String toString(Object obj) { - SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); - Date date = ((Customer) obj).getDob(); - return ((Customer) obj).getFirstName() + "," + ((Customer) obj).getLastName() + "," + formatter.format(date); - } - -} diff --git a/xstream-introduction/src/main/java/com/baeldung/utility/SimpleDataGeneration.java b/xstream-introduction/src/main/java/com/baeldung/utility/SimpleDataGeneration.java deleted file mode 100644 index 22d0f0ce77..0000000000 --- a/xstream-introduction/src/main/java/com/baeldung/utility/SimpleDataGeneration.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.utility; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - -import com.baeldung.pojo.ContactDetails; -import com.baeldung.pojo.Customer; - -public class SimpleDataGeneration { - - public static Customer generateData() { - Customer customer = new Customer(); - Calendar cal = Calendar.getInstance(); - cal.set(1986 , 01 , 14); - customer.setDob(cal.getTime()); - customer.setFirstName("XStream"); - customer.setLastName("Java"); - - List contactDetailsList = new ArrayList(); - - ContactDetails contactDetails1 = new ContactDetails(); - contactDetails1.setLandline("0124-2460311"); - contactDetails1.setMobile("6673543265"); - - ContactDetails contactDetails2 = new ContactDetails(); - contactDetails2.setLandline("0120-223312"); - contactDetails2.setMobile("4676543565"); - - contactDetailsList.add(contactDetails1); - contactDetailsList.add(contactDetails2); - - customer.setContactDetailsList(contactDetailsList); - return customer; - } - -} diff --git a/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java deleted file mode 100644 index 10f59e843b..0000000000 --- a/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.pojo.test; - -import java.io.FileReader; -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.complex.pojo.Customer; -import com.baeldung.initializer.SimpleXstreamInitializer; -import com.thoughtworks.xstream.XStream; - -public class ComplexXmlToObjectAnnotationTest { - - private XStream xstream = null; - - @Before - public void dataSetup() { - SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); - xstream = simpleXstreamInitializer.getXstreamInstance(); - xstream.processAnnotations(Customer.class); - } - - @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field-complex.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - Assert.assertNotNull(customer.getContactDetailsList()); - - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java deleted file mode 100644 index 876a407f76..0000000000 --- a/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.pojo.test; - -import java.io.FileReader; -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.complex.pojo.ContactDetails; -import com.baeldung.complex.pojo.Customer; -import com.baeldung.initializer.SimpleXstreamInitializer; -import com.thoughtworks.xstream.XStream; - -public class ComplexXmlToObjectAttributeCollectionTest { - - private XStream xstream = null; - - @Before - public void dataSetup() { - SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); - xstream = simpleXstreamInitializer.getXstreamInstance(); - xstream.processAnnotations(Customer.class); - } - - @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field-complex.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - Assert.assertNotNull(customer.getContactDetailsList()); - for(ContactDetails contactDetails : customer.getContactDetailsList()){ - Assert.assertNotNull(contactDetails.getContactType()); - } - - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java deleted file mode 100644 index d701fc153b..0000000000 --- a/xstream-introduction/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.pojo.test; - -import java.io.FileReader; -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.implicit.collection.pojo.Customer; -import com.baeldung.initializer.SimpleXstreamInitializer; -import com.thoughtworks.xstream.XStream; - -public class ComplexXmlToObjectCollectionTest { - - private XStream xstream = null; - - @Before - public void dataSetup() { - SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); - xstream = simpleXstreamInitializer.getXstreamInstance(); - xstream.processAnnotations(Customer.class); - } - - @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-alias-implicit-collection.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - Assert.assertNotNull(customer.getContactDetailsList()); - //System.out.println(customer); - - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java deleted file mode 100644 index cc6d945254..0000000000 --- a/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.pojo.test; - -import java.io.FileReader; -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.initializer.SimpleXstreamInitializer; -import com.baeldung.pojo.Customer; -import com.thoughtworks.xstream.XStream; - -public class XmlToObjectAliasTest { - - private XStream xstream = null; - - @Before - public void dataSetup() { - SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); - xstream = simpleXstreamInitializer.getXstreamInstance(); - xstream.alias("customer" , Customer.class); - } - - @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-alias.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java deleted file mode 100644 index f2012e2b12..0000000000 --- a/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.pojo.test; - -import java.io.FileReader; -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.annotation.pojo.Customer; -import com.baeldung.initializer.SimpleXstreamInitializer; -import com.thoughtworks.xstream.XStream; - -public class XmlToObjectAnnotationTest { - - private XStream xstream = null; - - @Before - public void dataSetup() { - SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); - xstream = simpleXstreamInitializer.getXstreamInstance(); - xstream.processAnnotations(Customer.class); - } - - @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - Assert.assertNotNull(customer.getFirstName()); - - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java deleted file mode 100644 index c4bba86265..0000000000 --- a/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.pojo.test; - -import java.io.FileReader; -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.initializer.SimpleXstreamInitializer; -import com.baeldung.pojo.Customer; -import com.thoughtworks.xstream.XStream; - -public class XmlToObjectFieldAliasTest { - - private XStream xstream = null; - - @Before - public void dataSetup() { - SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); - xstream = simpleXstreamInitializer.getXstreamInstance(); - xstream.alias("customer" , Customer.class); - xstream.aliasField("fn", Customer.class, "firstName"); - } - - @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - Assert.assertNotNull(customer.getFirstName()); - - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java deleted file mode 100644 index cb13bb9570..0000000000 --- a/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.pojo.test; - -import java.io.FileReader; -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.initializer.SimpleXstreamInitializer; -import com.baeldung.pojo.Customer; -import com.thoughtworks.xstream.XStream; - -public class XmlToObjectIgnoreFieldsTest { - - private XStream xstream = null; - - @Before - public void dataSetup() { - SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); - xstream = simpleXstreamInitializer.getXstreamInstance(); - xstream.alias("customer" , Customer.class); - xstream.ignoreUnknownElements(); - } - - @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file-ignore-field.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - //System.out.println(customer); - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java b/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java deleted file mode 100644 index e24e54aea4..0000000000 --- a/xstream-introduction/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.pojo.test; - -import java.io.FileReader; -import java.io.IOException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.initializer.SimpleXstreamInitializer; -import com.baeldung.pojo.Customer; -import com.baeldung.utility.SimpleDataGeneration; -import com.thoughtworks.xstream.XStream; - -public class XmlToObjectTest { - - private XStream xstream = null; - - @Before - public void dataSetup() { - SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); - xstream = simpleXstreamInitializer.getXstreamInstance(); - } - - @Test - public void convertXmlToObjectFromFile() { - try { - ClassLoader classLoader = getClass().getClassLoader(); - FileReader reader = new FileReader(classLoader.getResource("data-file.xml").getFile()); - Customer customer = (Customer) xstream.fromXML(reader); - Assert.assertNotNull(customer); - - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test - public void convertXmlToObjectFromString() { - Customer customer = SimpleDataGeneration.generateData(); - String dataXml = xstream.toXML(customer); - Customer convertedCustomer = (Customer) xstream.fromXML(dataXml); - Assert.assertNotNull(convertedCustomer); - } - - -} diff --git a/xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java b/xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java deleted file mode 100644 index ea60e68743..0000000000 --- a/xstream-introduction/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.utility; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.initializer.SimpleXstreamInitializer; -import com.baeldung.pojo.AddressDetails; -import com.baeldung.pojo.ContactDetails; -import com.baeldung.pojo.Customer; -import com.baeldung.utility.SimpleDataGeneration; -import com.thoughtworks.xstream.XStream; - -public class XStreamSimpleXmlTest { - - private Customer customer = null; - - private String dataXml = null; - - private XStream xstream = null; - - @Before - public void dataSetup() { - customer = SimpleDataGeneration.generateData(); - SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); - xstream = simpleXstreamInitializer.getXstreamInstance(); - xstream.processAnnotations(Customer.class); - xstream.processAnnotations(AddressDetails.class); - xstream.processAnnotations(ContactDetails.class); - xstream.omitField(Customer.class , "lastName"); - xstream.registerConverter(new MyDateConverter()); - // xstream.registerConverter(new MySingleValueConverter()); - xstream.aliasField("fn" , Customer.class , "firstName"); - dataXml = xstream.toXML(customer); - } - - @Test - public void testClassAliasedAnnotation() { - Assert.assertNotEquals(-1 , dataXml.indexOf("")); - } - - @Test - public void testFieldAliasedAnnotation() { - Assert.assertNotEquals(-1 , dataXml.indexOf("")); - } - - @Test - public void testImplicitCollection() { - Assert.assertEquals(-1 , dataXml.indexOf("contactDetailsList")); - } - - @Test - public void testDateFieldFormating() { - Assert.assertEquals("14-02-1986" , dataXml.substring(dataXml.indexOf("") + 5 , dataXml.indexOf(""))); - } - - @Test - public void testOmitField() { - Assert.assertEquals(-1 , dataXml.indexOf("lastName")); - } -} diff --git a/xstream-introduction/src/test/resources/data-file-alias-field-complex.xml b/xstream-introduction/src/test/resources/data-file-alias-field-complex.xml deleted file mode 100644 index 2235aa7044..0000000000 --- a/xstream-introduction/src/test/resources/data-file-alias-field-complex.xml +++ /dev/null @@ -1,15 +0,0 @@ - - XStream - Java - 1986-02-14 04:14:05.874 UTC - - - 6673543265 - 0124-2460311 - - - 4676543565 - 0120-223312 - - - \ No newline at end of file diff --git a/xstream-introduction/src/test/resources/data-file-alias-field.xml b/xstream-introduction/src/test/resources/data-file-alias-field.xml deleted file mode 100644 index 9bc1d0990a..0000000000 --- a/xstream-introduction/src/test/resources/data-file-alias-field.xml +++ /dev/null @@ -1,5 +0,0 @@ - - XStream - Java - 1986-02-14 03:46:16.381 UTC - \ No newline at end of file diff --git a/xstream-introduction/src/test/resources/data-file-alias-implicit-collection.xml b/xstream-introduction/src/test/resources/data-file-alias-implicit-collection.xml deleted file mode 100644 index d8731900b9..0000000000 --- a/xstream-introduction/src/test/resources/data-file-alias-implicit-collection.xml +++ /dev/null @@ -1,13 +0,0 @@ - - XStream - Java - 1986-02-14 04:14:20.541 UTC - - 6673543265 - 0124-2460311 - - - 4676543565 - 0120-223312 - - \ No newline at end of file diff --git a/xstream-introduction/src/test/resources/data-file-alias.xml b/xstream-introduction/src/test/resources/data-file-alias.xml deleted file mode 100644 index 964157f1dd..0000000000 --- a/xstream-introduction/src/test/resources/data-file-alias.xml +++ /dev/null @@ -1,5 +0,0 @@ - - XStream - Java - 1986-02-14 03:46:16.381 UTC - \ No newline at end of file diff --git a/xstream-introduction/src/test/resources/data-file-ignore-field.xml b/xstream-introduction/src/test/resources/data-file-ignore-field.xml deleted file mode 100644 index 865e93d4b4..0000000000 --- a/xstream-introduction/src/test/resources/data-file-ignore-field.xml +++ /dev/null @@ -1,6 +0,0 @@ - - XStream - Java - 1986-02-14 04:14:20.541 UTC - XStream Java - \ No newline at end of file diff --git a/xstream-introduction/src/test/resources/data-file.xml b/xstream-introduction/src/test/resources/data-file.xml deleted file mode 100644 index 59f2ea1cca..0000000000 --- a/xstream-introduction/src/test/resources/data-file.xml +++ /dev/null @@ -1,5 +0,0 @@ - - XStream - Java - 1986-02-14 03:46:16.381 UTC - \ No newline at end of file diff --git a/xstream-introduction/pom.xml b/xstream/pom.xml similarity index 75% rename from xstream-introduction/pom.xml rename to xstream/pom.xml index 2f0f26d6f2..8a5aec41e9 100644 --- a/xstream-introduction/pom.xml +++ b/xstream/pom.xml @@ -27,4 +27,18 @@
+ + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/xstream/src/main/java/com/baeldung/annotation/pojo/Customer.java b/xstream/src/main/java/com/baeldung/annotation/pojo/Customer.java new file mode 100644 index 0000000000..2cdb0f56c9 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/annotation/pojo/Customer.java @@ -0,0 +1,46 @@ +package com.baeldung.annotation.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import java.util.Date; + +@XStreamAlias("customer") +public class Customer { + + @XStreamAlias("fn") + private String firstName; + + private String lastName; + + private Date dob; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + + ", dob=" + dob + "]"; + } +} diff --git a/xstream/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java b/xstream/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java new file mode 100644 index 0000000000..f5b98c9c1b --- /dev/null +++ b/xstream/src/main/java/com/baeldung/annotation/pojo/CustomerOmitField.java @@ -0,0 +1,50 @@ +package com.baeldung.annotation.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamOmitField; + +import java.util.Date; + + +@XStreamAlias("customer") +public class CustomerOmitField { + + @XStreamOmitField + private String firstName; + + private String lastName; + + private Date dob; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + @Override + public String toString() { + return "CustomerOmitAnnotation [firstName=" + firstName + ", lastName=" + + lastName + ", dob=" + dob + "]"; + } + + +} diff --git a/xstream/src/main/java/com/baeldung/complex/pojo/ContactDetails.java b/xstream/src/main/java/com/baeldung/complex/pojo/ContactDetails.java new file mode 100644 index 0000000000..e091492a1a --- /dev/null +++ b/xstream/src/main/java/com/baeldung/complex/pojo/ContactDetails.java @@ -0,0 +1,46 @@ +package com.baeldung.complex.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("ContactDetails") +public class ContactDetails { + + private String mobile; + + private String landline; + + @XStreamAsAttribute + private String contactType; + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getLandline() { + return landline; + } + + public void setLandline(String landline) { + this.landline = landline; + } + + public String getContactType() { + return contactType; + } + + public void setContactType(String contactType) { + this.contactType = contactType; + } + + @Override + public String toString() { + return "ContactDetails [mobile=" + mobile + ", landline=" + landline + + ", contactType=" + contactType + "]"; + } + +} diff --git a/xstream/src/main/java/com/baeldung/complex/pojo/Customer.java b/xstream/src/main/java/com/baeldung/complex/pojo/Customer.java new file mode 100644 index 0000000000..c6f98982f0 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/complex/pojo/Customer.java @@ -0,0 +1,57 @@ +package com.baeldung.complex.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import java.util.Date; +import java.util.List; + +@XStreamAlias("customer") +public class Customer { + + private String firstName; + + private String lastName; + + private Date dob; + + private List contactDetailsList; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + public List getContactDetailsList() { + return contactDetailsList; + } + + public void setContactDetailsList(List contactDetailsList) { + this.contactDetailsList = contactDetailsList; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + + "]"; + } +} diff --git a/xstream/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java b/xstream/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java new file mode 100644 index 0000000000..38ec7ff077 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/implicit/collection/pojo/ContactDetails.java @@ -0,0 +1,46 @@ +package com.baeldung.implicit.collection.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamAsAttribute; + +@XStreamAlias("ContactDetails") +public class ContactDetails { + + private String mobile; + + private String landline; + + @XStreamAsAttribute + private String contactType; + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getLandline() { + return landline; + } + + public void setLandline(String landline) { + this.landline = landline; + } + + public String getContactType() { + return contactType; + } + + public void setContactType(String contactType) { + this.contactType = contactType; + } + + @Override + public String toString() { + return "ContactDetails [mobile=" + mobile + ", landline=" + landline + + ", contactType=" + contactType + "]"; + } + +} diff --git a/xstream/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java b/xstream/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java new file mode 100644 index 0000000000..a50ac850dd --- /dev/null +++ b/xstream/src/main/java/com/baeldung/implicit/collection/pojo/Customer.java @@ -0,0 +1,59 @@ +package com.baeldung.implicit.collection.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamImplicit; + +import java.util.Date; +import java.util.List; + +@XStreamAlias("customer") +public class Customer { + + private String firstName; + + private String lastName; + + private Date dob; + + @XStreamImplicit + private List contactDetailsList; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + public List getContactDetailsList() { + return contactDetailsList; + } + + public void setContactDetailsList(List contactDetailsList) { + this.contactDetailsList = contactDetailsList; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + + "]"; + } +} diff --git a/xstream/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java b/xstream/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java new file mode 100644 index 0000000000..5dec19d181 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/initializer/SimpleXstreamInitializer.java @@ -0,0 +1,19 @@ +package com.baeldung.initializer; + +import com.thoughtworks.xstream.XStream; + +public class SimpleXstreamInitializer { + + private XStream xtreamInstance; + + public XStream getXstreamInstance() { + if (xtreamInstance == null) { + synchronized (SimpleXstreamInitializer.class) { + if (xtreamInstance == null) { + xtreamInstance = new XStream(); + } + } + } + return xtreamInstance; + } +} \ No newline at end of file diff --git a/xstream/src/main/java/com/baeldung/pojo/AddressDetails.java b/xstream/src/main/java/com/baeldung/pojo/AddressDetails.java new file mode 100644 index 0000000000..53ba7e9a85 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/pojo/AddressDetails.java @@ -0,0 +1,40 @@ +package com.baeldung.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import java.util.List; + +@XStreamAlias("AddressDetails") +public class AddressDetails { + + private String address; + + private String zipcode; + + private List contactDetails; + + public String getZipcode() { + return zipcode; + } + + public void setZipcode(String zipcode) { + this.zipcode = zipcode; + } + + public List getContactDetails() { + return contactDetails; + } + + public void setContactDetails(List contactDetails) { + this.contactDetails = contactDetails; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + +} diff --git a/xstream/src/main/java/com/baeldung/pojo/ContactDetails.java b/xstream/src/main/java/com/baeldung/pojo/ContactDetails.java new file mode 100644 index 0000000000..75408bdba8 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/pojo/ContactDetails.java @@ -0,0 +1,28 @@ +package com.baeldung.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +@XStreamAlias("ContactDetails") +public class ContactDetails { + + private String mobile; + + private String landline; + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getLandline() { + return landline; + } + + public void setLandline(String landline) { + this.landline = landline; + } + +} diff --git a/xstream/src/main/java/com/baeldung/pojo/Customer.java b/xstream/src/main/java/com/baeldung/pojo/Customer.java new file mode 100644 index 0000000000..728939c356 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/pojo/Customer.java @@ -0,0 +1,57 @@ +package com.baeldung.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; +import com.thoughtworks.xstream.annotations.XStreamImplicit; + +import java.util.Date; +import java.util.List; + +@XStreamAlias("customer") +public class Customer { + + private String firstName; + + private String lastName; + + private Date dob; + + @XStreamImplicit + private List contactDetailsList; + + 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 Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + public List getContactDetailsList() { + return contactDetailsList; + } + + public void setContactDetailsList(List contactDetailsList) { + this.contactDetailsList = contactDetailsList; + } + + @Override + public String toString() { + return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]"; + } +} diff --git a/xstream/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java b/xstream/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java new file mode 100644 index 0000000000..f203c9cce9 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/pojo/CustomerAddressDetails.java @@ -0,0 +1,50 @@ +package com.baeldung.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import java.util.List; + +@XStreamAlias("CustomerAddressDetails") +public class CustomerAddressDetails { + + private List addressDetails; + + private String firstName; + + private String lastName; + + private int age; + + 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 int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + + public List getAddressDetails() { + return addressDetails; + } + + public void setAddressDetails(List addressDetails) { + this.addressDetails = addressDetails; + } +} diff --git a/xstream/src/main/java/com/baeldung/pojo/CustomerPortfolio.java b/xstream/src/main/java/com/baeldung/pojo/CustomerPortfolio.java new file mode 100644 index 0000000000..90722feb71 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/pojo/CustomerPortfolio.java @@ -0,0 +1,20 @@ +package com.baeldung.pojo; + +import com.thoughtworks.xstream.annotations.XStreamAlias; + +import java.util.List; + +@XStreamAlias("CustomerPortfolio") +public class CustomerPortfolio { + + private List customerAddressDetailsList; + + public List getCustomerAddressDetailsList() { + return customerAddressDetailsList; + } + + public void setCustomerAddressDetailsList(List customerAddressDetailsList) { + this.customerAddressDetailsList = customerAddressDetailsList; + } + +} diff --git a/xstream/src/main/java/com/baeldung/utility/MyDateConverter.java b/xstream/src/main/java/com/baeldung/utility/MyDateConverter.java new file mode 100644 index 0000000000..af7ca19aac --- /dev/null +++ b/xstream/src/main/java/com/baeldung/utility/MyDateConverter.java @@ -0,0 +1,40 @@ +package com.baeldung.utility; + +import com.thoughtworks.xstream.converters.ConversionException; +import com.thoughtworks.xstream.converters.Converter; +import com.thoughtworks.xstream.converters.MarshallingContext; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import com.thoughtworks.xstream.io.HierarchicalStreamWriter; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.GregorianCalendar; + +public class MyDateConverter implements Converter { + + private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); + + @Override + public boolean canConvert(Class clazz) { + return Date.class.isAssignableFrom(clazz); + } + + @Override + public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext arg2) { + Date date = (Date) value; + writer.setValue(formatter.format(date)); + } + + @Override + public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext arg1) { + GregorianCalendar calendar = new GregorianCalendar(); + try { + calendar.setTime(formatter.parse(reader.getValue())); + } catch (ParseException e) { + throw new ConversionException(e.getMessage(), e); + } + return calendar; + } +} diff --git a/xstream/src/main/java/com/baeldung/utility/MySingleValueConverter.java b/xstream/src/main/java/com/baeldung/utility/MySingleValueConverter.java new file mode 100644 index 0000000000..9b242f1c7c --- /dev/null +++ b/xstream/src/main/java/com/baeldung/utility/MySingleValueConverter.java @@ -0,0 +1,28 @@ +package com.baeldung.utility; + +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.converters.SingleValueConverter; + +import java.text.SimpleDateFormat; +import java.util.Date; + +public class MySingleValueConverter implements SingleValueConverter { + + @Override + public boolean canConvert(Class clazz) { + return Customer.class.isAssignableFrom(clazz); + } + + @Override + public Object fromString(String arg0) { + return null; + } + + @Override + public String toString(Object obj) { + SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); + Date date = ((Customer) obj).getDob(); + return ((Customer) obj).getFirstName() + "," + ((Customer) obj).getLastName() + "," + formatter.format(date); + } + +} diff --git a/xstream/src/main/java/com/baeldung/utility/SimpleDataGeneration.java b/xstream/src/main/java/com/baeldung/utility/SimpleDataGeneration.java new file mode 100644 index 0000000000..cf038bfd1b --- /dev/null +++ b/xstream/src/main/java/com/baeldung/utility/SimpleDataGeneration.java @@ -0,0 +1,37 @@ +package com.baeldung.utility; + +import com.baeldung.pojo.ContactDetails; +import com.baeldung.pojo.Customer; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +public class SimpleDataGeneration { + + public static Customer generateData() { + Customer customer = new Customer(); + Calendar cal = Calendar.getInstance(); + cal.set(1986, 01, 14); + customer.setDob(cal.getTime()); + customer.setFirstName("XStream"); + customer.setLastName("Java"); + + List contactDetailsList = new ArrayList(); + + ContactDetails contactDetails1 = new ContactDetails(); + contactDetails1.setLandline("0124-2460311"); + contactDetails1.setMobile("6673543265"); + + ContactDetails contactDetails2 = new ContactDetails(); + contactDetails2.setLandline("0120-223312"); + contactDetails2.setMobile("4676543565"); + + contactDetailsList.add(contactDetails1); + contactDetailsList.add(contactDetails2); + + customer.setContactDetailsList(contactDetailsList); + return customer; + } + +} diff --git a/xstream-introduction/src/main/resources/log4j.properties b/xstream/src/main/resources/log4j.properties similarity index 100% rename from xstream-introduction/src/main/resources/log4j.properties rename to xstream/src/main/resources/log4j.properties diff --git a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java new file mode 100644 index 0000000000..479500c4a0 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAnnotationTest.java @@ -0,0 +1,38 @@ +package com.baeldung.pojo.test; + +import com.baeldung.complex.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class ComplexXmlToObjectAnnotationTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field-complex.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getContactDetailsList()); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java new file mode 100644 index 0000000000..8c569aa11e --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectAttributeCollectionTest.java @@ -0,0 +1,42 @@ +package com.baeldung.pojo.test; + +import com.baeldung.complex.pojo.ContactDetails; +import com.baeldung.complex.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class ComplexXmlToObjectAttributeCollectionTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field-complex.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getContactDetailsList()); + for (ContactDetails contactDetails : customer.getContactDetailsList()) { + Assert.assertNotNull(contactDetails.getContactType()); + } + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java new file mode 100644 index 0000000000..29ef7a5d64 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/ComplexXmlToObjectCollectionTest.java @@ -0,0 +1,39 @@ +package com.baeldung.pojo.test; + +import com.baeldung.implicit.collection.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class ComplexXmlToObjectCollectionTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-implicit-collection.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getContactDetailsList()); + //System.out.println(customer); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java new file mode 100644 index 0000000000..8a4de3b70a --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAliasTest.java @@ -0,0 +1,37 @@ +package com.baeldung.pojo.test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class XmlToObjectAliasTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.alias("customer", Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java new file mode 100644 index 0000000000..4a7ff2f74a --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectAnnotationTest.java @@ -0,0 +1,38 @@ +package com.baeldung.pojo.test; + +import com.baeldung.annotation.pojo.Customer; +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class XmlToObjectAnnotationTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getFirstName()); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java new file mode 100644 index 0000000000..3b1b8326ab --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectFieldAliasTest.java @@ -0,0 +1,39 @@ +package com.baeldung.pojo.test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class XmlToObjectFieldAliasTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.alias("customer", Customer.class); + xstream.aliasField("fn", Customer.class, "firstName"); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-alias-field.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + Assert.assertNotNull(customer.getFirstName()); + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java new file mode 100644 index 0000000000..95a034b3e7 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectIgnoreFieldsTest.java @@ -0,0 +1,38 @@ +package com.baeldung.pojo.test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class XmlToObjectIgnoreFieldsTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.alias("customer", Customer.class); + xstream.ignoreUnknownElements(); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file-ignore-field.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + //System.out.println(customer); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java new file mode 100644 index 0000000000..b6b64ce8da --- /dev/null +++ b/xstream/src/test/java/com/baeldung/pojo/test/XmlToObjectTest.java @@ -0,0 +1,46 @@ +package com.baeldung.pojo.test; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.Customer; +import com.baeldung.utility.SimpleDataGeneration; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; + +public class XmlToObjectTest { + + private XStream xstream = null; + + @Before + public void dataSetup() { + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + } + + @Test + public void convertXmlToObjectFromFile() { + try { + ClassLoader classLoader = getClass().getClassLoader(); + FileReader reader = new FileReader(classLoader.getResource("data-file.xml").getFile()); + Customer customer = (Customer) xstream.fromXML(reader); + Assert.assertNotNull(customer); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void convertXmlToObjectFromString() { + Customer customer = SimpleDataGeneration.generateData(); + String dataXml = xstream.toXML(customer); + Customer convertedCustomer = (Customer) xstream.fromXML(dataXml); + Assert.assertNotNull(convertedCustomer); + } + + +} diff --git a/xstream/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java b/xstream/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java new file mode 100644 index 0000000000..83a965ce1b --- /dev/null +++ b/xstream/src/test/java/com/baeldung/utility/XStreamSimpleXmlTest.java @@ -0,0 +1,57 @@ +package com.baeldung.utility; + +import com.baeldung.initializer.SimpleXstreamInitializer; +import com.baeldung.pojo.AddressDetails; +import com.baeldung.pojo.ContactDetails; +import com.baeldung.pojo.Customer; +import com.thoughtworks.xstream.XStream; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class XStreamSimpleXmlTest { + + private Customer customer; + private String dataXml; + private XStream xstream; + + @Before + public void dataSetup() { + customer = SimpleDataGeneration.generateData(); + SimpleXstreamInitializer simpleXstreamInitializer = new SimpleXstreamInitializer(); + xstream = simpleXstreamInitializer.getXstreamInstance(); + xstream.processAnnotations(Customer.class); + xstream.processAnnotations(AddressDetails.class); + xstream.processAnnotations(ContactDetails.class); + xstream.omitField(Customer.class, "lastName"); + xstream.registerConverter(new MyDateConverter()); + // xstream.registerConverter(new MySingleValueConverter()); + xstream.aliasField("fn", Customer.class, "firstName"); + dataXml = xstream.toXML(customer); + } + + @Test + public void testClassAliasedAnnotation() { + Assert.assertNotEquals(-1, dataXml.indexOf("")); + } + + @Test + public void testFieldAliasedAnnotation() { + Assert.assertNotEquals(-1, dataXml.indexOf("")); + } + + @Test + public void testImplicitCollection() { + Assert.assertEquals(-1, dataXml.indexOf("contactDetailsList")); + } + + @Test + public void testDateFieldFormating() { + Assert.assertEquals("14-02-1986", dataXml.substring(dataXml.indexOf("") + 5, dataXml.indexOf(""))); + } + + @Test + public void testOmitField() { + Assert.assertEquals(-1, dataXml.indexOf("lastName")); + } +} diff --git a/xstream/src/test/resources/data-file-alias-field-complex.xml b/xstream/src/test/resources/data-file-alias-field-complex.xml new file mode 100644 index 0000000000..06050cd1ed --- /dev/null +++ b/xstream/src/test/resources/data-file-alias-field-complex.xml @@ -0,0 +1,15 @@ + + XStream + Java + 1986-02-14 04:14:05.874 UTC + + + 6673543265 + 0124-2460311 + + + 4676543565 + 0120-223312 + + + \ No newline at end of file diff --git a/xstream/src/test/resources/data-file-alias-field.xml b/xstream/src/test/resources/data-file-alias-field.xml new file mode 100644 index 0000000000..7e71d721ca --- /dev/null +++ b/xstream/src/test/resources/data-file-alias-field.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file diff --git a/xstream/src/test/resources/data-file-alias-implicit-collection.xml b/xstream/src/test/resources/data-file-alias-implicit-collection.xml new file mode 100644 index 0000000000..0cb852fc04 --- /dev/null +++ b/xstream/src/test/resources/data-file-alias-implicit-collection.xml @@ -0,0 +1,13 @@ + + XStream + Java + 1986-02-14 04:14:20.541 UTC + + 6673543265 + 0124-2460311 + + + 4676543565 + 0120-223312 + + \ No newline at end of file diff --git a/xstream/src/test/resources/data-file-alias.xml b/xstream/src/test/resources/data-file-alias.xml new file mode 100644 index 0000000000..61ee9f1ac3 --- /dev/null +++ b/xstream/src/test/resources/data-file-alias.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file diff --git a/xstream/src/test/resources/data-file-ignore-field.xml b/xstream/src/test/resources/data-file-ignore-field.xml new file mode 100644 index 0000000000..7dc8023b96 --- /dev/null +++ b/xstream/src/test/resources/data-file-ignore-field.xml @@ -0,0 +1,6 @@ + + XStream + Java + 1986-02-14 04:14:20.541 UTC + XStream Java + \ No newline at end of file diff --git a/xstream/src/test/resources/data-file.xml b/xstream/src/test/resources/data-file.xml new file mode 100644 index 0000000000..b8dbce32c0 --- /dev/null +++ b/xstream/src/test/resources/data-file.xml @@ -0,0 +1,5 @@ + + XStream + Java + 1986-02-14 03:46:16.381 UTC + \ No newline at end of file From d64c9e47f40bf4913af1088a448b24b959baa38d Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 4 Apr 2016 13:41:57 +0200 Subject: [PATCH 43/47] minor fix --- .../main/java/org/baeldung/spring/SecSecurityConfig.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java index c62b795e01..deeea78e4e 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -7,6 +7,7 @@ import org.springframework.security.config.annotation.authentication.builders.Au import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.session.HttpSessionEventPublisher; @@ -49,7 +50,12 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .and() .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400) .and() - .sessionManagement().invalidSessionUrl("/invalidSession.html").maximumSessions(2).expiredUrl("/sessionExpired.html"); + .sessionManagement() + .sessionFixation().migrateSession() + .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) + .invalidSessionUrl("/invalidSession.html") + .maximumSessions(2) + .expiredUrl("/sessionExpired.html"); // @formatter:on } From 08c8d82cd49eece79a6ae02f9e533bdfdb01840d Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 4 Apr 2016 13:42:21 +0200 Subject: [PATCH 44/47] add java zip examples --- .../java/com/baeldung/unzip/UnzipFile.java | 17 ++++--- .../java/com/baeldung/zip/ZipDirectory.java | 43 ++++++++++++++++++ .../main/java/com/baeldung/zip/ZipFile.java | 17 ++++--- .../com/baeldung/zip/ZipMultipleFiles.java | 33 ++++++++++++++ core-java-8/src/main/resources/compressed.zip | Bin 0 -> 146 bytes .../src/main/resources/dirCompressed.zip | Bin 0 -> 634 bytes .../src/main/resources/multiCompressed.zip | Bin 0 -> 273 bytes .../src/main/resources/unzipTest/test1.txt | 1 + .../src/main/resources/zipTest/test1.txt | 1 + .../src/main/resources/zipTest/test2.txt | 1 + .../resources/zipTest/testFolder/test3.txt | 1 + .../resources/zipTest/testFolder/test4.txt | 1 + 12 files changed, 97 insertions(+), 18 deletions(-) create mode 100644 core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java create mode 100644 core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java create mode 100644 core-java-8/src/main/resources/compressed.zip create mode 100644 core-java-8/src/main/resources/dirCompressed.zip create mode 100644 core-java-8/src/main/resources/multiCompressed.zip create mode 100644 core-java-8/src/main/resources/unzipTest/test1.txt create mode 100644 core-java-8/src/main/resources/zipTest/test1.txt create mode 100644 core-java-8/src/main/resources/zipTest/test2.txt create mode 100644 core-java-8/src/main/resources/zipTest/testFolder/test3.txt create mode 100644 core-java-8/src/main/resources/zipTest/testFolder/test4.txt diff --git a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java index d0b4274731..813d8f20f8 100644 --- a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java +++ b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java @@ -2,27 +2,26 @@ package com.baeldung.unzip; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class UnzipFile { - public static void main(String[] args) throws FileNotFoundException, IOException { - String fileZip = "/opt/zipped/cities.zip"; - byte[] buffer = new byte[1024]; - ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip)); + public static void main(final String[] args) throws IOException { + final String fileZip = "src/main/resources/compressed.zip"; + final byte[] buffer = new byte[1024]; + final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip)); ZipEntry zipEntry = zis.getNextEntry(); while(zipEntry != null){ - String fileName = zipEntry.getName(); - File newFile = new File("/opt/unzipped/" + fileName); - FileOutputStream fos = new FileOutputStream(newFile); + final String fileName = zipEntry.getName(); + final File newFile = new File("src/main/resources/unzipTest/" + fileName); + final FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } - fos.close(); + fos.close(); zipEntry = zis.getNextEntry(); } zis.closeEntry(); diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java b/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java new file mode 100644 index 0000000000..7da71a093d --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java @@ -0,0 +1,43 @@ +package com.baeldung.zip; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ZipDirectory { + public static void main(final String[] args) throws IOException { + final String sourceFile = "src/main/resources/zipTest"; + final FileOutputStream fos = new FileOutputStream("src/main/resources/dirCompressed.zip"); + final ZipOutputStream zipOut = new ZipOutputStream(fos); + final File fileToZip = new File(sourceFile); + + zipFile(fileToZip, fileToZip.getName(), zipOut); + zipOut.close(); + fos.close(); + } + + private static void zipFile(final File fileToZip, final String fileName, final ZipOutputStream zipOut) throws IOException { + if (fileToZip.isHidden()) { + return; + } + if (fileToZip.isDirectory()) { + final File[] children = fileToZip.listFiles(); + for (final File childFile : children) { + zipFile(childFile, fileName + "/" + childFile.getName(), zipOut); + } + return; + } + final FileInputStream fis = new FileInputStream(fileToZip); + final ZipEntry zipEntry = new ZipEntry(fileName); + zipOut.putNextEntry(zipEntry); + final byte[] bytes = new byte[1024]; + int length; + while ((length = fis.read(bytes)) >= 0) { + zipOut.write(bytes, 0, length); + } + fis.close(); + } +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java index dccd3f2347..af80ec9609 100644 --- a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java +++ b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java @@ -2,22 +2,21 @@ package com.baeldung.zip; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipFile { - public static void main(String[] args) throws FileNotFoundException, IOException { - String sourceFile = "/opt/photos/photo.png"; - FileOutputStream fos = new FileOutputStream("/opt/zipped/cities.zip"); - ZipOutputStream zipOut = new ZipOutputStream(fos); - File fileToZip = new File(sourceFile); - FileInputStream fis = new FileInputStream(fileToZip); - ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); + public static void main(final String[] args) throws IOException { + final String sourceFile = "src/main/resources/zipTest/test1.txt"; + final FileOutputStream fos = new FileOutputStream("src/main/resources/compressed.zip"); + final ZipOutputStream zipOut = new ZipOutputStream(fos); + final File fileToZip = new File(sourceFile); + final FileInputStream fis = new FileInputStream(fileToZip); + final ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); - byte[] bytes = new byte[1024]; + final byte[] bytes = new byte[1024]; int length; while((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java b/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java new file mode 100644 index 0000000000..211696195d --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java @@ -0,0 +1,33 @@ +package com.baeldung.zip; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ZipMultipleFiles { + public static void main(final String[] args) throws IOException { + final List srcFiles = Arrays.asList("src/main/resources/zipTest/test1.txt", "src/main/resources/zipTest/test2.txt"); + final FileOutputStream fos = new FileOutputStream("src/main/resources/multiCompressed.zip"); + final ZipOutputStream zipOut = new ZipOutputStream(fos); + for (final String srcFile : srcFiles) { + final File fileToZip = new File(srcFile); + final FileInputStream fis = new FileInputStream(fileToZip); + final ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); + zipOut.putNextEntry(zipEntry); + + final byte[] bytes = new byte[1024]; + int length; + while((length = fis.read(bytes)) >= 0) { + zipOut.write(bytes, 0, length); + } + fis.close(); + } + zipOut.close(); + fos.close(); + } +} \ No newline at end of file diff --git a/core-java-8/src/main/resources/compressed.zip b/core-java-8/src/main/resources/compressed.zip new file mode 100644 index 0000000000000000000000000000000000000000..03f840ae2bf13bdf8e9509168e964dea40f782f7 GIT binary patch literal 146 zcmWIWW@Zs#;Nak3Xvk^tU_b(#Kz2!LafzW`Nkz$LkFzIFhI5?PKjj(7!Vuui&aqfV pQ-%+yga?QNycwB97!bxF%YlqR1#m+Hyjj^mQj9=o4y0Yd>Hv0b7M1`2 literal 0 HcmV?d00001 diff --git a/core-java-8/src/main/resources/dirCompressed.zip b/core-java-8/src/main/resources/dirCompressed.zip new file mode 100644 index 0000000000000000000000000000000000000000..f42d3aa5c651b72d7150dd7c6b7a805c3b3421b6 GIT binary patch literal 634 zcmWIWW@Zs#;Nak3sLW~cU_b(bKz3DTK}c$GiGB%?Fw`rlDEaJh_T`r4eqd88VX9b(Qr^4~108k&uwYXi1$7B;UlRtQ!@rD@vVAjSx2uCwA zi7+6-6ghxEYES{PC%_>b;Ek#sIXqCc`vOfu)(#F+bnVEV26+tu<^q|>+R=j$-6Ui` eqMGy_w@Kh23-D%T1KG<0ghGrA3_(E5zyJVb(vt-M literal 0 HcmV?d00001 diff --git a/core-java-8/src/main/resources/multiCompressed.zip b/core-java-8/src/main/resources/multiCompressed.zip new file mode 100644 index 0000000000000000000000000000000000000000..002e70ef81cd58a1945bbdf9f96c49140bd5bd2c GIT binary patch literal 273 zcmWIWW@Zs#;Nak3Xvt~uU_b(#Kz2!LafzW`Nkz$LkFzIFhI5?PKjj(7!Vuui&aqfV zQ-%+yga?QN2pVDpHe_wc2k$e!p(k|0KAbv#f*EYilatHK1%YPpgUw-N5@A3%2iXpg ob5H@?aRJ__+K`Pz)#eH`0i+G=oB(fDHjs%-K$r)ldqErq0N^t-RR910 literal 0 HcmV?d00001 diff --git a/core-java-8/src/main/resources/unzipTest/test1.txt b/core-java-8/src/main/resources/unzipTest/test1.txt new file mode 100644 index 0000000000..c57eff55eb --- /dev/null +++ b/core-java-8/src/main/resources/unzipTest/test1.txt @@ -0,0 +1 @@ +Hello World! \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/test1.txt b/core-java-8/src/main/resources/zipTest/test1.txt new file mode 100644 index 0000000000..c57eff55eb --- /dev/null +++ b/core-java-8/src/main/resources/zipTest/test1.txt @@ -0,0 +1 @@ +Hello World! \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/test2.txt b/core-java-8/src/main/resources/zipTest/test2.txt new file mode 100644 index 0000000000..f0fb0f14d1 --- /dev/null +++ b/core-java-8/src/main/resources/zipTest/test2.txt @@ -0,0 +1 @@ +My Name is John \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test3.txt b/core-java-8/src/main/resources/zipTest/testFolder/test3.txt new file mode 100644 index 0000000000..882edb168e --- /dev/null +++ b/core-java-8/src/main/resources/zipTest/testFolder/test3.txt @@ -0,0 +1 @@ +My Name is Tom \ No newline at end of file diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test4.txt b/core-java-8/src/main/resources/zipTest/testFolder/test4.txt new file mode 100644 index 0000000000..a78c3fadc8 --- /dev/null +++ b/core-java-8/src/main/resources/zipTest/testFolder/test4.txt @@ -0,0 +1 @@ +My Name is Jane \ No newline at end of file From 3061fc7c0f9b17bf517259154900e9a70a0c512b Mon Sep 17 00:00:00 2001 From: Ivan Date: Mon, 4 Apr 2016 14:03:44 +0200 Subject: [PATCH 45/47] Add file upload example --- .../src/main/webapp/WEB-INF/view/fileUploadForm.jsp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp index 371acdc0ed..1414b824ff 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/fileUploadForm.jsp @@ -8,13 +8,13 @@ -

Enter The File to Upload

+

Enter The File to Upload (Single file)

- + From 9630170b032304afb7adff66b29f59a70112352c Mon Sep 17 00:00:00 2001 From: David Morley Date: Thu, 7 Apr 2016 06:17:57 -0500 Subject: [PATCH 46/47] Rename package --- .../baeldung/aop/LoggingAspect.java | 6 +- .../baeldung/aop/PerformanceAspect.java | 2 +- .../baeldung/aop/PublishingAspect.java | 4 +- .../baeldung/aop/annotations/Entity.java | 2 +- .../baeldung/aop/annotations/Loggable.java | 2 +- .../{org => com}/baeldung/dao/FooDao.java | 6 +- .../baeldung/dialect/CustomDialect.java | 4 +- .../baeldung/events/FooCreationEvent.java | 2 +- .../events/FooCreationEventListener.java | 2 +- .../{org => com}/baeldung/model/Employee.java | 2 +- .../java/{org => com}/baeldung/model/Foo.java | 4 +- .../{org => com}/baeldung/model/User.java | 2 +- .../baeldung/processor/NameProcessor.java | 2 +- .../spring/web/config/ClientWebConfig.java | 4 +- .../config/ContentManagementWebConfig.java | 2 +- .../web/config/MainWebAppInitializer.java | 4 +- .../baeldung/spring/web/config/WebConfig.java | 4 +- .../java/{org => com}/baeldung/web/BeanA.java | 2 +- .../java/{org => com}/baeldung/web/BeanB.java | 2 +- .../web/controller/EmployeeController.java | 4 +- .../web/controller/FileUploadController.java | 2 +- .../web/controller/UserController.java | 4 +- .../spring/web/config/WebConfig.java.orig | 116 ------------------ .../{org => com}/baeldung/aop/beans.xml | 4 +- .../src/main/webapp/WEB-INF/web_old.xml | 2 +- .../baeldung/aop/AopLoggingTest.java | 8 +- .../baeldung/aop/AopPerformanceTest.java | 6 +- .../baeldung/aop/AopPublishingTest.java | 10 +- .../aop/AopXmlConfigPerformanceTest.java | 6 +- .../baeldung/config/TestConfig.java | 4 +- 30 files changed, 54 insertions(+), 170 deletions(-) rename spring-mvc-java/src/main/java/{org => com}/baeldung/aop/LoggingAspect.java (90%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/aop/PerformanceAspect.java (97%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/aop/PublishingAspect.java (94%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/aop/annotations/Entity.java (86%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/aop/annotations/Loggable.java (87%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/dao/FooDao.java (75%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/dialect/CustomDialect.java (86%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/events/FooCreationEvent.java (86%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/events/FooCreationEventListener.java (94%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/model/Employee.java (97%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/model/Foo.java (80%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/model/User.java (90%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/processor/NameProcessor.java (94%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/spring/web/config/ClientWebConfig.java (97%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/spring/web/config/ContentManagementWebConfig.java (97%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/spring/web/config/MainWebAppInitializer.java (95%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/spring/web/config/WebConfig.java (96%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/web/BeanA.java (89%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/web/BeanB.java (83%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/web/controller/EmployeeController.java (95%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/web/controller/FileUploadController.java (96%) rename spring-mvc-java/src/main/java/{org => com}/baeldung/web/controller/UserController.java (90%) delete mode 100644 spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java.orig rename spring-mvc-java/src/main/resources/{org => com}/baeldung/aop/beans.xml (86%) rename spring-mvc-java/src/test/java/{org => com}/baeldung/aop/AopLoggingTest.java (95%) rename spring-mvc-java/src/test/java/{org => com}/baeldung/aop/AopPerformanceTest.java (95%) rename spring-mvc-java/src/test/java/{org => com}/baeldung/aop/AopPublishingTest.java (90%) rename spring-mvc-java/src/test/java/{org => com}/baeldung/aop/AopXmlConfigPerformanceTest.java (94%) rename spring-mvc-java/src/test/java/{org => com}/baeldung/config/TestConfig.java (67%) diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java b/spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java similarity index 90% rename from spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java rename to spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java index c59c4f060a..7ae37404be 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/LoggingAspect.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java @@ -1,4 +1,4 @@ -package org.baeldung.aop; +package com.baeldung.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; @@ -27,11 +27,11 @@ public class LoggingAspect { public void repositoryMethods() { } - @Pointcut("@annotation(org.baeldung.aop.annotations.Loggable)") + @Pointcut("@annotation(com.baeldung.aop.annotations.Loggable)") public void loggableMethods() { } - @Pointcut("@args(org.baeldung.aop.annotations.Entity)") + @Pointcut("@args(com.baeldung.aop.annotations.Entity)") public void methodsAcceptingEntities() { } diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java b/spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java similarity index 97% rename from spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java rename to spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java index 2d07e5a5f3..1f2076adff 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/PerformanceAspect.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java @@ -1,4 +1,4 @@ -package org.baeldung.aop; +package com.baeldung.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java b/spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java similarity index 94% rename from spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java rename to spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java index 324605dab1..7791c63e7b 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/PublishingAspect.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java @@ -1,10 +1,10 @@ -package org.baeldung.aop; +package com.baeldung.aop; +import com.baeldung.events.FooCreationEvent; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; -import org.baeldung.events.FooCreationEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java b/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Entity.java similarity index 86% rename from spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java rename to spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Entity.java index f964c3979e..61d91b0777 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Entity.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Entity.java @@ -1,4 +1,4 @@ -package org.baeldung.aop.annotations; +package com.baeldung.aop.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java b/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Loggable.java similarity index 87% rename from spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java rename to spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Loggable.java index ef2863957f..92aa950e58 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/aop/annotations/Loggable.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/annotations/Loggable.java @@ -1,4 +1,4 @@ -package org.baeldung.aop.annotations; +package com.baeldung.aop.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java b/spring-mvc-java/src/main/java/com/baeldung/dao/FooDao.java similarity index 75% rename from spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java rename to spring-mvc-java/src/main/java/com/baeldung/dao/FooDao.java index f204440b2d..1d28b082ec 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/dao/FooDao.java +++ b/spring-mvc-java/src/main/java/com/baeldung/dao/FooDao.java @@ -1,7 +1,7 @@ -package org.baeldung.dao; +package com.baeldung.dao; -import org.baeldung.aop.annotations.Loggable; -import org.baeldung.model.Foo; +import com.baeldung.aop.annotations.Loggable; +import com.baeldung.model.Foo; import org.springframework.stereotype.Repository; @Repository diff --git a/spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java b/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java similarity index 86% rename from spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java rename to spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java index e6d1ad6b74..0c6a7c3ae0 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/dialect/CustomDialect.java +++ b/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java @@ -1,9 +1,9 @@ -package org.baeldung.dialect; +package com.baeldung.dialect; import java.util.HashSet; import java.util.Set; -import org.baeldung.processor.NameProcessor; +import com.baeldung.processor.NameProcessor; import org.thymeleaf.dialect.AbstractDialect; import org.thymeleaf.processor.IProcessor; diff --git a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java b/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEvent.java similarity index 86% rename from spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java rename to spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEvent.java index af11f3a4be..5ea4b46c04 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEvent.java +++ b/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEvent.java @@ -1,4 +1,4 @@ -package org.baeldung.events; +package com.baeldung.events; import org.springframework.context.ApplicationEvent; diff --git a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java b/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEventListener.java similarity index 94% rename from spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java rename to spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEventListener.java index 35dcfd2bc3..c0aa744bc1 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/events/FooCreationEventListener.java +++ b/spring-mvc-java/src/main/java/com/baeldung/events/FooCreationEventListener.java @@ -1,4 +1,4 @@ -package org.baeldung.events; +package com.baeldung.events; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/Employee.java b/spring-mvc-java/src/main/java/com/baeldung/model/Employee.java similarity index 97% rename from spring-mvc-java/src/main/java/org/baeldung/model/Employee.java rename to spring-mvc-java/src/main/java/com/baeldung/model/Employee.java index 5365068a89..d0f6b724eb 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/model/Employee.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/Employee.java @@ -1,4 +1,4 @@ -package org.baeldung.model; +package com.baeldung.model; import javax.xml.bind.annotation.XmlRootElement; diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java b/spring-mvc-java/src/main/java/com/baeldung/model/Foo.java similarity index 80% rename from spring-mvc-java/src/main/java/org/baeldung/model/Foo.java rename to spring-mvc-java/src/main/java/com/baeldung/model/Foo.java index 87bd7132e6..01f5f43f60 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/model/Foo.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/Foo.java @@ -1,6 +1,6 @@ -package org.baeldung.model; +package com.baeldung.model; -import org.baeldung.aop.annotations.Entity; +import com.baeldung.aop.annotations.Entity; @Entity public class Foo { diff --git a/spring-mvc-java/src/main/java/org/baeldung/model/User.java b/spring-mvc-java/src/main/java/com/baeldung/model/User.java similarity index 90% rename from spring-mvc-java/src/main/java/org/baeldung/model/User.java rename to spring-mvc-java/src/main/java/com/baeldung/model/User.java index df549cd21d..dc4480c986 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/model/User.java +++ b/spring-mvc-java/src/main/java/com/baeldung/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.model; +package com.baeldung.model; public class User { private String firstname; diff --git a/spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java b/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java similarity index 94% rename from spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java rename to spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java index df9a4da7f0..9a7857198c 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/processor/NameProcessor.java +++ b/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java @@ -1,4 +1,4 @@ -package org.baeldung.processor; +package com.baeldung.processor; import org.thymeleaf.Arguments; import org.thymeleaf.dom.Element; diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java similarity index 97% rename from spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java rename to spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java index 6084943ddd..c108a450ae 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java @@ -1,9 +1,9 @@ -package org.baeldung.spring.web.config; +package com.baeldung.spring.web.config; import java.util.HashSet; import java.util.Set; -import org.baeldung.dialect.CustomDialect; +import com.baeldung.dialect.CustomDialect; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java similarity index 97% rename from spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java rename to spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java index 2c5b423029..9780575678 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ContentManagementWebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.web.config; +package com.baeldung.spring.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java similarity index 95% rename from spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java rename to spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java index ad37bbec5e..4a11ba986c 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.web.config; +package com.baeldung.spring.web.config; import java.util.Set; @@ -25,7 +25,7 @@ public class MainWebAppInitializer implements WebApplicationInitializer { // Create the 'root' Spring application context final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.scan("org.baeldung.spring.web.config"); + root.scan("com.baeldung.spring.web.config"); // root.getEnvironment().setDefaultProfiles("embedded"); // Manages the lifecycle of the root application context diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java similarity index 96% rename from spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java rename to spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index bd2af0886e..693fd74f74 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.web.config; +package com.baeldung.spring.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -16,7 +16,7 @@ import org.springframework.web.servlet.view.XmlViewResolver; @Configuration @EnableWebMvc -@ComponentScan("org.baeldung.web") +@ComponentScan("com.baeldung.web") public class WebConfig extends WebMvcConfigurerAdapter { public WebConfig() { diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/BeanA.java b/spring-mvc-java/src/main/java/com/baeldung/web/BeanA.java similarity index 89% rename from spring-mvc-java/src/main/java/org/baeldung/web/BeanA.java rename to spring-mvc-java/src/main/java/com/baeldung/web/BeanA.java index b6b6f49c16..79fac724f7 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/BeanA.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/BeanA.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/BeanB.java b/spring-mvc-java/src/main/java/com/baeldung/web/BeanB.java similarity index 83% rename from spring-mvc-java/src/main/java/org/baeldung/web/BeanB.java rename to spring-mvc-java/src/main/java/com/baeldung/web/BeanB.java index 49e5af4ccb..05c9560a0c 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/BeanB.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/BeanB.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.web; import org.springframework.stereotype.Component; diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java similarity index 95% rename from spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java rename to spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java index e18bbdbf63..38272b23cb 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -1,9 +1,9 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import java.util.HashMap; import java.util.Map; -import org.baeldung.model.Employee; +import com.baeldung.model.Employee; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/FileUploadController.java similarity index 96% rename from spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java rename to spring-mvc-java/src/main/java/com/baeldung/web/controller/FileUploadController.java index 6f557adf0f..bc9cf13c34 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/controller/FileUploadController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/FileUploadController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; diff --git a/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/UserController.java similarity index 90% rename from spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java rename to spring-mvc-java/src/main/java/com/baeldung/web/controller/UserController.java index da39a36adf..fda159f204 100644 --- a/spring-mvc-java/src/main/java/org/baeldung/web/controller/UserController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/UserController.java @@ -1,6 +1,6 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; diff --git a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java.orig b/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java.orig deleted file mode 100644 index 78307849b4..0000000000 --- a/spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java.orig +++ /dev/null @@ -1,116 +0,0 @@ -package org.baeldung.spring.web.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.ClassPathResource; -import org.springframework.web.multipart.commons.CommonsMultipartResolver; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; -import org.springframework.web.servlet.view.ResourceBundleViewResolver; -import org.springframework.web.servlet.view.XmlViewResolver; - -@Configuration -@EnableWebMvc -@ComponentScan("org.baeldung.web") -public class WebConfig extends WebMvcConfigurerAdapter { - -<<<<<<< HEAD - public WebConfig() { - super(); - } - - // - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } - - @Bean - public ViewResolver internalResourceViewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(2); - return bean; - } - - @Bean - public ViewResolver xmlViewResolver() { - final XmlViewResolver bean = new XmlViewResolver(); - bean.setLocation(new ClassPathResource("views.xml")); - bean.setOrder(1); - return bean; - } - - @Bean - public ViewResolver resourceBundleViewResolver() { - final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); - bean.setBasename("views"); - bean.setOrder(0); - return bean; - } - -======= - public WebConfig() { - super(); - } - - // @Bean - // public StandardServletMultipartResolver multipartResolver() { - // return new StandardServletMultipartResolver(); - // } - - @Bean(name = "multipartResolver") - public CommonsMultipartResolver multipartResolver() { - - final CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); - multipartResolver.setMaxUploadSize(100000); - - return multipartResolver; - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - - super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } - - @Bean - public ViewResolver internalResourceViewResolver() { - - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(2); - return bean; - } - - @Bean - public ViewResolver xmlViewResolver() { - - final XmlViewResolver bean = new XmlViewResolver(); - bean.setLocation(new ClassPathResource("views.xml")); - bean.setOrder(1); - return bean; - } - - @Bean - public ViewResolver resourceBundleViewResolver() { - - final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); - bean.setBasename("views"); - bean.setOrder(0); - return bean; - } ->>>>>>> 3061fc7c0f9b17bf517259154900e9a70a0c512b -} \ No newline at end of file diff --git a/spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml b/spring-mvc-java/src/main/resources/com/baeldung/aop/beans.xml similarity index 86% rename from spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml rename to spring-mvc-java/src/main/resources/com/baeldung/aop/beans.xml index 17c63e39e4..e6aa9d77c4 100644 --- a/spring-mvc-java/src/main/resources/org/baeldung/aop/beans.xml +++ b/spring-mvc-java/src/main/resources/com/baeldung/aop/beans.xml @@ -7,8 +7,8 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"> - - + + diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/web_old.xml b/spring-mvc-java/src/main/webapp/WEB-INF/web_old.xml index 016369ad27..c8b38fae30 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/web_old.xml +++ b/spring-mvc-java/src/main/webapp/WEB-INF/web_old.xml @@ -16,7 +16,7 @@ contextConfigLocation - org.baeldung.spring.web.config + com.baeldung.spring.web.config diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java similarity index 95% rename from spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java index b1c9867e41..19bf4d0fac 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopLoggingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopLoggingTest.java @@ -1,8 +1,8 @@ -package org.baeldung.aop; +package com.baeldung.aop; -import org.baeldung.config.TestConfig; -import org.baeldung.dao.FooDao; -import org.baeldung.model.Foo; +import com.baeldung.config.TestConfig; +import com.baeldung.dao.FooDao; +import com.baeldung.model.Foo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPerformanceTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java similarity index 95% rename from spring-mvc-java/src/test/java/org/baeldung/aop/AopPerformanceTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java index 69083c60a2..4ad5a3e1a6 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPerformanceTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPerformanceTest.java @@ -1,7 +1,7 @@ -package org.baeldung.aop; +package com.baeldung.aop; -import org.baeldung.config.TestConfig; -import org.baeldung.dao.FooDao; +import com.baeldung.config.TestConfig; +import com.baeldung.dao.FooDao; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java similarity index 90% rename from spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java index e691dbd32e..c075db9fc6 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopPublishingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopPublishingTest.java @@ -1,9 +1,9 @@ -package org.baeldung.aop; +package com.baeldung.aop; -import org.baeldung.config.TestConfig; -import org.baeldung.dao.FooDao; -import org.baeldung.events.FooCreationEventListener; -import org.baeldung.model.Foo; +import com.baeldung.config.TestConfig; +import com.baeldung.dao.FooDao; +import com.baeldung.events.FooCreationEventListener; +import com.baeldung.model.Foo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java b/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java similarity index 94% rename from spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java rename to spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java index 7ef25d743c..4d2df50d18 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/aop/AopXmlConfigPerformanceTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/aop/AopXmlConfigPerformanceTest.java @@ -1,6 +1,6 @@ -package org.baeldung.aop; +package com.baeldung.aop; -import org.baeldung.dao.FooDao; +import com.baeldung.dao.FooDao; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,7 +21,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("/org/baeldung/aop/beans.xml") +@ContextConfiguration("/com/baeldung/aop/beans.xml") public class AopXmlConfigPerformanceTest { @Before diff --git a/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/TestConfig.java similarity index 67% rename from spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java rename to spring-mvc-java/src/test/java/com/baeldung/config/TestConfig.java index f9573b2add..641513a24a 100644 --- a/spring-mvc-java/src/test/java/org/baeldung/config/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/config/TestConfig.java @@ -1,11 +1,11 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration -@ComponentScan(basePackages = { "org.baeldung.dao", "org.baeldung.aop", "org.baeldung.events" }) +@ComponentScan(basePackages = { "com.baeldung.dao", "com.baeldung.aop", "com.baeldung.events" }) @EnableAspectJAutoProxy public class TestConfig { } From d575f443bc9c33d0ce39b9aea2e983c2e8951282 Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 8 Apr 2016 12:05:59 +0200 Subject: [PATCH 47/47] minor fix --- .../java/org/baeldung/java/io/JavaXToWriterUnitTest.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java index 35ec15df16..eb393668bd 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java @@ -1,5 +1,7 @@ package org.baeldung.java.io; +import static org.junit.Assert.assertEquals; + import java.io.IOException; import java.io.StringWriter; import java.io.Writer; @@ -23,6 +25,8 @@ public class JavaXToWriterUnitTest { final Writer targetWriter = new StringWriter().append(new String(initialArray)); targetWriter.close(); + + assertEquals("With Java", targetWriter.toString()); } @Test @@ -40,6 +44,8 @@ public class JavaXToWriterUnitTest { charSink.write(buffer); stringWriter.close(); + + assertEquals("With Guava", stringWriter.toString()); } @Test @@ -48,6 +54,8 @@ public class JavaXToWriterUnitTest { final Writer targetWriter = new StringBuilderWriter(new StringBuilder(new String(initialArray))); targetWriter.close(); + + assertEquals("With Commons IO", targetWriter.toString()); } }
Select a file to upload (Single file)Select a file to upload