[Fix] Always use SAXParserFactory feature disallow-doctype-decl=true

This commit is contained in:
Robert von Burg 2023-11-30 12:16:28 +01:00
parent 2ab8d95c0b
commit 579cd0b0e5
Signed by: eitch
GPG Key ID: 75DB9C85C74331F7
16 changed files with 369 additions and 335 deletions

View File

@ -1,11 +1,14 @@
package li.strolch.model.xml;
import static java.nio.charset.StandardCharsets.UTF_8;
import static li.strolch.model.StrolchModelConstants.DEFAULT_ENCODING;
import static li.strolch.model.StrolchModelConstants.DEFAULT_XML_VERSION;
import javanet.staxutils.IndentingXMLStreamWriter;
import li.strolch.model.Order;
import li.strolch.model.Resource;
import li.strolch.model.StrolchRootElement;
import li.strolch.model.Tags;
import li.strolch.model.activity.Activity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
@ -19,14 +22,10 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javanet.staxutils.IndentingXMLStreamWriter;
import li.strolch.model.Order;
import li.strolch.model.Resource;
import li.strolch.model.StrolchRootElement;
import li.strolch.model.Tags;
import li.strolch.model.activity.Activity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.nio.charset.StandardCharsets.UTF_8;
import static li.strolch.model.StrolchModelConstants.DEFAULT_ENCODING;
import static li.strolch.model.StrolchModelConstants.DEFAULT_XML_VERSION;
import static li.strolch.utils.helper.XmlHelper.getSaxParser;
public class StrolchXmlHelper {
@ -69,8 +68,7 @@ public class StrolchXmlHelper {
private static SimpleStrolchElementListener parse(String xml) {
try {
SimpleStrolchElementListener elementListener = new SimpleStrolchElementListener();
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes(UTF_8)), new XmlModelSaxReader(elementListener));
getSaxParser().parse(new ByteArrayInputStream(xml.getBytes(UTF_8)), new XmlModelSaxReader(elementListener));
return elementListener;
} catch (Exception e) {
throw new IllegalStateException("Failed to parse XML", e);

View File

@ -15,19 +15,19 @@
*/
package li.strolch.model.xml;
import static li.strolch.utils.helper.StringHelper.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import li.strolch.exception.StrolchException;
import li.strolch.model.Tags;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import java.io.File;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import static li.strolch.utils.helper.StringHelper.formatNanoDuration;
import static li.strolch.utils.helper.StringHelper.isEmpty;
import static li.strolch.utils.helper.XmlHelper.getSaxParser;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@ -61,7 +61,8 @@ public class XmlModelSaxFileReader extends XmlModelSaxReader {
File includeFile = new File(this.modelFile.getParentFile(), includeFileS);
if (!includeFile.exists() || !includeFile.canRead()) {
String msg = "The IncludeFile does not exist, or is not readable. Source model: {0} with IncludeFile: {1}";
String msg
= "The IncludeFile does not exist, or is not readable. Source model: {0} with IncludeFile: {1}";
msg = MessageFormat.format(msg, this.modelFile.getAbsolutePath(), includeFileS);
throw new IllegalArgumentException(msg);
}
@ -78,10 +79,7 @@ public class XmlModelSaxFileReader extends XmlModelSaxReader {
long startNanos = System.nanoTime();
this.statistics.startTime = LocalDateTime.now();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
sp.parse(this.modelFile, this);
getSaxParser().parse(this.modelFile, this);
long endNanos = System.nanoTime();
this.statistics.durationNanos = endNanos - startNanos;

View File

@ -15,11 +15,14 @@
*/
package li.strolch.model.xml;
import static li.strolch.model.StrolchModelConstants.DEFAULT_ENCODING;
import li.strolch.exception.StrolchException;
import li.strolch.model.Tags;
import li.strolch.utils.helper.StringHelper;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@ -27,12 +30,8 @@ import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import li.strolch.exception.StrolchException;
import li.strolch.model.Tags;
import li.strolch.utils.helper.StringHelper;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import static li.strolch.model.StrolchModelConstants.DEFAULT_ENCODING;
import static li.strolch.utils.helper.XmlHelper.getSaxParser;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -85,10 +84,7 @@ public class XmlModelSaxStreamReader extends XmlModelSaxReader {
long startNanos = System.nanoTime();
this.statistics.startTime = LocalDateTime.now();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
sp.parse(this.source, this);
getSaxParser().parse(this.source, this);
long endNanos = System.nanoTime();
this.statistics.durationNanos = endNanos - startNanos;

View File

@ -1,19 +1,5 @@
package li.strolch.model.activity;
import static li.strolch.model.ModelGenerator.*;
import static org.junit.Assert.assertEquals;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.StringWriter;
import li.strolch.model.timevalue.IValueChange;
import li.strolch.model.timevalue.impl.IntegerValue;
import li.strolch.model.timevalue.impl.ValueChange;
@ -25,6 +11,19 @@ import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.StringWriter;
import static li.strolch.model.ModelGenerator.*;
import static li.strolch.utils.helper.XmlHelper.getDocumentBuilder;
import static org.junit.Assert.assertEquals;
public class ActionTest {
private static final Logger logger = LoggerFactory.getLogger(ActionTest.class);
@ -76,8 +75,7 @@ public class ActionTest {
// @Test
public void showToDOM() throws ParserConfigurationException, TransformerException {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.newDocument();
Document document = getDocumentBuilder().newDocument();
Element dom = new StrolchElementToDomVisitor().toDom(this.action);
document.appendChild(dom);

View File

@ -15,10 +15,16 @@
*/
package li.strolch.model.activity;
import static org.junit.Assert.*;
import li.strolch.exception.StrolchException;
import li.strolch.model.ModelGenerator;
import li.strolch.model.State;
import li.strolch.model.xml.StrolchElementToDomVisitor;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
@ -31,15 +37,8 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import li.strolch.exception.StrolchException;
import li.strolch.model.ModelGenerator;
import li.strolch.model.State;
import li.strolch.model.xml.StrolchElementToDomVisitor;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import static li.strolch.utils.helper.XmlHelper.getDocumentBuilder;
import static org.junit.Assert.*;
public class ActivityTest {
@ -342,9 +341,7 @@ public class ActivityTest {
// @Test
public void showToDOM() throws ParserConfigurationException, TransformerException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
Document document = getDocumentBuilder().newDocument();
Element dom = new StrolchElementToDomVisitor().toDom(this.activity);
document.appendChild(dom);

View File

@ -15,15 +15,6 @@
*/
package li.strolch.persistence.postgresql;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Calendar;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import li.strolch.model.activity.Activity;
@ -35,18 +26,32 @@ import li.strolch.persistence.api.StrolchPersistenceException;
import li.strolch.persistence.api.TransactionResult;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Calendar;
import static li.strolch.utils.helper.XmlHelper.getSaxParser;
@SuppressWarnings("nls")
public class PostgreSqlActivityDao extends PostgresqlDao<Activity> implements ActivityDao {
public static final String ACTIVITIES = "activities";
private static final String insertAsXmlSqlS = "insert into {0} (id, version, created_by, created_at, updated_at, deleted, latest, name, type, state, asxml) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?::order_state, ?)";
private static final String insertAsJsonSqlS = "insert into {0} (id, version, created_by, created_at, updated_at, deleted, latest, name, type, state, asjson) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?::order_state, ?)";
private static final String insertAsXmlSqlS
= "insert into {0} (id, version, created_by, created_at, updated_at, deleted, latest, name, type, state, asxml) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?::order_state, ?)";
private static final String insertAsJsonSqlS
= "insert into {0} (id, version, created_by, created_at, updated_at, deleted, latest, name, type, state, asjson) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?::order_state, ?)";
private static final String updateAsXmlSqlS = "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, state = ?::order_state, asxml = ? where type = ? and id = ? and version = ?";
private static final String updateAsJsonSqlS = "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, state = ?::order_state, asjson = ? where type = ? and id = ? and version = ?";
private static final String updateAsXmlSqlS
= "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, state = ?::order_state, asxml = ? where type = ? and id = ? and version = ?";
private static final String updateAsJsonSqlS
= "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, state = ?::order_state, asjson = ? where type = ? and id = ? and version = ?";
private static final String updateLatestSqlS = "update {0} SET latest = false WHERE type = ? and id = ? AND version = ?";
private static final String updateLatestSqlS
= "update {0} SET latest = false WHERE type = ? and id = ? AND version = ?";
public PostgreSqlActivityDao(DataType dataType, Connection connection, TransactionResult txResult,
boolean versioningEnabled) {
@ -62,8 +67,7 @@ public class PostgreSqlActivityDao extends PostgresqlDao<Activity> implements Ac
protected Activity parseFromXml(String id, String type, SQLXML sqlxml) {
SimpleStrolchElementListener listener = new SimpleStrolchElementListener();
try (InputStream binaryStream = sqlxml.getBinaryStream()) {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(binaryStream, new XmlModelSaxReader(listener));
getSaxParser().parse(binaryStream, new XmlModelSaxReader(listener));
} catch (SQLException | IOException | SAXException | ParserConfigurationException e) {
throw new StrolchPersistenceException(
MessageFormat.format("Failed to extract Activity from sqlxml value for {0} / {1}", id, type), e);
@ -126,9 +130,9 @@ public class PostgreSqlActivityDao extends PostgresqlDao<Activity> implements Ac
}
} catch (SQLException | SAXException e) {
throw new StrolchPersistenceException(MessageFormat
.format("Failed to insert Activity {0} due to {1}", activity.getLocator(), e.getLocalizedMessage()),
e);
throw new StrolchPersistenceException(
MessageFormat.format("Failed to insert Activity {0} due to {1}", activity.getLocator(),
e.getLocalizedMessage()), e);
}
if (activity.getVersion().isFirstVersion()) {
@ -146,15 +150,16 @@ public class PostgreSqlActivityDao extends PostgresqlDao<Activity> implements Ac
int modCount = preparedStatement.executeUpdate();
if (modCount != 1) {
String msg = "Expected to update 1 previous element with id {0} and version {1} but SQL statement modified {2} elements!";
String msg
= "Expected to update 1 previous element with id {0} and version {1} but SQL statement modified {2} elements!";
msg = MessageFormat.format(msg, activity.getId(), activity.getVersion().getPreviousVersion(), modCount);
throw new StrolchPersistenceException(msg);
}
} catch (SQLException e) {
throw new StrolchPersistenceException(MessageFormat
.format("Failed to update previous version of Activity {0} due to {1}", activity.getVersion(),
e.getLocalizedMessage()), e);
throw new StrolchPersistenceException(
MessageFormat.format("Failed to update previous version of Activity {0} due to {1}",
activity.getVersion(), e.getLocalizedMessage()), e);
}
}
@ -169,15 +174,15 @@ public class PostgreSqlActivityDao extends PostgresqlDao<Activity> implements Ac
// make sure is first version when versioning is not enabled
if (!activity.getVersion().isFirstVersion()) {
throw new StrolchPersistenceException(MessageFormat
.format("Versioning is not enabled, so version must always be 0 to perform an update, but it is {0}",
activity.getVersion()));
throw new StrolchPersistenceException(MessageFormat.format(
"Versioning is not enabled, so version must always be 0 to perform an update, but it is {0}",
activity.getVersion()));
}
// and also not marked as deleted!
if (activity.getVersion().isDeleted()) {
throw new StrolchPersistenceException(MessageFormat
.format("Versioning is not enabled, so version can not be marked as deleted for {0}",
throw new StrolchPersistenceException(
MessageFormat.format("Versioning is not enabled, so version can not be marked as deleted for {0}",
activity.getVersion()));
}
@ -219,9 +224,9 @@ public class PostgreSqlActivityDao extends PostgresqlDao<Activity> implements Ac
}
} catch (SQLException | SAXException e) {
throw new StrolchPersistenceException(MessageFormat
.format("Failed to update Activity {0} due to {1}", activity.getLocator(), e.getLocalizedMessage()),
e);
throw new StrolchPersistenceException(
MessageFormat.format("Failed to update Activity {0} due to {1}", activity.getLocator(),
e.getLocalizedMessage()), e);
}
}
}

View File

@ -15,17 +15,6 @@
*/
package li.strolch.persistence.postgresql;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import li.strolch.model.Order;
@ -39,31 +28,54 @@ import li.strolch.utils.collections.DateRange;
import li.strolch.utils.iso8601.ISO8601;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import static li.strolch.utils.helper.XmlHelper.getSaxParser;
@SuppressWarnings("nls")
public class PostgreSqlOrderDao extends PostgresqlDao<Order> implements OrderDao {
public static final String ORDERS = "orders";
private static final String querySizeDrSqlS = "select count(*) from {0} where latest = true {1}";
private static final String querySizeOfTypeDrSqlS = "select count(*) from {0} where type = ANY(?) and latest = true {1}";
private static final String querySizeOfTypeDrSqlS
= "select count(*) from {0} where type = ANY(?) and latest = true {1}";
private static final String queryAllDrAsXmlSqlS = "select id, type, asxml from {0} where latest = true {1}";
private static final String queryAllDrAsXmlLimitSqlS = "select id, type, asxml from {0} where latest = true {1} order by date {2} limit {3} offset {4}";
private static final String queryAllDrAsXmlLimitSqlS
= "select id, type, asxml from {0} where latest = true {1} order by date {2} limit {3} offset {4}";
private static final String queryAllDrAsJsonSqlS = "select id, type, asjson from {0} where latest = true {1}";
private static final String queryAllDrAsJsonLimitSqlS = "select id, type, asjson from {0} where latest = true {1} order by date {2} limit {3} offset {4}";
private static final String queryAllDrAsJsonLimitSqlS
= "select id, type, asjson from {0} where latest = true {1} order by date {2} limit {3} offset {4}";
private static final String queryAllByTypeDrAsXmlSqlS = "select id, type, asxml from {0} where type = ANY(?) and latest = true {1}";
private static final String queryAllByTypeDrAsXmlLimitSqlS = "select id, type, asxml from {0} where type = ANY(?) and latest = true {1} order by date {2} limit {3,number,#} offset {4,number,#}";
private static final String queryAllByTypeDrAsJsonSqlS = "select id, type, asjson from {0} where type = ANY(?) and latest = true {1}";
private static final String queryAllByTypeDrAsJsonLimitSqlS = "select id, type, asjson from {0} where type = ANY(?) and latest = true {1} order by date {2} limit {3,number,#} offset {4,number,#}";
private static final String queryAllByTypeDrAsXmlSqlS
= "select id, type, asxml from {0} where type = ANY(?) and latest = true {1}";
private static final String queryAllByTypeDrAsXmlLimitSqlS
= "select id, type, asxml from {0} where type = ANY(?) and latest = true {1} order by date {2} limit {3,number,#} offset {4,number,#}";
private static final String queryAllByTypeDrAsJsonSqlS
= "select id, type, asjson from {0} where type = ANY(?) and latest = true {1}";
private static final String queryAllByTypeDrAsJsonLimitSqlS
= "select id, type, asjson from {0} where type = ANY(?) and latest = true {1} order by date {2} limit {3,number,#} offset {4,number,#}";
private static final String insertAsXmlSqlS = "insert into {0} (id, version, created_by, created_at, updated_at, deleted, latest, name, type, state, date, asxml) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?::order_state, ?, ?)";
private static final String insertAsJsonSqlS = "insert into {0} (id, version, created_by, created_at, updated_at, deleted, latest, name, type, state, date, asjson) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?::order_state, ?, ?)";
private static final String insertAsXmlSqlS
= "insert into {0} (id, version, created_by, created_at, updated_at, deleted, latest, name, type, state, date, asxml) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?::order_state, ?, ?)";
private static final String insertAsJsonSqlS
= "insert into {0} (id, version, created_by, created_at, updated_at, deleted, latest, name, type, state, date, asjson) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?::order_state, ?, ?)";
private static final String updateAsXmlSqlS = "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, state = ?::order_state, date = ?, asxml = ? where type = ? and id = ? and version = ?";
private static final String updateAsJsonSqlS = "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, state = ?::order_state, date = ?, asjson = ? where type = ? and id = ? and version = ?";
private static final String updateAsXmlSqlS
= "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, state = ?::order_state, date = ?, asxml = ? where type = ? and id = ? and version = ?";
private static final String updateAsJsonSqlS
= "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, state = ?::order_state, date = ?, asjson = ? where type = ? and id = ? and version = ?";
private static final String updateLatestSqlS = "update {0} SET latest = false WHERE type = ? and id = ? AND version = ?";
private static final String updateLatestSqlS
= "update {0} SET latest = false WHERE type = ? and id = ? AND version = ?";
public PostgreSqlOrderDao(DataType dataType, Connection connection, TransactionResult txResult,
boolean versioningEnabled) {
@ -79,8 +91,7 @@ public class PostgreSqlOrderDao extends PostgresqlDao<Order> implements OrderDao
protected Order parseFromXml(String id, String type, SQLXML sqlxml) {
SimpleStrolchElementListener listener = new SimpleStrolchElementListener();
try (InputStream binaryStream = sqlxml.getBinaryStream()) {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(binaryStream, new XmlModelSaxReader(listener));
getSaxParser().parse(binaryStream, new XmlModelSaxReader(listener));
} catch (SQLException | IOException | SAXException | ParserConfigurationException e) {
throw new StrolchPersistenceException(
MessageFormat.format("Failed to extract Order from sqlxml value for {0} / {1}", id, type), e);
@ -115,10 +126,10 @@ public class PostgreSqlOrderDao extends PostgresqlDao<Order> implements OrderDao
// version
preparedStatement.setInt(2, order.getVersion().getVersion());
preparedStatement.setString(3, order.getVersion().getCreatedBy());
preparedStatement
.setTimestamp(4, new Timestamp(order.getVersion().getCreated().getTime()), Calendar.getInstance());
preparedStatement
.setTimestamp(5, new Timestamp(order.getVersion().getUpdated().getTime()), Calendar.getInstance());
preparedStatement.setTimestamp(4, new Timestamp(order.getVersion().getCreated().getTime()),
Calendar.getInstance());
preparedStatement.setTimestamp(5, new Timestamp(order.getVersion().getUpdated().getTime()),
Calendar.getInstance());
preparedStatement.setBoolean(6, order.getVersion().isDeleted());
preparedStatement.setBoolean(7, !order.getVersion().isDeleted());
@ -144,8 +155,9 @@ public class PostgreSqlOrderDao extends PostgresqlDao<Order> implements OrderDao
}
} catch (SQLException | SAXException e) {
throw new StrolchPersistenceException(MessageFormat
.format("Failed to insert Order {0} due to {1}", order.getVersion(), e.getLocalizedMessage()), e);
throw new StrolchPersistenceException(
MessageFormat.format("Failed to insert Order {0} due to {1}", order.getVersion(),
e.getLocalizedMessage()), e);
}
if (order.getVersion().isFirstVersion()) {
@ -163,15 +175,16 @@ public class PostgreSqlOrderDao extends PostgresqlDao<Order> implements OrderDao
int modCount = preparedStatement.executeUpdate();
if (modCount != 1) {
String msg = "Expected to update 1 previous element with id {0} and version {1} but SQL statement modified {2} elements!";
String msg
= "Expected to update 1 previous element with id {0} and version {1} but SQL statement modified {2} elements!";
msg = MessageFormat.format(msg, order.getId(), order.getVersion().getPreviousVersion(), modCount);
throw new StrolchPersistenceException(msg);
}
} catch (SQLException e) {
throw new StrolchPersistenceException(MessageFormat
.format("Failed to update previous version of Order {0} due to {1}", order.getVersion(),
e.getLocalizedMessage()), e);
throw new StrolchPersistenceException(
MessageFormat.format("Failed to update previous version of Order {0} due to {1}",
order.getVersion(), e.getLocalizedMessage()), e);
}
}
@ -186,15 +199,15 @@ public class PostgreSqlOrderDao extends PostgresqlDao<Order> implements OrderDao
// make sure is first version when versioning is not enabled
if (!order.getVersion().isFirstVersion()) {
throw new StrolchPersistenceException(MessageFormat
.format("Versioning is not enabled, so version must always be 0 to perform an update, but it is {0}",
order.getVersion()));
throw new StrolchPersistenceException(MessageFormat.format(
"Versioning is not enabled, so version must always be 0 to perform an update, but it is {0}",
order.getVersion()));
}
// and also not marked as deleted!
if (order.getVersion().isDeleted()) {
throw new StrolchPersistenceException(MessageFormat
.format("Versioning is not enabled, so version can not be marked as deleted for {0}",
throw new StrolchPersistenceException(
MessageFormat.format("Versioning is not enabled, so version can not be marked as deleted for {0}",
order.getVersion()));
}
@ -205,10 +218,10 @@ public class PostgreSqlOrderDao extends PostgresqlDao<Order> implements OrderDao
// version
preparedStatement.setString(1, order.getVersion().getCreatedBy());
preparedStatement
.setTimestamp(2, new Timestamp(order.getVersion().getCreated().getTime()), Calendar.getInstance());
preparedStatement
.setTimestamp(3, new Timestamp(order.getVersion().getUpdated().getTime()), Calendar.getInstance());
preparedStatement.setTimestamp(2, new Timestamp(order.getVersion().getCreated().getTime()),
Calendar.getInstance());
preparedStatement.setTimestamp(3, new Timestamp(order.getVersion().getUpdated().getTime()),
Calendar.getInstance());
preparedStatement.setBoolean(4, order.getVersion().isDeleted());
preparedStatement.setBoolean(5, !order.getVersion().isDeleted());
@ -228,7 +241,8 @@ public class PostgreSqlOrderDao extends PostgresqlDao<Order> implements OrderDao
try {
int modCount = preparedStatement.executeUpdate();
if (modCount != 1) {
String msg = "Expected to update 1 element with id {0} and version {1} but SQL statement modified {2} elements!";
String msg
= "Expected to update 1 element with id {0} and version {1} but SQL statement modified {2} elements!";
msg = MessageFormat.format(msg, order.getId(), order.getVersion().getVersion(), modCount);
throw new StrolchPersistenceException(msg);
}
@ -238,8 +252,9 @@ public class PostgreSqlOrderDao extends PostgresqlDao<Order> implements OrderDao
}
} catch (SQLException | SAXException e) {
throw new StrolchPersistenceException(MessageFormat
.format("Failed to update Order {0} due to {1}", order.getLocator(), e.getLocalizedMessage()), e);
throw new StrolchPersistenceException(
MessageFormat.format("Failed to update Order {0} due to {1}", order.getLocator(),
e.getLocalizedMessage()), e);
}
}

View File

@ -15,15 +15,6 @@
*/
package li.strolch.persistence.postgresql;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Calendar;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import li.strolch.model.Resource;
@ -35,18 +26,32 @@ import li.strolch.persistence.api.StrolchPersistenceException;
import li.strolch.persistence.api.TransactionResult;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Calendar;
import static li.strolch.utils.helper.XmlHelper.getSaxParser;
@SuppressWarnings("nls")
public class PostgreSqlResourceDao extends PostgresqlDao<Resource> implements ResourceDao {
public static final String RESOURCES = "resources";
private static final String insertAsXmlSqlS = "insert into {0} (id, version, created_by, updated_at, created_at, deleted, latest, name, type, asxml) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String insertAsJsonSqlS = "insert into {0} (id, version, created_by, updated_at, created_at, deleted, latest, name, type, asjson) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String insertAsXmlSqlS
= "insert into {0} (id, version, created_by, updated_at, created_at, deleted, latest, name, type, asxml) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String insertAsJsonSqlS
= "insert into {0} (id, version, created_by, updated_at, created_at, deleted, latest, name, type, asjson) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String updateAsXmlSqlS = "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, asxml = ? where type = ? and id = ? and version = ?";
private static final String updateAsJsonSqlS = "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, asjson = ? where type = ? and id = ? and version = ?";
private static final String updateAsXmlSqlS
= "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, asxml = ? where type = ? and id = ? and version = ?";
private static final String updateAsJsonSqlS
= "update {0} set created_by = ?, created_at = ?, updated_at = ?, deleted = ?, latest = ?, name = ?, asjson = ? where type = ? and id = ? and version = ?";
private static final String updateLatestSqlS = "update {0} SET latest = false WHERE type = ? and id = ? AND version = ?";
private static final String updateLatestSqlS
= "update {0} SET latest = false WHERE type = ? and id = ? AND version = ?";
protected PostgreSqlResourceDao(DataType dataType, Connection connection, TransactionResult txResult,
boolean versioningEnabled) {
@ -62,8 +67,7 @@ public class PostgreSqlResourceDao extends PostgresqlDao<Resource> implements Re
protected Resource parseFromXml(String id, String type, SQLXML sqlxml) {
SimpleStrolchElementListener listener = new SimpleStrolchElementListener();
try (InputStream binaryStream = sqlxml.getBinaryStream()) {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(binaryStream, new XmlModelSaxReader(listener));
getSaxParser().parse(binaryStream, new XmlModelSaxReader(listener));
} catch (SQLException | IOException | SAXException | ParserConfigurationException e) {
throw new StrolchPersistenceException(
MessageFormat.format("Failed to extract Resource from sqlxml value for {0} / {1}", id, type), e);
@ -125,9 +129,9 @@ public class PostgreSqlResourceDao extends PostgresqlDao<Resource> implements Re
}
} catch (SQLException | SAXException e) {
throw new StrolchPersistenceException(MessageFormat
.format("Failed to insert Resource {0} due to {1}", resource.getLocator(), e.getLocalizedMessage()),
e);
throw new StrolchPersistenceException(
MessageFormat.format("Failed to insert Resource {0} due to {1}", resource.getLocator(),
e.getLocalizedMessage()), e);
}
if (resource.getVersion().isFirstVersion()) {
@ -145,15 +149,16 @@ public class PostgreSqlResourceDao extends PostgresqlDao<Resource> implements Re
int modCount = preparedStatement.executeUpdate();
if (modCount != 1) {
String msg = "Expected to update 1 previous element with id {0} and version {1} but SQL statement modified {2} elements!";
String msg
= "Expected to update 1 previous element with id {0} and version {1} but SQL statement modified {2} elements!";
msg = MessageFormat.format(msg, resource.getId(), resource.getVersion().getPreviousVersion(), modCount);
throw new StrolchPersistenceException(msg);
}
} catch (SQLException e) {
throw new StrolchPersistenceException(MessageFormat
.format("Failed to insert Resource {0} due to {1}", resource.getLocator(), e.getLocalizedMessage()),
e);
throw new StrolchPersistenceException(
MessageFormat.format("Failed to insert Resource {0} due to {1}", resource.getLocator(),
e.getLocalizedMessage()), e);
}
}
@ -168,15 +173,15 @@ public class PostgreSqlResourceDao extends PostgresqlDao<Resource> implements Re
// make sure is first version when versioning is not enabled
if (!resource.getVersion().isFirstVersion()) {
throw new StrolchPersistenceException(MessageFormat
.format("Versioning is not enabled, so version must always be 0 to perform an update, but it is {0}",
resource.getVersion()));
throw new StrolchPersistenceException(MessageFormat.format(
"Versioning is not enabled, so version must always be 0 to perform an update, but it is {0}",
resource.getVersion()));
}
// and also not marked as deleted!
if (resource.getVersion().isDeleted()) {
throw new StrolchPersistenceException(MessageFormat
.format("Versioning is not enabled, so version can not be marked as deleted for {0}",
throw new StrolchPersistenceException(
MessageFormat.format("Versioning is not enabled, so version can not be marked as deleted for {0}",
resource.getVersion()));
}
@ -208,7 +213,8 @@ public class PostgreSqlResourceDao extends PostgresqlDao<Resource> implements Re
try {
int modCount = preparedStatement.executeUpdate();
if (modCount != 1) {
String msg = "Expected to update 1 element with id {0} and version {1} but SQL statement modified {2} elements!";
String msg
= "Expected to update 1 element with id {0} and version {1} but SQL statement modified {2} elements!";
msg = MessageFormat.format(msg, resource.getId(), resource.getVersion().getVersion(), modCount);
throw new StrolchPersistenceException(msg);
}
@ -218,9 +224,9 @@ public class PostgreSqlResourceDao extends PostgresqlDao<Resource> implements Re
}
} catch (SQLException | SAXException e) {
throw new StrolchPersistenceException(MessageFormat
.format("Failed to update Resource {0} due to {1}", resource.getLocator(), e.getLocalizedMessage()),
e);
throw new StrolchPersistenceException(
MessageFormat.format("Failed to update Resource {0} due to {1}", resource.getLocator(),
e.getLocalizedMessage()), e);
}
}
}

View File

@ -16,10 +16,11 @@
package li.strolch.utils.helper;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.text.MessageFormat;
import static li.strolch.utils.helper.XmlHelper.getDocumentBuilder;
/**
* @author Robert von Burg &lt;eitch@eitchnet.ch&gt;
*/
@ -27,8 +28,7 @@ public class DomUtil {
public static DocumentBuilder createDocumentBuilder() {
try {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
return dbfac.newDocumentBuilder();
return getDocumentBuilder();
} catch (ParserConfigurationException e) {
String msg = "No Xml Parser could be loaded: {0}";
msg = MessageFormat.format(msg, e.getMessage());

View File

@ -1,5 +1,13 @@
package li.strolch.utils.helper;
import li.strolch.utils.dbc.DBC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
@ -22,13 +30,7 @@ import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.*;
import li.strolch.utils.dbc.DBC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import static li.strolch.utils.helper.XmlHelper.getDocumentBuilderFactory;
public class XmlDomSigner {
@ -230,7 +232,7 @@ public class XmlDomSigner {
Document doc;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory dbf = getDocumentBuilderFactory();
dbf.setNamespaceAware(true);
doc = dbf.newDocumentBuilder().parse(in);
} catch (Exception e) {

View File

@ -28,6 +28,8 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.*;
@ -94,14 +96,9 @@ public class XmlHelper {
* @param xmlFileInputStream the XML {@link InputStream} which is to be parsed
*/
public static void parseDocument(InputStream xmlFileInputStream, DefaultHandler xmlHandler) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
SAXParser sp = getSaxParser();
sp.parse(xmlFileInputStream, xmlHandler);
} catch (ParserConfigurationException e) {
throw new XmlException("Failed to initialize a SAX Parser: " + e.getMessage(), e);
} catch (SAXException e) {
@ -111,6 +108,29 @@ public class XmlHelper {
}
}
public static SAXParser getSaxParser() throws SAXException, ParserConfigurationException {
SAXParserFactory factory = getSaxParserFactory();
return factory.newSAXParser();
}
public static SAXParserFactory getSaxParserFactory()
throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
return factory;
}
public static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
DocumentBuilderFactory dbf = getDocumentBuilderFactory();
return dbf.newDocumentBuilder();
}
public static DocumentBuilderFactory getDocumentBuilderFactory() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
return factory;
}
/**
* Parses an XML file on the file system and returns the resulting {@link Document} object
*
@ -130,7 +150,7 @@ public class XmlHelper {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParserFactory spf = getSaxParserFactory();
if (nsAware)
spf.setNamespaceAware(true);
@ -306,12 +326,7 @@ public class XmlHelper {
*/
public static Document createDocument() throws RuntimeException {
try {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
return docBuilder.newDocument();
return getDocumentBuilder().newDocument();
} catch (DOMException | ParserConfigurationException e) {
throw new XmlException("Failed to create Document: " + e.getLocalizedMessage(), e);
}
@ -333,18 +348,12 @@ public class XmlHelper {
public static void marshall(File dstFile, Object object) throws Exception {
try (FileOutputStream out = new FileOutputStream(dstFile)) {
JAXBContext jc = JAXBContext.newInstance(object.getClass());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
Document document = getDocumentBuilder().newDocument();
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(object, document);
writeDocument(document, out);
out.flush();
}

View File

@ -1,6 +1,10 @@
package li.strolch.utils.helper;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.parsers.DocumentBuilder;
@ -11,11 +15,8 @@ import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import org.junit.BeforeClass;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import static li.strolch.utils.helper.XmlHelper.getDocumentBuilderFactory;
import static org.junit.Assert.assertEquals;
public class XmlSignHelperTest {
@ -124,10 +125,10 @@ public class XmlSignHelperTest {
issueInstant.add(Calendar.SECOND, 10);
String notOnOrAfterS = simpleDf.format(issueInstant.getTime());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder docBuilder;
try {
DocumentBuilderFactory dbf = getDocumentBuilderFactory();
dbf.setNamespaceAware(true);
docBuilder = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException("Failed to configure document builder!", e);
@ -168,10 +169,10 @@ public class XmlSignHelperTest {
issueInstant.add(Calendar.SECOND, 10);
String notOnOrAfterS = simpleDf.format(issueInstant.getTime());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder docBuilder;
try {
DocumentBuilderFactory dbf = getDocumentBuilderFactory();
dbf.setNamespaceAware(true);
docBuilder = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException("Failed to configure document builder!", e);

View File

@ -57,8 +57,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.File;
@ -79,6 +77,7 @@ import static li.strolch.runtime.StrolchConstants.StrolchPrivilegeConstants.PRIV
import static li.strolch.search.SearchBuilder.orderBy;
import static li.strolch.utils.helper.ExceptionHelper.getCallerMethod;
import static li.strolch.utils.helper.ExceptionHelper.getCallerMethodNoClass;
import static li.strolch.utils.helper.XmlHelper.getSaxParser;
/**
* The RESTful inspector for Strolch. It allows to inspect the realms, and their respective elements. Supporting
@ -210,8 +209,10 @@ public class InspectorResource {
};
String fileName = "strolch_export_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
return Response
.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
}
@GET
@ -336,8 +337,10 @@ public class InspectorResource {
};
String fileName = "strolch_export_resources_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
return Response
.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
}
@GET
@ -363,8 +366,10 @@ public class InspectorResource {
};
String fileName = "strolch_export_orders_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
return Response
.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
}
@GET
@ -390,8 +395,10 @@ public class InspectorResource {
};
String fileName = "strolch_export_activities_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
return Response
.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
}
@GET
@ -562,8 +569,10 @@ public class InspectorResource {
};
String fileName = "strolch_export_resources_" + type + "_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
return Response
.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
}
@GET
@ -595,8 +604,10 @@ public class InspectorResource {
};
String fileName = "strolch_export_orders_" + type + "_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
return Response
.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
}
@GET
@ -628,8 +639,10 @@ public class InspectorResource {
};
String fileName = "strolch_export_activities_" + type + "_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
return Response
.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
}
@GET
@ -1423,15 +1436,16 @@ public class InspectorResource {
Resource resource;
try {
SimpleStrolchElementListener listener = new SimpleStrolchElementListener();
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new InputSource(new StringReader(data)), new XmlModelSaxReader(listener));
getSaxParser().parse(new InputSource(new StringReader(data)), new XmlModelSaxReader(listener));
if (listener.getResources().size() == 0)
throw new StrolchPersistenceException("No Resource parsed from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""));
if (listener.getResources().isEmpty())
throw new StrolchPersistenceException(
"No Resource parsed from xml value" + (StringHelper.isNotEmpty(type) ? " for type " + type :
""));
if (listener.getResources().size() > 1)
throw new StrolchPersistenceException("Multiple Resources parsed from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""));
throw new StrolchPersistenceException(
"Multiple Resources parsed from xml value" + (StringHelper.isNotEmpty(type) ?
" for type " + type : ""));
resource = listener.getResources().get(0);
resource.setVersion(null);
@ -1439,8 +1453,9 @@ public class InspectorResource {
DBC.INTERIM.assertEquals("Posted type must be same as request!", type, resource.getType());
} catch (Exception e) {
throw new StrolchPersistenceException("Failed to extract Resource from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""), e);
throw new StrolchPersistenceException(
"Failed to extract Resource from xml value" + (StringHelper.isNotEmpty(type) ? " for type " + type :
""), e);
}
return resource;
}
@ -1449,15 +1464,15 @@ public class InspectorResource {
Order order;
try {
SimpleStrolchElementListener listener = new SimpleStrolchElementListener();
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new InputSource(new StringReader(data)), new XmlModelSaxReader(listener));
getSaxParser().parse(new InputSource(new StringReader(data)), new XmlModelSaxReader(listener));
if (listener.getOrders().size() == 0)
if (listener.getOrders().isEmpty())
throw new StrolchPersistenceException(
"No Order parsed from xml value" + (StringHelper.isNotEmpty(type) ? " for type " + type : ""));
if (listener.getOrders().size() > 1)
throw new StrolchPersistenceException("Multiple Orders parsed from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""));
throw new StrolchPersistenceException(
"Multiple Orders parsed from xml value" + (StringHelper.isNotEmpty(type) ? " for type " + type :
""));
order = listener.getOrders().get(0);
order.setVersion(null);
@ -1465,8 +1480,9 @@ public class InspectorResource {
DBC.INTERIM.assertEquals("Posted type must be same as request!", type, order.getType());
} catch (Exception e) {
throw new StrolchPersistenceException("Failed to extract Order from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""), e);
throw new StrolchPersistenceException(
"Failed to extract Order from xml value" + (StringHelper.isNotEmpty(type) ? " for type " + type :
""), e);
}
return order;
}
@ -1475,15 +1491,16 @@ public class InspectorResource {
Activity activity;
try {
SimpleStrolchElementListener listener = new SimpleStrolchElementListener();
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new InputSource(new StringReader(data)), new XmlModelSaxReader(listener));
getSaxParser().parse(new InputSource(new StringReader(data)), new XmlModelSaxReader(listener));
if (listener.getActivities().size() == 0)
throw new StrolchPersistenceException("No Activity parsed from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""));
if (listener.getActivities().isEmpty())
throw new StrolchPersistenceException(
"No Activity parsed from xml value" + (StringHelper.isNotEmpty(type) ? " for type " + type :
""));
if (listener.getActivities().size() > 1)
throw new StrolchPersistenceException("Multiple Activities parsed from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""));
throw new StrolchPersistenceException(
"Multiple Activities parsed from xml value" + (StringHelper.isNotEmpty(type) ?
" for type " + type : ""));
activity = listener.getActivities().get(0);
activity.setVersion(null);
@ -1491,8 +1508,9 @@ public class InspectorResource {
DBC.INTERIM.assertEquals("Posted type must be same as request!", type, activity.getType());
} catch (Exception e) {
throw new StrolchPersistenceException("Failed to extract Activity from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""), e);
throw new StrolchPersistenceException(
"Failed to extract Activity from xml value" + (StringHelper.isNotEmpty(type) ? " for type " + type :
""), e);
}
return activity;
}

View File

@ -15,20 +15,6 @@
*/
package li.strolch.xmlpers.api;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.text.MessageFormat;
import javanet.staxutils.IndentingXMLStreamWriter;
import li.strolch.utils.exceptions.XmlException;
import li.strolch.utils.helper.StringHelper;
@ -40,6 +26,21 @@ import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.text.MessageFormat;
import static li.strolch.utils.helper.XmlHelper.PROP_LINE_SEPARATOR;
import static li.strolch.utils.helper.XmlHelper.getSaxParser;
public class FileIo {
public static final String DEFAULT_XML_VERSION = "1.0";
@ -103,12 +104,9 @@ public class FileIo {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
SaxParser<T> saxParser = ctx.getParserFactor().getSaxParser();
DefaultHandler defaultHandler = saxParser.getDefaultHandler();
sp.parse(this.path, defaultHandler);
getSaxParser().parse(this.path, defaultHandler);
if (logger.isDebugEnabled()) {
String msg = "SAX parsed file {0}";
@ -127,7 +125,7 @@ public class FileIo {
public <T> void writeDom(PersistenceContext<T> ctx) {
String lineSep = System.getProperty(XmlHelper.PROP_LINE_SEPARATOR);
String lineSep = System.getProperty(PROP_LINE_SEPARATOR);
try {
@ -142,7 +140,7 @@ public class FileIo {
if (!lineSep.equals(StringHelper.NEW_LINE)) {
logger.info("Overriding line separator to \\n");
System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, StringHelper.NEW_LINE);
System.setProperty(PROP_LINE_SEPARATOR, StringHelper.NEW_LINE);
}
// Set up a transformer
@ -176,7 +174,7 @@ public class FileIo {
throw new XmlException(msg, e);
} finally {
System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, lineSep);
System.setProperty(PROP_LINE_SEPARATOR, lineSep);
}
}

View File

@ -15,12 +15,13 @@
*/
package li.strolch.xmlpers.util;
import li.strolch.xmlpers.api.XmlPersistenceException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.text.MessageFormat;
import li.strolch.xmlpers.api.XmlPersistenceException;
import static li.strolch.utils.helper.XmlHelper.getDocumentBuilder;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -29,8 +30,7 @@ public class DomUtil {
public static DocumentBuilder createDocumentBuilder() {
try {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
return dbfac.newDocumentBuilder();
return getDocumentBuilder();
} catch (ParserConfigurationException e) {
String msg = "No Xml Parser could be loaded: {0}";
msg = MessageFormat.format(msg, e.getMessage());

View File

@ -15,23 +15,6 @@
*/
package li.strolch.xmlpers.test;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import javanet.staxutils.IndentingXMLStreamWriter;
import li.strolch.utils.exceptions.XmlException;
import li.strolch.utils.helper.XmlHelper;
@ -46,6 +29,22 @@ import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import static li.strolch.utils.helper.XmlHelper.getDocumentBuilder;
import static li.strolch.utils.helper.XmlHelper.getSaxParser;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@ -72,9 +71,7 @@ public class XmlTestMain {
private static List<MyModel> readDom() throws Exception {
File file = new File("target/res_dom.xml");
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document document = docBuilder.parse(file);
Document document = getDocumentBuilder().parse(file);
Element rootElement = document.getDocumentElement();
List<MyModel> resources = new ArrayList<>();
@ -131,34 +128,32 @@ public class XmlTestMain {
public void startElement(String uri, String localName, String qName, Attributes attributes) {
switch (qName) {
case "Resource":
MyModel res = new MyModel();
res.setId(attributes.getValue("id"));
res.setName(attributes.getValue("name"));
res.setType(attributes.getValue("type"));
currentRes[0] = res;
resources.add(res);
break;
case "Parameter":
MyParameter param = new MyParameter();
param.setId(attributes.getValue("id"));
param.setName(attributes.getValue("name"));
param.setType(attributes.getValue("type"));
param.setValue(attributes.getValue("value"));
currentRes[0].addParameter(param);
break;
case "model":
break;
default:
throw new IllegalArgumentException("The element '" + qName + "' is unhandled!");
case "Resource":
MyModel res = new MyModel();
res.setId(attributes.getValue("id"));
res.setName(attributes.getValue("name"));
res.setType(attributes.getValue("type"));
currentRes[0] = res;
resources.add(res);
break;
case "Parameter":
MyParameter param = new MyParameter();
param.setId(attributes.getValue("id"));
param.setName(attributes.getValue("name"));
param.setType(attributes.getValue("type"));
param.setValue(attributes.getValue("value"));
currentRes[0].addParameter(param);
break;
case "model":
break;
default:
throw new IllegalArgumentException("The element '" + qName + "' is unhandled!");
}
}
};
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
File file = new File("target/res_sax.xml");
sp.parse(file, xmlHandler);
getSaxParser().parse(file, xmlHandler);
logger.info("SAX parsed file " + file.getAbsolutePath());
@ -167,9 +162,7 @@ public class XmlTestMain {
private static void writeDom(MyModel res) throws Exception {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Document doc = getDocumentBuilder().newDocument();
Element resElement = doc.createElement("Resource");
resElement.setAttribute("id", res.getId());