Merge remote-tracking branch 'origin/master'

This commit is contained in:
Slavisa Baeldung 2016-06-28 17:09:58 +02:00
commit 85410e329d
53 changed files with 1131 additions and 283 deletions

View File

@ -63,6 +63,12 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>

View File

@ -1,54 +0,0 @@
package com.baeldung.date_migration;
import java.text.ParseException;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class NewApi {
public void currentTime() {
ZonedDateTime now = ZonedDateTime.now();
}
public void specificTime() {
LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);
}
public void extractMonth() {
Month month = LocalDateTime.now().getMonth();
}
public void subtractTime() {
LocalDateTime fiveHoursBefore = LocalDateTime.now().minusHours(5);
}
public void alterField() {
LocalDateTime inJune = LocalDateTime.now().withMonth(Month.JUNE.getValue());
}
public void truncate() {
LocalTime truncated = LocalTime.now().truncatedTo(ChronoUnit.HOURS);
}
public void convertTimeZone() {
ZonedDateTime centralEastern = LocalDateTime.now().atZone(ZoneId.of("CET"));
}
public void getTimeSpan() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime hourLater = LocalDateTime.now().plusHours(1);
Duration span = Duration.between(now, hourLater);
}
public void formatAndParse() throws ParseException {
LocalDate now = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = now.format(formatter);
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
}
public void daysInMonth() {
int daysInMonth = YearMonth.of(1990, 2).lengthOfMonth();
}
}

View File

@ -1,68 +0,0 @@
package com.baeldung.date_migration;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class OldApi {
public void currentTime() {
Date now = new Date();
}
public void specificTime () {
Date birthDay = new GregorianCalendar(1990, Calendar.DECEMBER, 15).getTime();
}
public void extractMonth() {
int month = new GregorianCalendar().get(Calendar.MONTH);
}
public void subtractTime() {
GregorianCalendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR_OF_DAY, -5);
Date fiveHoursBefore = calendar.getTime();
}
public void alterField() {
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(Calendar.MONTH, Calendar.JUNE);
Date inJune = calendar.getTime();
}
public void truncate() {
Calendar now = Calendar.getInstance();
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
Date truncated = now.getTime();
}
public void convertTimeZone() {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getTimeZone("CET"));
Date centralEastern = calendar.getTime();
}
public void getTimeSpan() {
GregorianCalendar calendar = new GregorianCalendar();
Date now = new Date();
calendar.add(Calendar.HOUR, 1);
Date hourLater = calendar.getTime();
long elapsed = hourLater.getTime() - now.getTime();
}
public void formatAndParse() throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date now = new Date();
String formattedDate = dateFormat.format(now);
Date parsedDate = dateFormat.parse(formattedDate);
}
public void daysInMonth() {
Calendar calendar = new GregorianCalendar(1990, Calendar.FEBRUARY, 20);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.date_migration;
package com.baeldung.dateapi;
import java.time.Instant;
import java.time.ZoneId;
@ -7,7 +7,7 @@ import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Conversion {
public class ConversionExample {
public static void main(String[] args) {
Instant instantFromCalendar = GregorianCalendar.getInstance().toInstant();
ZonedDateTime zonedDateTimeFromCalendar = new GregorianCalendar().toZonedDateTime();

View File

@ -0,0 +1,89 @@
package com.baeldung.dateapi;
import org.junit.Test;
import java.text.ParseException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import static org.assertj.core.api.Assertions.assertThat;
public class JavaUtilTimeTest {
@Test
public void currentTime() {
final LocalDate now = LocalDate.now();
System.out.println(now);
// there is not much to test here
}
@Test
public void specificTime() {
LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);
System.out.println(birthDay);
// there is not much to test here
}
@Test
public void extractMonth() {
Month month = LocalDate.of(1990, Month.DECEMBER, 15).getMonth();
assertThat(month).isEqualTo(Month.DECEMBER);
}
@Test
public void subtractTime() {
LocalDateTime fiveHoursBefore = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).minusHours(5);
assertThat(fiveHoursBefore.getHour()).isEqualTo(10);
}
@Test
public void alterField() {
LocalDateTime inJune = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).with(Month.JUNE);
assertThat(inJune.getMonth()).isEqualTo(Month.JUNE);
}
@Test
public void truncate() {
LocalTime truncated = LocalTime.of(15, 12, 34).truncatedTo(ChronoUnit.HOURS);
assertThat(truncated).isEqualTo(LocalTime.of(15, 0, 0));
}
@Test
public void getTimeSpan() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime hourLater = now.plusHours(1);
Duration span = Duration.between(now, hourLater);
assertThat(span).isEqualTo(Duration.ofHours(1));
}
@Test
public void formatAndParse() throws ParseException {
LocalDate someDate = LocalDate.of(2016, 12, 7);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = someDate.format(formatter);
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
assertThat(formattedDate).isEqualTo("2016-12-07");
assertThat(parsedDate).isEqualTo(someDate);
}
@Test
public void daysInMonth() {
int daysInMonth = YearMonth.of(1990, 2).lengthOfMonth();
assertThat(daysInMonth).isEqualTo(28);
}
}

View File

@ -1,7 +1,9 @@
=========
## HttpClient 4.x Cookbooks and Examples
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:

View File

@ -2,6 +2,9 @@
## Jackson Cookbooks and Examples
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Jackson Ignore Properties on Marshalling](http://www.baeldung.com/jackson-ignore-properties-on-serialization)
- [Jackson Unmarshall to Collection/Array](http://www.baeldung.com/jackson-collection-array)

View File

@ -12,6 +12,8 @@
<mockito.version>1.10.19</mockito.version>
<easymock.version>3.4</easymock.version>
<jmockit.version>1.24</jmockit.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>

2
raml/README.MD Normal file
View File

@ -0,0 +1,2 @@
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring

View File

@ -2,6 +2,8 @@
## REST Testing and Examples
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Test a REST API with Java](http://www.baeldung.com/2011/10/13/integration-testing-a-rest-api/)

View File

@ -4,6 +4,8 @@
This project is used to replicate Spring Exceptions only.
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant articles:
- [Properties with Spring](http://www.baeldung.com/2012/02/06/properties-with-spring) - checkout the `org.baeldung.properties` package for all scenarios of properties injection and usage

2
spring-boot/README.MD Normal file
View File

@ -0,0 +1,2 @@
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring

View File

@ -1,3 +1,6 @@
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
# 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.

View File

@ -2,5 +2,8 @@
## Java Web Application
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [JSON API in a Java Web Application](http://www.baeldung.com/json-api-java-spring-web-app)

View File

@ -2,6 +2,8 @@
## Spring MVC with Java Configuration Example Project
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations)

View File

@ -2,6 +2,8 @@
## Spring MVC with NO XML Configuration Example Project
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
-
-

View File

@ -1,5 +1,8 @@
=========
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
## Spring MVC with XML Configuration Example Project
- access a sample jsp page at: `http://localhost:8080/spring-mvc-xml/sample.html`

View File

@ -0,0 +1,2 @@
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring

View File

@ -2,6 +2,8 @@
## Spring REST Example Project
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping)

View File

@ -0,0 +1,2 @@
###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity

View File

@ -2,6 +2,8 @@
## Spring Security with Basic Authentication Example Project
###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
### Relevant Article:
- [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll)
@ -9,4 +11,4 @@
### Notes
- the project includes both views as well as a REST layer
- the project includes both views as well as a REST layer

View File

@ -0,0 +1,2 @@
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring

View File

@ -2,6 +2,8 @@
## Spring Security Login Example Project
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Spring Security Remember Me](http://www.baeldung.com/spring-security-remember-me)

View File

@ -2,6 +2,8 @@
## Spring Security with Digest Authentication Example Project
###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
### Relevant Article:
- [Spring Security Digest Authentication](http://www.baeldung.com/spring-security-digest-authentication)

View File

@ -1,6 +1,8 @@
## Spring Security with LDAP Example Project
###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
### Relevant Article:
- [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll)

View File

@ -2,11 +2,13 @@
## Spring Security Login Example Project
###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
### Relevant Articles:
- [Spring Security Form Login](http://www.baeldung.com/spring-security-login)
- [Spring Security Logout](http://www.baeldung.com/spring-security-logout)
- [Spring Security Expressions hasRole Example](http://www.baeldung.com/spring-security-expressions-basic)
- [Spring Security Expressions hasRole Example](http://www.baeldung.com/spring-security-expressions-basic)
### Build the Project

View File

@ -2,6 +2,8 @@
## Spring Security Persisted Remember Me Example Project
###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
### Relevant Articles:
- [Spring Security Persisted Remember Me](http://www.baeldung.com/spring-security-persistent-remember-me)

View File

@ -2,9 +2,11 @@
## Spring Security Login Example Project
###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
### Relevant Articles:
- [HttpSessionListener Example Monitoring](http://www.baeldung.com/httpsessionlistener_with_metrics)
- [HttpSessionListener Example Monitoring](http://www.baeldung.com/httpsessionlistener_with_metrics)
- [Spring Security Session Management](http://www.baeldung.com/spring-security-session)

View File

@ -2,6 +2,8 @@
## REST API with Basic Authentication - Example Project
###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
### Relevant Articles:
- [RestTemplate with Basic Authentication in Spring](http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1)

View File

@ -2,6 +2,9 @@
## Spring Security for REST Example Project
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Spring Security Authentication Provider](http://www.baeldung.com/spring-security-authentication-provider)
- [Retrieve User Information in Spring Security](http://www.baeldung.com/get-user-in-spring-security)

View File

@ -2,6 +2,8 @@
## REST API with Digest Authentication - Example Project
###The Course
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
### Relevant Articles:
- [RestTemplate with Digest Authentication](http://www.baeldung.com/resttemplate-digest-authentication)

View File

@ -2,8 +2,10 @@
## REST Example Project with Spring Security
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Courses
The "REST With Spring" Classes: http://bit.ly/restwithspring
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
### Relevant Articles:
- [Spring Security Expressions - hasRole Example](http://www.baeldung.com/spring-security-expressions-basic)

View File

@ -2,6 +2,10 @@
## Spring Security for REST Example Project
### Courses
The "REST With Spring" Classes: http://bit.ly/restwithspring
The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity
### Relevant Articles:
- [Spring REST Service Security](http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/)

View File

@ -1,139 +1,117 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>xml</artifactId>
<version>0.1-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>xml</artifactId>
<version>0.1-SNAPSHOT</version>
<name>xml</name>
<name>xml</name>
<dependencies>
<!-- utils -->
<dependencies>
<!-- xml libraries -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- test scoped -->
<!-- utils -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- test scoped -->
<build>
<finalName>xml</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<plugins>
</dependencies>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<build>
<finalName>xml</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugins>
</plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</build>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
</plugins>
<!-- marshalling -->
<jackson.version>2.7.2</jackson.version>
</build>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<properties>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<!-- testing -->
<junit.version>4.12</junit.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>
</properties>
</project>

View File

@ -39,7 +39,7 @@ public class DefaultParser {
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/Tutorials/Tutorial";
String expression = "/tutorials/tutorial";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
@ -60,7 +60,7 @@ public class DefaultParser {
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/Tutorials/Tutorial[@tutId=" + "'" + id + "'" + "]";
String expression = "/tutorials/tutorial[@tutId=" + "'" + id + "'" + "]";
node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
@ -83,7 +83,7 @@ public class DefaultParser {
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//Tutorial[descendant::title[text()=" + "'" + name + "'" + "]]";
String expression = "//tutorial[descendant::title[text()=" + "'" + name + "'" + "]]";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
@ -107,7 +107,7 @@ public class DefaultParser {
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//Tutorial[number(translate(date, '/', '')) > " + date + "]";
String expression = "//tutorial[number(translate(date, '/', '')) > " + date + "]";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
@ -151,7 +151,7 @@ public class DefaultParser {
}
});
String expression = "/bdn:Tutorials/bdn:Tutorial";
String expression = "/bdn:tutorials/bdn:tutorial";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

View File

@ -0,0 +1,131 @@
package com.baeldung.xml;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4JParser {
private File file;
public Dom4JParser(File file) {
this.file = file;
}
public Element getRootElement() {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
return document.getRootElement();
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public List<Element> getFirstElementList() {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
return document.getRootElement().elements();
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public Node getNodeById(String id) {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
List<Node> elements = document.selectNodes("//*[@tutId='" + id + "']");
return elements.get(0);
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public Node getElementsListByTitle(String name) {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
List<Node> elements = document
.selectNodes("//tutorial[descendant::title[text()=" + "'" + name + "'" + "]]");
return elements.get(0);
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
public void generateModifiedDocument() {
try {
SAXReader reader = new SAXReader();
Document document = reader.read(file);
List<Node> nodes = document.selectNodes("/tutorials/tutorial");
for (Node node : nodes) {
Element element = (Element) node;
Iterator<Element> iterator = element.elementIterator("title");
while (iterator.hasNext()) {
Element title = (Element) iterator.next();
title.setText(title.getText() + " updated");
}
}
XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_updated.xml")));
writer.write(document);
writer.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void generateNewDocument() {
try {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("XMLTutorials");
Element tutorialElement = root.addElement("tutorial").addAttribute("tutId", "01");
tutorialElement.addAttribute("type", "xml");
tutorialElement.addElement("title").addText("XML with Dom4J");
tutorialElement.addElement("description").addText("XML handling with Dom4J");
tutorialElement.addElement("date").addText("14/06/2016");
tutorialElement.addElement("author").addText("Dom4J tech writer");
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_new.xml")), format);
writer.write(document);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.xml;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
public class JDomParser {
private File file;
public JDomParser(File file) {
this.file = file;
}
public List<Element> getAllTitles() {
try {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(this.getFile());
Element tutorials = doc.getRootElement();
List<Element> titles = tutorials.getChildren("tutorial");
return titles;
} catch (JDOMException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public Element getNodeById(String id) {
try {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(file);
String filter = "//*[@tutId='" + id + "']";
XPathFactory xFactory = XPathFactory.instance();
XPathExpression<Element> expr = xFactory.compile(filter, Filters.element());
List<Element> node = expr.evaluate(document);
return node.get(0);
} catch (JDOMException | IOException e ) {
e.printStackTrace();
return null;
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.xml;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import com.baeldung.xml.binding.Tutorial;
import com.baeldung.xml.binding.Tutorials;
public class JaxbParser {
private File file;
public JaxbParser(File file) {
this.file = file;
}
public Tutorials getFullDocument() {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Tutorials tutorials = (Tutorials) jaxbUnmarshaller.unmarshal(this.getFile());
return tutorials;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
public void createNewDocument() {
Tutorials tutorials = new Tutorials();
tutorials.setTutorial(new ArrayList<Tutorial>());
Tutorial tut = new Tutorial();
tut.setTutId("01");
tut.setType("XML");
tut.setTitle("XML with Jaxb");
tut.setDescription("XML Binding with Jaxb");
tut.setDate(new Date());
tut.setAuthor("Jaxb author");
tutorials.getTutorial().add(tut);
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(tutorials, file);
} catch (JAXBException e) {
e.printStackTrace();
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.xml;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.jaxen.JaxenException;
import org.jaxen.XPath;
import org.jaxen.dom.DOMXPath;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class JaxenDemo {
private File file;
public JaxenDemo(File file) {
this.file = file;
}
public List getAllTutorial(){
try {
FileInputStream fileIS = new FileInputStream(this.getFile());
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(fileIS);
String expression = "/tutorials/tutorial";
XPath path = new DOMXPath(expression);
List result = path.selectNodes(xmlDocument);
return result;
} catch (SAXException | IOException | ParserConfigurationException | JaxenException e) {
e.printStackTrace();
return null;
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}

View File

@ -0,0 +1,120 @@
package com.baeldung.xml;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import com.baeldung.xml.model.Tutorial;
public class StaxParser {
private File file;
public StaxParser(File file) {
this.file = file;
}
public List<Tutorial> getAllTutorial() {
boolean bTitle = false;
boolean bDescription = false;
boolean bDate = false;
boolean bAuthor = false;
List<Tutorial> tutorials = new ArrayList<Tutorial>();
try {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(this.getFile()));
Tutorial current = null;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
switch (event.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
StartElement startElement = event.asStartElement();
String qName = startElement.getName().getLocalPart();
if (qName.equalsIgnoreCase("tutorial")) {
current = new Tutorial();
Iterator<Attribute> attributes = startElement.getAttributes();
while (attributes.hasNext()) {
Attribute currentAt = attributes.next();
if (currentAt.getName().toString().equalsIgnoreCase("tutId")) {
current.setTutId(currentAt.getValue());
} else if (currentAt.getName().toString().equalsIgnoreCase("type")) {
current.setType(currentAt.getValue());
}
}
} else if (qName.equalsIgnoreCase("title")) {
bTitle = true;
} else if (qName.equalsIgnoreCase("description")) {
bDescription = true;
} else if (qName.equalsIgnoreCase("date")) {
bDate = true;
} else if (qName.equalsIgnoreCase("author")) {
bAuthor = true;
}
break;
case XMLStreamConstants.CHARACTERS:
Characters characters = event.asCharacters();
if (bTitle) {
if (current != null) {
current.setTitle(characters.getData());
}
bTitle = false;
}
if (bDescription) {
if (current != null) {
current.setDescription(characters.getData());
}
bDescription = false;
}
if (bDate) {
if (current != null) {
current.setDate(characters.getData());
}
bDate = false;
}
if (bAuthor) {
if (current != null) {
current.setAuthor(characters.getData());
}
bAuthor = false;
}
break;
case XMLStreamConstants.END_ELEMENT:
EndElement endElement = event.asEndElement();
if (endElement.getName().getLocalPart().equalsIgnoreCase("tutorial")) {
if(current != null){
tutorials.add(current);
}
}
break;
}
}
} catch (FileNotFoundException | XMLStreamException e) {
e.printStackTrace();
}
return tutorials;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.xml.binding;
import java.util.Date;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
public class Tutorial {
private String tutId;
private String type;
private String title;
private String description;
private Date date;
private String author;
public String getTutId() {
return tutId;
}
@XmlAttribute
public void setTutId(String tutId) {
this.tutId = tutId;
}
public String getType() {
return type;
}
@XmlAttribute
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
@XmlElement
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
@XmlElement
public void setDescription(String description) {
this.description = description;
}
public Date getDate() {
return date;
}
@XmlElement
public void setDate(Date date) {
this.date = date;
}
public String getAuthor() {
return author;
}
@XmlElement
public void setAuthor(String author) {
this.author = author;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.xml.binding;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Tutorials {
private List<Tutorial> tutorial;
public List<Tutorial> getTutorial() {
return tutorial;
}
@XmlElement
public void setTutorial(List<Tutorial> tutorial) {
this.tutorial = tutorial;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.xml.model;
public class Tutorial {
private String tutId;
private String type;
private String title;
private String description;
private String date;
private String author;
public String getTutId() {
return tutId;
}
public void setTutId(String tutId) {
this.tutId = tutId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}

View File

@ -1,23 +1,22 @@
package com.baeldung.xml;
import static org.junit.Assert.*;
import java.io.File;
import org.junit.Test;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Unit test for simple App.
*/
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class DefaultParserTest {
final String fileName = "src/test/resources/example.xml";
private final String fileName = "src/test/resources/example.xml";
final String fileNameSpace = "src/test/resources/example_namespace.xml";
private final String fileNameSpace = "src/test/resources/example_namespace.xml";
DefaultParser parser;
private DefaultParser parser;
@Test
public void getFirstLevelNodeListTest() {
@ -29,11 +28,11 @@ public class DefaultParserTest {
}
@Test
public void getNodeListByTitle() {
public void getNodeListByTitleTest() {
parser = new DefaultParser(new File(fileName));
NodeList list = parser.getNodeListByTitle("XML");
for (int i = 0; null != list && i < list.getLength(); i++) {
for (int i = 0; i < list.getLength(); i++) {
Node nod = list.item(i);
assertEquals("java", nod.getAttributes().getNamedItem("type").getTextContent());
assertEquals("02", nod.getAttributes().getNamedItem("tutId").getTextContent());
@ -47,7 +46,7 @@ public class DefaultParserTest {
}
@Test
public void getNodeById() {
public void getNodeByIdTest() {
parser = new DefaultParser(new File(fileName));
Node node = parser.getNodeById("03");
@ -56,10 +55,10 @@ public class DefaultParserTest {
}
@Test
public void getNodeListByDate(){
public void getNodeListByDateTest(){
parser = new DefaultParser(new File(fileName));
NodeList list = parser.getNodeListByTitle("04022016");
for (int i = 0; null != list && i < list.getLength(); i++) {
for (int i = 0; i < list.getLength(); i++) {
Node nod = list.item(i);
assertEquals("java", nod.getAttributes().getNamedItem("type").getTextContent());
assertEquals("04", nod.getAttributes().getNamedItem("tutId").getTextContent());
@ -73,7 +72,7 @@ public class DefaultParserTest {
}
@Test
public void getNodeListWithNamespace(){
public void getNodeListWithNamespaceTest(){
parser = new DefaultParser(new File(fileNameSpace));
NodeList list = parser.getAllTutorials();
assertNotNull(list);

View File

@ -0,0 +1,88 @@
package com.baeldung.xml;
import org.dom4j.Element;
import org.dom4j.Node;
import org.junit.Test;
import java.io.File;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class Dom4JParserTest {
private static final String FILE_NAME = "src/test/resources/example.xml";
private Dom4JParser parser;
@Test
public void getRootElementTest() {
parser = new Dom4JParser(new File(FILE_NAME));
Element root = parser.getRootElement();
assertNotNull(root);
assertTrue(root.elements().size() == 4);
}
@Test
public void getFirstElementListTest() {
parser = new Dom4JParser(new File(FILE_NAME));
List<Element> firstList = parser.getFirstElementList();
assertNotNull(firstList);
assertTrue(firstList.size() == 4);
assertTrue(firstList.get(0).attributeValue("type").equals("java"));
}
@Test
public void getElementByIdTest() {
parser = new Dom4JParser(new File(FILE_NAME));
Node element = parser.getNodeById("03");
String type = element.valueOf("@type");
assertEquals("android", type);
}
@Test
public void getElementsListByTitleTest() {
parser = new Dom4JParser(new File(FILE_NAME));
Node element = parser.getElementsListByTitle("XML");
assertEquals("java", element.valueOf("@type"));
assertEquals("02", element.valueOf("@tutId"));
assertEquals("XML", element.selectSingleNode("title").getText());
assertEquals("title", element.selectSingleNode("title").getName());
}
@Test
public void generateModifiedDocumentTest() {
parser = new Dom4JParser(new File(FILE_NAME));
parser.generateModifiedDocument();
File generatedFile = new File("src/test/resources/example_updated.xml");
assertTrue(generatedFile.exists());
parser.setFile(generatedFile);
Node element = parser.getNodeById("02");
assertEquals("XML updated", element.selectSingleNode("title").getText());
}
@Test
public void generateNewDocumentTest() {
parser = new Dom4JParser(new File(FILE_NAME));
parser.generateNewDocument();
File newFile = new File("src/test/resources/example_new.xml");
assertTrue(newFile.exists());
parser.setFile(newFile);
Node element = parser.getNodeById("01");
assertEquals("XML with Dom4J", element.selectSingleNode("title").getText());
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.xml;
import org.jdom2.Element;
import org.junit.Test;
import java.io.File;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class JDomParserTest {
private final String fileName = "src/test/resources/example.xml";
private JDomParser parser;
@Test
public void getFirstElementListTest() {
parser = new JDomParser(new File(fileName));
List<Element> firstList = parser.getAllTitles();
assertNotNull(firstList);
assertTrue(firstList.size() == 4);
assertTrue(firstList.get(0).getAttributeValue("type").equals("java"));
}
@Test
public void getElementByIdTest() {
parser = new JDomParser(new File(fileName));
Element el = parser.getNodeById("03");
String type = el.getAttributeValue("type");
assertEquals("android", type);
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.xml;
import com.baeldung.xml.binding.Tutorials;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class JaxbParserTest {
private final String fileName = "src/test/resources/example.xml";
private JaxbParser parser;
@Test
public void getFullDocumentTest(){
parser = new JaxbParser(new File(fileName));
Tutorials tutorials = parser.getFullDocument();
assertNotNull(tutorials);
assertTrue(tutorials.getTutorial().size() == 4);
assertTrue(tutorials.getTutorial().get(0).getType().equalsIgnoreCase("java"));
}
@Test
public void createNewDocumentTest(){
File newFile = new File("src/test/resources/example_new.xml");
parser = new JaxbParser(newFile);
parser.createNewDocument();
assertTrue(newFile.exists());
Tutorials tutorials = parser.getFullDocument();
assertNotNull(tutorials);
assertTrue(tutorials.getTutorial().size() == 1);
assertTrue(tutorials.getTutorial().get(0).getTitle().equalsIgnoreCase("XML with Jaxb"));
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.xml;
import org.junit.Test;
import java.io.File;
import java.util.List;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class JaxenDemoTest {
private final String fileName = "src/test/resources/example.xml";
private JaxenDemo jaxenDemo;
@Test
public void getFirstLevelNodeListTest() {
jaxenDemo = new JaxenDemo(new File(fileName));
List<?> list = jaxenDemo.getAllTutorial();
assertNotNull(list);
assertTrue(list.size() == 4);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.xml;
import com.baeldung.xml.model.Tutorial;
import org.junit.Test;
import java.io.File;
import java.util.List;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class StaxParserTest {
private final String fileName = "src/test/resources/example.xml";
private StaxParser parser;
@Test
public void getAllTutorialsTest(){
parser = new StaxParser(new File(fileName));
List<Tutorial> tutorials = parser.getAllTutorial();
assertNotNull(tutorials);
assertTrue(tutorials.size() == 4);
assertTrue(tutorials.get(0).getType().equalsIgnoreCase("java"));
}
}

View File

@ -1,24 +1,24 @@
<?xml version="1.0"?>
<Tutorials>
<Tutorial tutId="01" type="java">
<tutorials>
<tutorial tutId="01" type="java">
<title>Guava</title>
<description>Introduction to Guava</description>
<date>04/04/2016</date>
<author>GuavaAuthor</author>
</Tutorial>
<Tutorial tutId="02" type="java">
</tutorial>
<tutorial tutId="02" type="java">
<title>XML</title>
<description>Introduction to XPath</description>
<date>04/05/2016</date>
<author>XMLAuthor</author>
</Tutorial>
<Tutorial tutId="03" type="android">
</tutorial>
<tutorial tutId="03" type="android">
<title>Android</title>
<description>Introduction to Android</description>
<date>04/03/2016</date>
<author>AndroidAuthor</author>
</Tutorial>
<Tutorial tutId="04" type="java">
</tutorial>
<tutorial tutId="04" type="java">
<title>Spring</title>
<description>Introduction to Spring</description>
<date>04/02/2016</date>
@ -28,5 +28,5 @@
<section name="mvc">Spring MVC</section>
<section name="batch">Spring Batch</section>
</sections>
</Tutorial>
</Tutorials>
</tutorial>
</tutorials>

View File

@ -1,24 +1,24 @@
<?xml version="1.0"?>
<Tutorials xmlns="http://www.baeldung.com/full_archive">
<Tutorial tutId="01" type="java">
<tutorials xmlns="http://www.baeldung.com/full_archive">
<tutorial tutId="01" type="java">
<title>Guava</title>
<description>Introduction to Guava</description>
<date>04/04/2016</date>
<author>GuavaAuthor</author>
</Tutorial>
<Tutorial tutId="02" type="java">
</tutorial>
<tutorial tutId="02" type="java">
<title>XML</title>
<description>Introduction to XPath</description>
<date>04/05/2016</date>
<author>XMLAuthor</author>
</Tutorial>
<Tutorial tutId="03" type="android">
</tutorial>
<tutorial tutId="03" type="android">
<title>Android</title>
<description>Introduction to Android</description>
<date>04/03/2016</date>
<author>AndroidAuthor</author>
</Tutorial>
<Tutorial tutId="04" type="java">
</tutorial>
<tutorial tutId="04" type="java">
<title>Spring</title>
<description>Introduction to Spring</description>
<date>04/02/2016</date>
@ -28,5 +28,5 @@
<section name="mvc">Spring MVC</section>
<section name="batch">Spring Batch</section>
</sections>
</Tutorial>
</Tutorials>
</tutorial>
</tutorials>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<XMLTutorials>
<tutorial tutId="01" type="xml">
<title>XML with Dom4J</title>
<description>XML handling with Dom4J</description>
<date>14/06/2016</date>
<author>Dom4J tech writer</author>
</tutorial>
</XMLTutorials>

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<tutorials>
<tutorial tutId="01" type="java">
<title>Guava updated</title>
<description>Introduction to Guava</description>
<date>04/04/2016</date>
<author>GuavaAuthor</author>
</tutorial>
<tutorial tutId="02" type="java">
<title>XML updated</title>
<description>Introduction to XPath</description>
<date>04/05/2016</date>
<author>XMLAuthor</author>
</tutorial>
<tutorial tutId="03" type="android">
<title>Android updated</title>
<description>Introduction to Android</description>
<date>04/03/2016</date>
<author>AndroidAuthor</author>
</tutorial>
<tutorial tutId="04" type="java">
<title>Spring updated</title>
<description>Introduction to Spring</description>
<date>04/02/2016</date>
<author>SpringAuthor</author>
<sections>
<section name="core">Spring Core</section>
<section name="mvc">Spring MVC</section>
<section name="batch">Spring Batch</section>
</sections>
</tutorial>
</tutorials>