Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
net.sf.xolite.Attributes Maven / Gradle / Ivy
Go to download
This project provides a lightweight framework to
serialize/deserialize (or marshall/unmarshall) java objects into
XML. The implementation is based on standard SAX (Simple Api for
Xml) but it follows a original approach based on the strong data
encapsulation paradigm of Object Oriented (OO)
programming.
/*-------------------------------------------------------------------------
Copyright 2006 Olivier Berlanger
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------------*/
package net.sf.xolite;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A helper class to get formatted value out of XML element attributes.
* Note: this helper assume that attributes have no namespace (as it is usually the case). For the rare case where there is an
* attribute with namespace that has not a simple string value, you should get it directly from the XMLEventParser interface and
* interpret it with ad-hoc code.
*
* @author Olivier Berlanger
*/
public class Attributes {
private static Log log = LogFactory.getLog(Attributes.class);
private static ThreadLocal> threadDateFormats;
public static String getString(String attrName, String defaultValue, XMLEventParser parser) throws XMLParseException {
return getString(attrName, defaultValue, false, parser);
}
public static String getMandatoryString(String attrName, XMLEventParser parser) throws XMLParseException {
return getString(attrName, null, true, parser);
}
public static int getInt(String attrName, int defaultValue, XMLEventParser parser) throws XMLParseException {
return getInt(attrName, defaultValue, false, parser);
}
public static int getMandatoryInt(String attrName, XMLEventParser parser) throws XMLParseException {
return getInt(attrName, 0, true, parser);
}
public static > T getEnum(String attrName, T defaultValue, Class enumType, XMLEventParser parser)
throws XMLParseException {
return getEnum(attrName, defaultValue, enumType, parser, false);
}
public static > T getMandatoryEnum(String attrName, Class enumType, XMLEventParser parser)
throws XMLParseException {
return getEnum(attrName, null, enumType, parser, true);
}
public static double getDouble(String attrName, double defaultValue, XMLEventParser parser) throws XMLParseException {
return getDouble(attrName, defaultValue, false, parser);
}
public static double getMandatoryDouble(String attrName, XMLEventParser parser) throws XMLParseException {
return getDouble(attrName, 0, true, parser);
}
public static int[] getIntArray(String attrName, int[] defaultValue, XMLEventParser parser) throws XMLParseException {
return getIntArray(attrName, defaultValue, false, parser);
}
public static int[] getMandatoryIntArray(String attrName, XMLEventParser parser) throws XMLParseException {
return getIntArray(attrName, null, true, parser);
}
public static List getStringList(String attrName, String separator, XMLEventParser parser) throws XMLParseException {
return getStringList(attrName, separator, false, parser);
}
public static List getMandatoryStringList(String attrName, String separator, XMLEventParser parser)
throws XMLParseException {
return getStringList(attrName, separator, true, parser);
}
public static long getLong(String attrName, long defaultValue, XMLEventParser parser) throws XMLParseException {
return getLong(attrName, defaultValue, false, parser);
}
public static long getMandatoryLong(String attrName, XMLEventParser parser) throws XMLParseException {
return getLong(attrName, 0, true, parser);
}
public static boolean getBoolean(String attrName, boolean defaultValue, XMLEventParser parser) throws XMLParseException {
return getBoolean(attrName, defaultValue, false, parser);
}
public static boolean getMandatoryBoolean(String attrName, XMLEventParser parser) throws XMLParseException {
return getBoolean(attrName, false, true, parser);
}
public static Point getPoint(String attrName, Point defaultValue, XMLEventParser parser) throws XMLParseException {
return getPoint(attrName, defaultValue, false, parser);
}
public static Point getMandatoryPoint(String attrName, XMLEventParser parser) throws XMLParseException {
return getPoint(attrName, null, true, parser);
}
public static Dimension getDimension(String attrName, Dimension defaultValue, XMLEventParser parser)
throws XMLParseException {
return getDimension(attrName, defaultValue, false, parser);
}
public static Dimension getMandatoryDimension(String attrName, XMLEventParser parser) throws XMLParseException {
return getDimension(attrName, null, true, parser);
}
public static Rectangle getRectangle(String attrName, Rectangle defaultValue, XMLEventParser parser)
throws XMLParseException {
return getRectangle(attrName, defaultValue, false, parser);
}
public static Rectangle getMandatoryRectangle(String attrName, XMLEventParser parser) throws XMLParseException {
return getRectangle(attrName, null, true, parser);
}
public static Date getDate(String attrName, String pattern, Date defaultValue, XMLEventParser parser)
throws XMLParseException {
return getDate(attrName, pattern, defaultValue, false, parser);
}
public static Date getMandatoryDate(String attrName, String pattern, XMLEventParser parser) throws XMLParseException {
return getDate(attrName, pattern, null, true, parser);
}
// -------------------- Helper method for serialization ------------------------------------------------------------
public static final String intArrayToString(int[] values) {
if (values == null) return "";
StringBuffer sb = new StringBuffer();
int len = values.length;
for (int i = 0; i < len; i++) {
if (i > 0) sb.append(',');
sb.append(values[i]);
}
return sb.toString();
}
public static final String objectArrayToString(Object[] values) {
return iterableToString((values == null) ? null : Arrays.asList(values), ",", ";");
}
public static final String objectArrayToString(Object[] values, String separator, String replacement) {
return iterableToString((values == null) ? null : Arrays.asList(values), separator, replacement);
}
public static final String listToString(List extends Object> lst, String separator, String replacement) {
return iterableToString(lst, separator, replacement);
}
public static final String iterableToString(Iterable extends Object> iterabl, String separator, String replacement) {
String result = "";
if (iterabl != null) {
Iterator extends Object> it = iterabl.iterator();
if (it.hasNext()) {
StringBuffer sb = new StringBuffer();
sb.append(getNormalizedString(it.next(), separator, replacement));
while (it.hasNext()) {
sb.append(separator);
sb.append(getNormalizedString(it.next(), separator, replacement));
}
result = sb.toString();
}
}
return result;
}
public static final String pointToString(Point pt) {
String result = "";
if (pt != null) {
StringBuffer sb = new StringBuffer();
sb.append(pt.x);
sb.append(',');
sb.append(pt.y);
result = sb.toString();
}
return result;
}
public static final String dimensionToString(Dimension dim) {
String result = "";
if (dim != null) {
StringBuffer sb = new StringBuffer();
sb.append(dim.width);
sb.append(',');
sb.append(dim.height);
result = sb.toString();
}
return result;
}
public static final String rectangleToString(Rectangle rect) {
String result = "";
if (rect != null) {
StringBuffer sb = new StringBuffer();
sb.append(rect.x);
sb.append(',');
sb.append(rect.y);
sb.append(',');
sb.append(rect.width);
sb.append(',');
sb.append(rect.height);
result = sb.toString();
}
return result;
}
public static final String dateToString(Date dat, String pattern) {
String result = "";
if (dat != null) {
DateFormat fmt = getDateFormat(pattern);
result = fmt.format(dat);
}
return result;
}
private static String getNormalizedString(Object value, String separator, String replacement) {
String valueString = (value == null) ? "null" : value.toString();
if (valueString.indexOf(separator) >= 0) {
log.warn("The string serialized into XML list <" + valueString + "> contains the list separator: '" + separator
+ "', will be replaced by '" + replacement + "'");
valueString = valueString.replace(separator, replacement);
}
return valueString;
}
// ----------------------- Implementation ---------------------------------------------------------
protected static String getAttributeRawValue(String attrName, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
String attrVal = parser.getAttributeValue(attrName);
if ((attrVal == null) || (attrVal.length() == 0)) {
if (mandatory) {
parser.throwParseException("Attribute '" + attrName + "' is mandatory", null);
}
attrVal = null;
}
return attrVal;
}
protected static String getString(String attrName, String defaultValue, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal == null) attrVal = defaultValue;
return attrVal;
}
protected static boolean getBoolean(String attrName, boolean defaultValue, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
boolean result = defaultValue;
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal != null) {
result = stringToBoolean(attrVal);
}
return result;
}
protected static int getInt(String attrName, int defaultValue, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
int result = defaultValue;
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal != null) {
try {
result = Integer.parseInt(attrVal);
} catch (Exception e) {
parser.throwParseException("Attribute " + attrName + "='" + attrVal + "' must have an Integer value.", e);
}
}
return result;
}
protected static > T getEnum(String attrName, T defaultValue, Class enumType, XMLEventParser parser,
boolean mandatory) throws XMLParseException {
T result = defaultValue;
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal != null) {
try {
result = Enum.valueOf(enumType, attrVal);
} catch (Exception e) {
parser.throwParseException("Attribute " + attrName + "='" + attrVal + "' must be a enum value of type "
+ enumType, e);
}
}
return result;
}
protected static double getDouble(String attrName, double defaultValue, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
double result = defaultValue;
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal != null) {
try {
result = Double.parseDouble(attrVal);
} catch (Exception e) {
parser.throwParseException("Attribute " + attrName + "='" + attrVal + "' must have an Double value.", e);
}
}
return result;
}
protected static int[] getIntArray(String attrName, int[] defaultValue, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
int[] result = defaultValue;
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal != null) {
try {
result = stringToIntArray(attrVal);
} catch (Exception e) {
parser.throwParseException("Attribute " + attrName + "='" + attrVal
+ "' must be a coma-separated list of integers", e);
}
}
return result;
}
protected static Dimension getDimension(String attrName, Dimension defaultValue, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
Dimension result = defaultValue;
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal != null) {
try {
int[] vals = stringToIntArray(attrVal);
if (vals.length != 2) {
throw new IllegalArgumentException("Bad dimension value --> it should be 2 integers, not " + vals.length);
}
result = new Dimension(vals[0], vals[1]);
} catch (Exception e) {
parser.throwParseException("Attribute " + attrName + "='" + attrVal
+ "' must be a Dimension (coma-separated list of 2 integers)", e);
}
}
return result;
}
protected static Point getPoint(String attrName, Point defaultValue, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
Point result = defaultValue;
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal != null) {
try {
int[] vals = stringToIntArray(attrVal);
if (vals.length != 2) {
throw new IllegalArgumentException("Bad point value --> it should be 2 integers, not " + vals.length);
}
result = new Point(vals[0], vals[1]);
} catch (Exception e) {
parser.throwParseException("Attribute " + attrName + "='" + attrVal
+ "' must be a Point (coma-separated list of 2 integers)", e);
}
}
return result;
}
protected static Rectangle getRectangle(String attrName, Rectangle defaultValue, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
Rectangle result = defaultValue;
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal != null) {
try {
int[] vals = stringToIntArray(attrVal);
if (vals.length != 4) {
throw new IllegalArgumentException("Bad rectangle value --> it should be 4 integers, not " + vals.length);
}
result = new Rectangle(vals[0], vals[1], vals[2], vals[3]);
} catch (Exception e) {
parser.throwParseException("Attribute " + attrName + "='" + attrVal
+ "' must be a Rectangle (coma-separated list of 4 integers)", e);
}
}
return result;
}
protected static Date getDate(String attrName, String pattern, Date defaultValue, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
Date result = defaultValue;
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal != null) {
try {
DateFormat fmt = getDateFormat(pattern);
result = fmt.parse(attrVal);
} catch (Exception e) {
parser.throwParseException("Attribute " + attrName + "='" + attrVal + "' must be a Date with pattern ["
+ pattern + "]", e);
}
}
return result;
}
/**
* Method sharing the DateFormat used for parsing/formatting but ensuring that they are shared across threads (because they
* are not thread-safe).
*/
protected static DateFormat getDateFormat(String pattern) {
Map dateFormats = null;
synchronized (Attributes.class) {
if (threadDateFormats == null) threadDateFormats = new ThreadLocal>();
dateFormats = threadDateFormats.get();
if (dateFormats == null) {
dateFormats = new HashMap();
threadDateFormats.set(dateFormats);
}
}
DateFormat fmt = dateFormats.get(pattern);
if (fmt == null) {
fmt = new SimpleDateFormat(pattern);
dateFormats.put(pattern, fmt);
}
return fmt;
}
/**
* Warning: This method return an unmodifiable list (not an instance of the usual ArrayList implementation).
*
* @param attrName
* The name of the attribute holding the list data in the current element of the parser.
* @param separator
* The separator regular expression (see String.split(..))
* @param mandatory
* Flag saying if this attribute is mandatory in its XML element.
* @param parser
* The XML parser
* @return The content of the attribute as a list of string.
* @throws XMLParseException
* if attribute is mandatory and not present or if parsing failed.
*/
protected static List getStringList(String attrName, String separator, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
List result = null;
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal != null) {
try {
result = stringToStringList(attrVal, separator);
} catch (Exception e) {
parser.throwParseException("Attribute " + attrName + "='" + attrVal
+ "' must be a coma-separated list of integers", e);
}
}
return result;
}
protected static long getLong(String attrName, long defaultValue, boolean mandatory, XMLEventParser parser)
throws XMLParseException {
long result = defaultValue;
String attrVal = getAttributeRawValue(attrName, mandatory, parser);
if (attrVal != null) {
try {
result = Long.parseLong(attrVal);
} catch (Exception e) {
parser.throwParseException("Attribute " + attrName + "='" + attrVal + "' must have an Long value.", e);
}
}
return result;
}
static final String trim(String str) {
return (str == null) ? null : str.trim();
}
static final boolean isEmpty(String src) {
if (src == null) return true;
int len = src.length();
for (int i = 0; i < len; i++) {
if (src.charAt(i) > 32) return false;
}
return true;
}
// ----------------- conversion methods String to Object -------------------------------------------------------
public static final boolean stringToBoolean(String value) {
if ((value == null) || (value.length() == 0)) return false;
char ch = value.charAt(0);
return ((ch == 'T') || (ch == 't') || (ch == '1'));
}
public static final int[] stringToIntArray(String value) {
if ((value == null) || (value.length() == 0)) return null;
String[] tokens = value.split(",");
int len = tokens.length;
int[] result = new int[len];
for (int i = 0; i < len; i++) {
result[i] = Integer.parseInt(tokens[i]);
}
return result;
}
/**
* Warning: This method return an unmodifiable list (not an instance of the usual ArrayList implementation).
*
* @param src
* The string to transform to a List.
* @param separator
* The list items separator.
* @return The content of the given string as a List.
*/
public static final List stringToStringList(String src, String separator) {
List result;
if ((src != null) && (src.length() > 0)) {
String[] splitted = src.split(separator);
result = Arrays.asList(splitted);
} else {
result = Collections.emptyList();
}
return result;
}
public static final String stringListToString(List list, String separator) {
StringBuilder sb = new StringBuilder();
int len = (list == null) ? 0 : list.size();
for (int i = 0; i < len; i++) {
if (i > 0) sb.append(separator);
sb.append(list.get(i));
}
return sb.toString();
}
public static final Date stringToDate(String src, String pattern) throws ParseException {
Date result = null;
if ((src != null) && (src.length() > 0)) {
DateFormat fmt = getDateFormat(pattern);
result = fmt.parse(src);
}
return result;
}
}