Skip to content

Commit 2fde57d

Browse files
committed
test parsowania XML
1 parent 035b1b9 commit 2fde57d

File tree

5 files changed

+326
-16
lines changed

5 files changed

+326
-16
lines changed

spring-capgemini-jaxb/src/main/java/pl/altkom/spring/capgemini/jaxb/BaseXMLSerializer.java

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
/*
2-
* To change this license header, choose License Headers in Project Properties.
3-
* To change this template file, choose Tools | Templates
4-
* and open the template in the editor.
2+
* Copyright 2012-06-05 the original author or authors.
53
*/
64
package pl.altkom.spring.capgemini.jaxb;
75

@@ -17,7 +15,7 @@
1715

1816
/**
1917
*
20-
* @author instruktor
18+
* @author Adrian Lapierre <[email protected]>
2119
*/
2220
public class BaseXMLSerializer<T> {
2321

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/*
2+
* Copyright 2012-06-05 the original author or authors.
3+
*/
4+
package pl.altkom.spring.capgemini.jaxb;
5+
6+
import java.text.SimpleDateFormat;
7+
import java.util.Calendar;
8+
import java.util.Date;
9+
import java.util.GregorianCalendar;
10+
import javax.xml.datatype.DatatypeConfigurationException;
11+
import javax.xml.datatype.DatatypeFactory;
12+
import javax.xml.datatype.XMLGregorianCalendar;
13+
14+
/**
15+
*
16+
* @author Adrian Lapierre <[email protected]>
17+
*/
18+
public class DataTools {
19+
20+
private static final int MILLISECONDS_IN_DAY = 1000 * 60 * 60 * 24;
21+
22+
/**
23+
* Calculates the number of days between start and end dates, taking into
24+
* consideration leap years, year boundaries etc.
25+
*
26+
* @param start the start date
27+
* @param end the end date, must be later than the start date
28+
* @return the number of days between the start and end dates
29+
*/
30+
public static long countDaysBetween(Date start, Date end) {
31+
if (end.before(start)) {
32+
return 0;
33+
//throw new IllegalArgumentException("The end date must be later than the start date");
34+
}
35+
36+
//reset all hours mins and secs to zero on start date
37+
Calendar startCal = GregorianCalendar.getInstance();
38+
startCal.setTime(start);
39+
startCal.set(Calendar.HOUR_OF_DAY, 0);
40+
startCal.set(Calendar.MINUTE, 0);
41+
startCal.set(Calendar.SECOND, 0);
42+
long startTime = startCal.getTimeInMillis();
43+
44+
//reset all hours mins and secs to zero on end date
45+
Calendar endCal = GregorianCalendar.getInstance();
46+
endCal.setTime(end);
47+
endCal.set(Calendar.HOUR_OF_DAY, 0);
48+
endCal.set(Calendar.MINUTE, 0);
49+
endCal.set(Calendar.SECOND, 0);
50+
long endTime = endCal.getTimeInMillis();
51+
52+
return (endTime - startTime) / MILLISECONDS_IN_DAY;
53+
}
54+
55+
public static Date convertXMLCalendar(XMLGregorianCalendar calendar) {
56+
return calendar.toGregorianCalendar().getTime();
57+
}
58+
59+
public static XMLGregorianCalendar toXMLCalendar(Date date) {
60+
61+
GregorianCalendar c = new GregorianCalendar();
62+
c.setTime(date);
63+
64+
try {
65+
XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DATE), 0);
66+
return xmlCal;
67+
} catch (DatatypeConfigurationException ex) {
68+
return null;
69+
}
70+
}
71+
72+
public static Date addDaysToDate(Date start, int days) {
73+
Calendar calendar = GregorianCalendar.getInstance();
74+
calendar.setTime(start);
75+
calendar.add(Calendar.DAY_OF_MONTH, days);
76+
77+
return calendar.getTime();
78+
}
79+
80+
public static String formatDateWithTime(Date date) {
81+
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sXXX");
82+
return df.format(date);
83+
}
84+
85+
public static String formatDate(Date date) {
86+
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
87+
return df.format(date);
88+
}
89+
}
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,20 @@
11
/*
2-
* To change this license header, choose License Headers in Project Properties.
3-
* To change this template file, choose Tools | Templates
4-
* and open the template in the editor.
2+
* Copyright 2012-06-05 the original author or authors.
53
*/
6-
74
package pl.altkom.spring.capgemini.jaxb;
85

96
import pl.com.softproject.commons.model.invoice.Invoice;
107

118
/**
129
*
13-
* @author instruktor
10+
* @author Adrian Lapierre <[email protected]>
1411
*/
15-
public class InvoiceSerializer extends BaseXMLSerializer<Invoice>{
12+
public class InvoiceSerializer extends BaseXMLSerializer<Invoice> {
1613

1714
public InvoiceSerializer() {
18-
super("pl.com.softproject.commons.model.invoice",
19-
"invoice.xsd",
15+
super("pl.com.softproject.commons.model.invoice",
16+
"invoice.xsd",
2017
"http://www.softproject.com.pl/commons/model/invoice http://schema.softproject.com.pl/commons/invoice.xsd");
2118
}
22-
23-
24-
19+
2520
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
/*
2+
* Copyright 2012-04-17 the original author or authors.
3+
*/
4+
5+
6+
package pl.altkom.spring.capgemini.jaxb;
7+
8+
import java.io.IOException;
9+
import java.io.Reader;
10+
import java.net.URL;
11+
import java.util.ArrayList;
12+
import java.util.Collection;
13+
import java.util.List;
14+
import javax.xml.bind.JAXBContext;
15+
import javax.xml.bind.JAXBException;
16+
import javax.xml.bind.util.JAXBSource;
17+
import javax.xml.parsers.DocumentBuilder;
18+
import javax.xml.parsers.DocumentBuilderFactory;
19+
import javax.xml.parsers.ParserConfigurationException;
20+
import javax.xml.transform.Source;
21+
import javax.xml.transform.stream.StreamSource;
22+
import javax.xml.validation.Schema;
23+
import javax.xml.validation.SchemaFactory;
24+
import javax.xml.validation.Validator;
25+
import org.apache.log4j.Logger;
26+
import org.xml.sax.ErrorHandler;
27+
import org.xml.sax.InputSource;
28+
import org.xml.sax.SAXException;
29+
import org.xml.sax.SAXParseException;
30+
31+
/**
32+
*
33+
* @author Adrian Lapierre <[email protected]>
34+
*/
35+
public class XMLValidator {
36+
37+
private static Logger logger = Logger.getLogger(XMLValidator.class);
38+
39+
/**
40+
* Sprawdza składnie XML w przekazanym dokumencie
41+
*
42+
* @param reader - Reader do dokumentu XML
43+
* @param errors - zainicjowana kolekcja, w której zostaną˝ zwrócone błędy.
44+
* Kolekcja zostanie wyzerowana.
45+
* @return
46+
* @throws javax.xml.parsers.ParserConfigurationException
47+
* @throws java.io.IOException
48+
*/
49+
public static boolean checkSyntax(Reader reader, Collection<SAXParseException> errors) throws ParserConfigurationException, IOException {
50+
51+
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
52+
dbf.setValidating(false);
53+
dbf.setNamespaceAware(true);
54+
55+
DocumentBuilder builder = dbf.newDocumentBuilder();
56+
builder.setErrorHandler(new XMLErrorHandler(errors));
57+
58+
//InputSource is = new InputSource(filename);
59+
InputSource source = new InputSource(reader);
60+
try {
61+
builder.parse(source);
62+
} catch (SAXException ignore) {
63+
}
64+
65+
return errors.isEmpty();
66+
}
67+
68+
/**
69+
* Validuje XML względem XML Schemy
70+
*
71+
* @param reader - Reader do dokumentu XML
72+
* @param schemaLocation - url do shcemy XML, jeżli jest null to zostanie
73+
* użyta schema wskazana w atrybucie schemaLocation z dokumentu XML
74+
* @param errors - zainicjowana kolekcja, w kt�rej zostan� zwr�cone
75+
* b��dy. Kolekcja zostanie wyzerowana.
76+
* @return - true je�li dokument validuje si�
77+
* @throws org.xml.sax.SAXException - je�li nie mo�na zainicjowa�
78+
* parsera
79+
* @throws java.io.IOException - je�li nie mo�na czyta� z Readera
80+
*/
81+
public static boolean validate(Reader reader, URL schemaLocation, Collection<SAXParseException> errors) throws SAXException, IOException {
82+
//List<SAXParseException> errors = new LinkedList<SAXParseException>();
83+
84+
errors.clear();
85+
86+
// 1. Lookup a factory for the W3C XML Schema language
87+
SchemaFactory factory
88+
= SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
89+
90+
// 2. Compile the schema.
91+
Schema schema = null;
92+
//schema = factory.newSchema(new URL("http://www.dmh.pl/schema/dsml/dsml-1_2_14/dsml.xsd"));
93+
//schema = factory.newSchema(new File("D:/realizacje/CharSource/svn-nowy/dsml/dsml-core/src/main/xsd/dsml.xsd"));
94+
if (schemaLocation == null) {
95+
schema = factory.newSchema();
96+
} else {
97+
schema = factory.newSchema(schemaLocation);
98+
}
99+
100+
// 3. Get a validator from the schema.
101+
Validator validator = schema.newValidator();
102+
103+
// 4. Parse the document you want to check.
104+
Source source = new StreamSource(reader);
105+
106+
// 5. Check the document
107+
validator.setErrorHandler(new XMLErrorHandler(errors));
108+
validator.validate(source);
109+
110+
return errors.isEmpty();
111+
}
112+
113+
/**
114+
* Validuje XML względem XML Schemy, lokalizacja schemy będzie pobrana z
115+
* atrybutu schemaLocation z dokumentu XML
116+
*
117+
* @param reader - Reader do dokumentu XML
118+
* @param errors - zainicjowana kolekcja, w której zostaną zwrócone błędy.
119+
* Kolekcja zostanie wyzerowana.
120+
* @return - true jeśli dokument validuje się
121+
* @throws org.xml.sax.SAXException - jeśli nie można zainicjować parsera
122+
* @throws java.io.IOException - je�li nie mo�na czyta� z Readera
123+
*/
124+
public static boolean validate(Reader reader, Collection<SAXParseException> errors) throws SAXException, IOException {
125+
126+
return validate(reader, null, errors);
127+
}
128+
129+
/**
130+
* Validuje XML względem XML Schemy, lokalizacja schemy będzie pobrana z
131+
* atrybutu schemaLocation z dokumentu XML Metoda z założenia, nigdy nie
132+
* rzuca wyąkami. Gdy walidacje nie przejdzie zwraca po prostu "false".
133+
*
134+
* @param <T>
135+
* @param dsml - dokument który powstał‚ w wyniku wywołania metody
136+
* "unmarshal". Np. DsmlDocument lub DomainsDocument.
137+
* @param xsdFileName - nazwa pliku xsd, jeśli jest null to zostanie użyta
138+
* schema wskazana w atrybucie schemaLocation z dokumentu XML.
139+
* @param exceptions - kolekcja, w której zostaną zwrócone błędy.
140+
* @return - true jeśli dokument przechodzi poprawnie walidację.
141+
*/
142+
public static <T> boolean validate(T dsml, String xsdFileName, List<SAXParseException> exceptions) {
143+
try {
144+
Schema schema = null;
145+
146+
String contextPath = dsml.getClass().getPackage().getName();
147+
JAXBContext jc = JAXBContext.newInstance(contextPath);
148+
149+
JAXBSource source = new JAXBSource(jc, dsml);
150+
151+
SchemaFactory factory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
152+
153+
if (xsdFileName == null) {
154+
schema = factory.newSchema();
155+
} else {
156+
URL schemaLocation = XMLValidator.class.getClassLoader().getResource(xsdFileName);
157+
schema = factory.newSchema(schemaLocation);
158+
}
159+
160+
Validator validator = schema.newValidator();
161+
162+
if (exceptions == null) {
163+
exceptions = new ArrayList<SAXParseException>();
164+
}
165+
166+
validator.setErrorHandler(new XMLValidator.XMLErrorExtensionHandler(exceptions));
167+
validator.validate(source);
168+
169+
return exceptions.isEmpty();
170+
171+
} catch (SAXException ex) {
172+
throw new RuntimeException(ex.getMessage(), ex);
173+
} catch (JAXBException ex) {
174+
throw new RuntimeException(ex.getMessage(), ex);
175+
} catch (IOException ex) {
176+
throw new RuntimeException(ex.getMessage(), ex);
177+
} catch (Exception ex) {
178+
throw new RuntimeException(ex.getMessage(), ex);
179+
}
180+
}
181+
182+
public static class XMLErrorHandler implements ErrorHandler {
183+
184+
public XMLErrorHandler(Collection<SAXParseException> errors) {
185+
this.errors = errors;
186+
}
187+
188+
private Collection<SAXParseException> errors;
189+
190+
@Override
191+
public void warning(SAXParseException exception) throws SAXException {
192+
errors.add(exception);
193+
}
194+
195+
@Override
196+
public void error(SAXParseException exception) throws SAXException {
197+
errors.add(exception);
198+
}
199+
200+
@Override
201+
public void fatalError(SAXParseException exception) throws SAXException {
202+
errors.add(exception);
203+
}
204+
}
205+
206+
public static class XMLErrorExtensionHandler extends XMLErrorHandler {
207+
208+
public XMLErrorExtensionHandler(List<SAXParseException> exceptions) {
209+
super(exceptions);
210+
}
211+
212+
@Override
213+
public void warning(SAXParseException exception) throws SAXException {
214+
String message = exception.getMessage() != null ? exception.getMessage() : "";
215+
logger.warn(message, exception);
216+
}
217+
}
218+
}

spring-capgemini-jaxb/src/test/java/pl/altkom/spring/capgemini/jaxb/InvoiceSerializerTest.java

+11-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
package pl.altkom.spring.capgemini.jaxb;
88

9+
import java.io.File;
910
import org.junit.Test;
1011
import static org.junit.Assert.*;
1112
import pl.com.softproject.commons.model.invoice.Invoice;
@@ -16,7 +17,16 @@
1617
*/
1718
public class InvoiceSerializerTest {
1819

19-
20+
@Test
21+
public void testParse() {
22+
23+
InvoiceSerializer serializer = new InvoiceSerializer();
24+
25+
Invoice invoice = serializer.fromFile(new File("src/main/resources/FS 1_MAG_05_2012.xml"));
26+
27+
System.out.println(serializer.toString(invoice));
28+
29+
}
2030

2131
@Test
2232
public void testCrateXML() {

0 commit comments

Comments
 (0)