diff --git a/base-lib/pom.xml b/base-lib/pom.xml index e30c4cd1bc..9094066dab 100644 --- a/base-lib/pom.xml +++ b/base-lib/pom.xml @@ -551,18 +551,6 @@ json - - - org.apache.velocity - velocity - 1.6.4 - - - org.apache.velocity - velocity-tools - 1.4 - - org.incava diff --git a/base-lib/src/main/java/com/gentics/api/portalnode/imp/AbstractGenticsImp.java b/base-lib/src/main/java/com/gentics/api/portalnode/imp/AbstractGenticsImp.java deleted file mode 100644 index eb1cf1fd2a..0000000000 --- a/base-lib/src/main/java/com/gentics/api/portalnode/imp/AbstractGenticsImp.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * @author stefan - * @date Mar 8, 2006 - * @version $Id$ - */ -package com.gentics.api.portalnode.imp; - -import java.util.Map; - -import com.gentics.lib.log.NodeLogger; - -/** - * Abstract implementation for imps. - * This abstract class implements some common functions for imps. - */ -public abstract class AbstractGenticsImp implements GenticsImpInterface { - - private String impId; - - /** - * logger - */ - protected NodeLogger logger = NodeLogger.getNodeLogger(getClass()); - - protected AbstractGenticsImp() {} - - public String getImpId() { - return impId; - } - - public void init(String impId, Map parameters) throws ImpException { - this.impId = impId; - } - -} diff --git a/base-lib/src/main/java/com/gentics/api/portalnode/imp/GenticsImpInterface.java b/base-lib/src/main/java/com/gentics/api/portalnode/imp/GenticsImpInterface.java deleted file mode 100644 index efff579738..0000000000 --- a/base-lib/src/main/java/com/gentics/api/portalnode/imp/GenticsImpInterface.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * @author norbert - * @date 21.04.2005 - * @version $Id: GenticsImpInterface.java,v 1.2 2006-03-14 15:19:00 stefan Exp $ - * @gentics.sdk - */ -package com.gentics.api.portalnode.imp; - -import java.util.Map; - -/** - * interface for small imps that are available in dungeons, modules, templates, - * ... - * If the imp stores any private data which is not threadsafe (i.e. can be - * modified while using the imp), the com.gentics.api.portalnode.imp.GenticsStatefulImpInterface - * must be used. - * - * @author norbert - */ -public interface GenticsImpInterface { - - /** - * initialize the imp with the parameters defined in the <parameters> - * tag of the imp. Init is called before any other parameters are set - * and is called only once when the imp is created, not when the imp is reused. - * - * @param impId the configured id of the imp, must be returned by {@link #getImpId()} - * @param parameters configuration of the imp - * @throws ImpException if errors occured - */ - void init(String impId, Map parameters) throws ImpException; - - /** - * get the id of the imp by which it has been initialized. - * @return the id if this configured imp. - */ - String getImpId(); -} diff --git a/base-lib/src/main/java/com/gentics/api/portalnode/imp/ImpException.java b/base-lib/src/main/java/com/gentics/api/portalnode/imp/ImpException.java deleted file mode 100644 index d39d8a22c7..0000000000 --- a/base-lib/src/main/java/com/gentics/api/portalnode/imp/ImpException.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * @author marius.toader - * @date 21.02.2005 - * @version $Id: ImpException.java,v 1.1 2006-01-23 16:40:51 norbert Exp $ - * @gentics.sdk - */ -package com.gentics.api.portalnode.imp; - -/** - * Exception that might be thrown by imps. - */ -public class ImpException extends Exception { - - /** - * Create instance of the exception - */ - public ImpException() { - super(); - } - - /** - * Create instance of the exception with a message - * @param message - the message that will be displayed - */ - public ImpException(String message) { - super(message); - } -} diff --git a/base-lib/src/main/java/com/gentics/lib/formatter/GenericGenticsDateFormatter.java b/base-lib/src/main/java/com/gentics/lib/formatter/GenericGenticsDateFormatter.java deleted file mode 100644 index 3c11e1a67f..0000000000 --- a/base-lib/src/main/java/com/gentics/lib/formatter/GenericGenticsDateFormatter.java +++ /dev/null @@ -1,583 +0,0 @@ -package com.gentics.lib.formatter; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Map; - -import jakarta.xml.bind.JAXBException; - -import javax.xml.transform.stream.StreamSource; - -import com.gentics.api.lib.etc.ObjectTransformer; -import com.gentics.api.portalnode.imp.AbstractGenticsImp; -import com.gentics.api.portalnode.imp.ImpException; -import com.gentics.lib.etc.StringUtils; -import com.gentics.lib.formatter.dateformatter.DateFormatConfig; -import com.gentics.lib.formatter.dateformatter.JAXBDateFormatType; -import com.gentics.lib.formatter.dateformatter.JAXBDateFormatsType; -import com.gentics.lib.i18n.LanguageProviderFactory; -import com.gentics.lib.jaxb.JAXBHelper; - -/** - * New and better Version if the GenticsDateFormatter. Can be used to format - * dates in Portal.Node and Content.Node - */ -public class GenericGenticsDateFormatter extends AbstractGenticsImp { - - /** - * Default path of the configuration file. - */ - private final static String DEFAULT_CONFIGURATION = "${com.gentics.portalnode.home}/META-INF/config/formatter/dateformatter.xml"; - - /** - * Name of the parameter holding the path to the configuration file - */ - public final static String CONFIGPATH_PARAM = "configuration"; - - /** - * context path of the dateformatter configuration - */ - private final static String CONTEXT_PATH = "com.gentics.lib.formatter.dateformatter"; - - /** - * configured date formats (if any) - */ - protected JAXBDateFormatsType dateFormats; - - /** - * some basic definitions needed for calculations - */ - public static final int MINUTE = 60; - - public static final int HOUR = 60 * MINUTE; - - public static final int DAY = 24 * HOUR; - - public static final int WEEK = 7 * DAY; - - public static final int MONTH = 30 * DAY; - - public static final int YEAR = 365 * DAY; - - /** - * - */ - public GenericGenticsDateFormatter() {} - - /* - * (non-Javadoc) - * @see com.gentics.api.portalnode.imp.AbstractGenticsImp#init(java.lang.String, - * java.util.Map) - */ - public void init(String impId, Map parameters) throws ImpException { - super.init(impId, parameters); - - // get the configured path to the configuration file - String configFilePath = StringUtils.resolveSystemProperties(ObjectTransformer.getString(parameters.get(CONFIGPATH_PARAM), "")); - boolean customConfiguration = true; - - // no path configured, so get the default path - if (StringUtils.isEmpty(configFilePath)) { - configFilePath = StringUtils.resolveSystemProperties(DEFAULT_CONFIGURATION); - customConfiguration = false; - } - - // now try to read and interpret the configuration file - try { - dateFormats = JAXBHelper.unmarshall(CONTEXT_PATH, new StreamSource(new FileInputStream(configFilePath)), JAXBDateFormatsType.class); - } catch (FileNotFoundException e) { - if (customConfiguration) { - logger.error("Could not find the configuration file @ {" + configFilePath + "}. Trying default configuration file."); - configFilePath = StringUtils.resolveSystemProperties(DEFAULT_CONFIGURATION); - customConfiguration = false; - // do fallback to default configuration - try { - dateFormats = JAXBHelper.unmarshall(CONTEXT_PATH, new StreamSource(new FileInputStream(configFilePath)), JAXBDateFormatsType.class); - } catch (FileNotFoundException e1) { - logger.error("Could not find default configuration file @ {" + configFilePath + "}. Only default formats supported."); - } catch (JAXBException e1) { - logger.error("Error while interpreting configuration file @ {" + configFilePath + "}. Only default formats supported.", e1); - } - } else { - logger.error("Could not find the configuration file @ {" + configFilePath + "}. Only default formats supported."); - } - } catch (JAXBException e) { - logger.error("Error while interpreting configuration file @ {" + configFilePath + "}. Only default formats supported.", e); - } - } - - /** - * Format the current date in the given format and the current language - * @param format format - * @return formatted date - */ - public String format(String format) { - return format(new Date(), format, getCurrentLanguageCode()); - } - - /** - * @param format - * @deprecated use {@link #format(String)} instead - * @return - */ - public String formatDate(String format) { - return format(format); - } - - /** - * Format the current date in the given format and language - * @param format format - * @param languageCode language code - * @return formatted date - */ - public String format(String format, String languageCode) { - return format(new Date(), format, languageCode); - } - - /** - * @param format - * @param languageCode - * @deprecated use {@link #format(String, String)} instead - * @return - */ - public String formatDate(String format, String languageCode) { - return format(format, languageCode); - } - - /** - * Format the given date in the default format and current language - * @param date date - * @return formatted date - */ - public String format(Date date) { - return format(date, dateFormats != null ? dateFormats.getDefault() : null, getCurrentLanguageCode()); - } - - /** - * - * @param date - * @param format - * @deprecated use {@link #format(Date, String)} instead - * @return - */ - public String formatDate(Date date, String format) { - return format(date, format); - } - - /** - * Format the given date in the given format and current language - * @param date date - * @param format format - * @return formatted date - */ - public String format(Date date, String format) { - return format(date, format, getCurrentLanguageCode()); - } - - /** - * Format the given date in the given format and language - * @param date date - * @param format format - * @param languageCode language - * @return formatted date - */ - public String format(Date date, String format, String languageCode) { - if (format == null && dateFormats != null) { - format = dateFormats.getDefault(); - } - DateFormatConfig configuredDateFormat = getFormatWithId(format); - - if (configuredDateFormat != null) { - return configuredDateFormat.format(date, languageCode); - } else { - DateFormat dateFormat = DateFormatConfig.createDateTimeFormat(format, DateFormatConfig.getLocale(languageCode)); - - return dateFormat.format(date); - } - } - - /** - * @param date - * @param format - * @param languageCode - * @deprecated use {@link #format(Date, String, String)} instead - * @return - */ - public String formatDate(Date date, String format, String languageCode) { - return format(date, format, languageCode); - } - - /** - * Format the given date in the default format and current language - * @param date date - * @return formatted date - */ - public String format(Object date) { - return format(toDate(date)); - } - - /** - * @param date - * @deprecated use {@link #format(Object)} instead - * @return - */ - public String formatDate(Object date) { - return format(date); - } - - /** - * Format the given date in the given format and current language - * @param date date - * @param format format - * @return formatted date - */ - public String format(Object date, String format) { - return format(toDate(date), format); - } - - /** - * - * @param date - * @param format - * @deprecated use {@link #format(Object, String)} instead - * @return - */ - public String formatDate(Object date, String format) { - return format(date, format); - } - - /** - * Format the given date in the given format and language - * @param date date - * @param format format - * @param languageCode language - * @return formatted date - */ - public String format(Object date, String format, String languageCode) { - return format(toDate(date), format, languageCode); - } - - /** - * - * @param date - * @param format - * @param languageCode - * @deprecated use {@link #format(Object, String, String)} instead - * @return - */ - public String formatDate(Object date, String format, String languageCode) { - return format(date, format, languageCode); - } - - /** - * Format the current date in the default format and current language - * @return formatted date - */ - public String format() { - return format(new Date(), dateFormats != null ? dateFormats.getDefault() : null, getCurrentLanguageCode()); - } - - /** - * @deprecated use {@link #format()} instead - * @return - */ - public String formatDate() { - return format(); - } - - /** - * parse the given string to a date (in the default format) and return the - * date or null if the string is unparseable - * @param formattedDate formatted date to be parsed - * @return date object or null - */ - public Date parse(String formattedDate) { - return parse(formattedDate, null); - } - - /** - * - * @param formattedDate - * @deprecated use {@link #parse(String)} instead - * @return - */ - public Date parseDate(String formattedDate) { - return parse(formattedDate); - } - - /** - * parse the given string to a date in the given format and return the date - * or null if the string is unparseable - * @param formattedDate formatted date to be parsed - * @param dateFormat date format or null for the default format - * @return date object or null - */ - public Date parse(String formattedDate, String dateFormat) { - return parse(formattedDate, dateFormat, getCurrentLanguageCode()); - } - - /** - * - * @param formattedDate - * @param dateFormat - * @deprecated use {@link #parse(String, String))} instead - * @return - */ - public Date parseDate(String formattedDate, String dateFormat) { - return parse(formattedDate, dateFormat); - } - - /** - * Parse the given string to a date in the given format and given - * languagecode - * @param formattedDate formatted date to be parsed - * @param format date format or null for the default format - * @param languageCode language code - * @return date object or null - */ - public Date parse(String formattedDate, String format, String languageCode) { - if (format == null && dateFormats != null) { - format = dateFormats.getDefault(); - } - DateFormatConfig configuredDateFormat = getFormatWithId(format); - - try { - if (configuredDateFormat != null) { - return configuredDateFormat.parse(formattedDate, languageCode); - } else { - DateFormat dateFormat = DateFormatConfig.createDateTimeFormat(format, DateFormatConfig.getLocale(languageCode)); - - return dateFormat.parse(formattedDate); - } - } catch (ParseException e) { - logger.error("Error while parsing {" + formattedDate + "} into a date with format {" + format + "}", e); - return null; - } - } - - /** - * - * @param formattedDate - * @param format - * @param languageCode - * @deprecated use {@link #parse(String, String, String)} instead - * @return - */ - public Date parseDate(String formattedDate, String format, String languageCode) { - return parse(formattedDate, format, languageCode); - } - - /** - * generate a date from a timestamp - * @param timestamp timestamp - * @return date object - */ - public Date fromTimestamp(int timestamp) { - return new Date((long) timestamp * 1000L); - } - - /** - * generate a date from a timestamp - * @param timestamp timestamp (as string) - * @return date object - */ - public Date fromTimestamp(String timestamp) { - try { - return new Date(Long.parseLong(timestamp) * 1000L); - } catch (NumberFormatException ex) { - return null; - } - } - - /** - * check whether the object is a date or not - * @param object object to check - * @return true when the object is a date, false if not - */ - public boolean isDate(Object object) { - return object instanceof Date; - } - - /** - * Calculate the difference between the given dates in the given time unit. - * Possible time units are: - * - * @param fromDate first date (should be earlier) - * @param toDate second date (should be later) - * @param unit the time unit for output of the date difference - * @return difference in the given unit - */ - public long dateDiff(Date fromDate, Date toDate, String unit) { - long msDiff = toDate.getTime() - fromDate.getTime(); - long diff = msDiff; - - if ("y".equals(unit)) { - // difference in years - Calendar toCal = Calendar.getInstance(); - - toCal.setTime(toDate); - Calendar fromCal = Calendar.getInstance(); - - fromCal.setTime(fromDate); - diff = toCal.get(Calendar.YEAR) - fromCal.get(Calendar.YEAR); - // now check whether the to-day is earlier in the year as the - // from-day - toCal.set(Calendar.YEAR, fromCal.get(Calendar.YEAR)); - if (toCal.getTime().before(fromCal.getTime())) { - diff -= 1; - } - } else if ("M".equals(unit)) { - // difference in months - Calendar toCal = Calendar.getInstance(); - - toCal.setTime(toDate); - Calendar fromCal = Calendar.getInstance(); - - fromCal.setTime(fromDate); - diff = (toCal.get(Calendar.YEAR) - fromCal.get(Calendar.YEAR)) * 12; - // now check whether the to-day is earlier in the year as the - // from-day - toCal.set(Calendar.YEAR, fromCal.get(Calendar.YEAR)); - diff += (toCal.get(Calendar.MONTH) - fromCal.get(Calendar.MONTH)); - toCal.set(Calendar.MONTH, fromCal.get(Calendar.MONTH)); - if (toCal.getTime().before(fromCal.getTime())) { - diff -= 1; - } - } else if ("w".equals(unit)) { - // difference in weeks - diff = msDiff / (7 * 24 * 60 * 60 * 1000); - } else if ("d".equals(unit)) { - // difference in days - diff = msDiff / (24 * 60 * 60 * 1000); - } else if ("h".equals(unit)) { - // difference in hours - diff = msDiff / (60 * 60 * 1000); - } else if ("m".equals(unit)) { - // difference in minutes - diff = msDiff / (60 * 1000); - } else if ("s".equals(unit)) { - // difference in seconds - diff = msDiff / 1000; - } - return diff; - } - - /** - * Other version of the {@link #dateDiff(Date, Date, String)} Method - * @param fromDate first date - * @param toDate second date - * @param unit the time unit for output of the date difference - * @return difference in the given unit - */ - public long dateDiff(Object fromDate, Object toDate, String unit) { - return dateDiff(toDate(fromDate), toDate(toDate), unit); - } - - /** - * Calculate the difference between the given dates in milliseconds. - * @param fromDate first date (should be earlier) - * @param toDate second date (should be later) - * @return difference in milliseconds - */ - public long dateDiff(Date fromDate, Date toDate) { - return dateDiff(fromDate, toDate, "ms"); - } - - /** - * Other version of the {@link #dateDiff(Date, Date)} Method - * @param fromDate first date (should be earlier) - * @param toDate second date (should be later) - * @return difference in milliseconds - */ - public long dateDiff(Object fromDate, Object toDate) { - return dateDiff(toDate(fromDate), toDate(toDate)); - } - - /** - * Transform the Object to a Date - * @param date ContentNodeDate - * @return Date - */ - protected static Date toDate(Object date) { - if (date == null) { - return null; - } - - if (date instanceof Date) { - return (Date) date; - } else { - return null; - } - } - - /** - * Get the DateFormat with given id, or null if not found - * @param formatId format id - * @return DateFormat or null - */ - protected DateFormatConfig getFormatWithId(String formatId) { - DateFormatConfig dateFormat = null; - - if (dateFormats != null && formatId != null) { - JAXBDateFormatType[] dateFormatsArray = dateFormats.getDateFormat(); - - for (int i = 0; i < dateFormatsArray.length && dateFormat == null; i++) { - if (dateFormatsArray[i].getId().equals(formatId)) { - dateFormat = (DateFormatConfig) dateFormatsArray[i]; - } - } - } - - return dateFormat; - } - - /** - * Returns the current language code from the registered language provider wrapper - * - * @return - */ - protected String getCurrentLanguageCode() { - return LanguageProviderFactory.getInstance().getCurrentLanguageCode(); - } - - /** - * Get the timezone of the current date in RFC3339 format. - * See RFC 3339 for details. - * @return timezone of the current time in RFC3339 format. - */ - public String getRfc3339Timezone() { - - Date date = new Date(); - - return getRfc3339Timezone(date); - } - - /** - * Get the timezone of the given date in RFC3339 format. - * See RFC 3339 for details. - * @param date date - * @return timezone of the given date in RFC3339 format. - */ - public String getRfc3339Timezone(Object date) { - Date foo = toDate(date); - SimpleDateFormat format = new SimpleDateFormat("Z"); - String rfc3339tz = format.format(foo).substring(0, 3) + ":" + format.format(foo).substring(3); - - return rfc3339tz; - } - -} diff --git a/base-lib/src/main/java/com/gentics/lib/formatter/dateformatter/DateFormatConfig.java b/base-lib/src/main/java/com/gentics/lib/formatter/dateformatter/DateFormatConfig.java deleted file mode 100644 index 3115d36c8a..0000000000 --- a/base-lib/src/main/java/com/gentics/lib/formatter/dateformatter/DateFormatConfig.java +++ /dev/null @@ -1,308 +0,0 @@ -package com.gentics.lib.formatter.dateformatter; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import com.gentics.lib.etc.StringUtils; - -import jakarta.xml.bind.JAXBElement; - -/** - * @author norbert - */ -public class DateFormatConfig extends JAXBDateFormatType { - - /** - * Map of languagecode specific formats, keys are the languagecodes, values - * are either instances of {@link DateFormat} or - * {@link DateFormatConfig.CombinedDateFormat} - */ - protected Map languageFormats = new HashMap(); - - /** - * Format the given date in the given languagecode - * @param date date to format - * @param languageCode languagecode (may be null) - * @return formatted date - */ - public String format(java.util.Date date, String languageCode) { - // garbage in, garbage out - if (date == null) { - return null; - } - - // get the format - Object format = getDateFormat(languageCode); - - // format the date - if (format instanceof DateFormat) { - return ((DateFormat) format).format(date); - } else if (format instanceof CombinedDateFormat) { - return ((CombinedDateFormat) format).format(date); - } else { - // when no suitable format is found, just make to String representation of the date - return date.toString(); - } - } - - /** - * Parse the given formatted date into a Date object - * @param formattedDate formatted date - * @param languageCode languagecode - * @return date object - * @throws ParseException - */ - public java.util.Date parse(String formattedDate, String languageCode) throws ParseException { - // garbage in, garbage out - if (formattedDate == null) { - return null; - } - - // get the format - Object format = getDateFormat(languageCode); - - // format the date - if (format instanceof DateFormat) { - return ((DateFormat) format).parse(formattedDate); - } else if (format instanceof CombinedDateFormat) { - return ((CombinedDateFormat) format).parse(formattedDate); - } else { - // when no suitable format is found, just make to String representation of the date - return new java.util.Date(formattedDate); - } - } - - /** - * Get the formatter for the given languagecode, returns either a - * {@link DateFormat} or a {@link DateFormatConfig.CombinedDateFormat} or - * null - * @param languageCode language code - * @return date formatter - */ - protected Object getDateFormat(String languageCode) { - if (languageCode == null) { - return null; - } - Object format = languageFormats.get(languageCode); - - if (format == null && !languageFormats.containsKey(languageCode)) { - Locale locale = getLocale(languageCode); - - // first get language specific date/time variants - JAXBElement[] dateOrTime = getDateOrTime(); - String datePart = null; - String timePart = null; - - for (int i = 0; i < dateOrTime.length && (datePart == null || timePart == null); i++) { - if (languageCode.equalsIgnoreCase(dateOrTime[i].getValue().getLanguage())) { - String localName = dateOrTime[i].getName().getLocalPart(); - if (datePart == null && "date".equals(localName)) { - datePart = dateOrTime[i].getValue().getValue(); - } else if (timePart == null && "time".equals(localName)) { - timePart = dateOrTime[i].getValue().getValue(); - } - } - } - - // use default values where no specific formats found - if (datePart == null) { - datePart = getDefaultdate(); - } - if (timePart == null) { - timePart = getDefaulttime(); - } - - // now generate the formats - if (datePart != null) { - if (timePart != null) { - // both parts set - format = new CombinedDateFormat(createDateFormat(datePart, locale), createTimeFormat(timePart, locale)); - } else { - // only datepart set - format = createDateFormat(datePart, locale); - } - } else { - if (timePart != null) { - // only timepart set - format = createTimeFormat(timePart, locale); - } else {// no suitable format found - } - } - - languageFormats.put(languageCode, format); - } - - return format; - } - - /** - * Parse the given format into the shortformat int - * @param format format as string - * @return the constant for the short format or -1 - */ - public static int getShortFormat(String format) { - if ("FULL".equalsIgnoreCase(format)) { - return DateFormat.FULL; - } else if ("LONG".equalsIgnoreCase(format)) { - return DateFormat.LONG; - } else if ("MEDIUM".equalsIgnoreCase(format)) { - return DateFormat.MEDIUM; - } else if ("SHORT".equalsIgnoreCase(format)) { - return DateFormat.SHORT; - } else { - return -1; - } - } - - /** - * Create the dateformat for the given date format configuration - * @param dateFormat configured format - * @param locale locale - * @return dateformat - */ - public static DateFormat createDateFormat(String dateFormat, Locale locale) { - int shortFormat = getShortFormat(dateFormat); - - if (shortFormat >= 0) { - return DateFormat.getDateInstance(shortFormat, locale); - } else { - return new SimpleDateFormat(dateFormat, locale); - } - } - - /** - * Create the dateformat for the given time format configuration - * @param timeFormat configured format - * @param locale locale - * @return timeformat - */ - public static DateFormat createTimeFormat(String timeFormat, Locale locale) { - int shortFormat = getShortFormat(timeFormat); - - if (shortFormat >= 0) { - return DateFormat.getTimeInstance(shortFormat, locale); - } else { - return new SimpleDateFormat(timeFormat, locale); - } - } - - /** - * Create the dateformat for the given date/time format configuration - * @param dateTimeFormat configured format - * @param locale locale - * @return date/time format - */ - public static DateFormat createDateTimeFormat(String dateTimeFormat, Locale locale) { - int shortFormat = getShortFormat(dateTimeFormat); - - if (shortFormat >= 0) { - return DateFormat.getDateTimeInstance(shortFormat, shortFormat, locale); - } else { - return new SimpleDateFormat(dateTimeFormat, locale); - } - } - - /** - * Get the locale for the given language code - * @param languageCode language code - * @return locale - */ - public static Locale getLocale(String languageCode) { - if (StringUtils.isEmpty(languageCode)) { - return Locale.getDefault(); - } else { - return new Locale(languageCode); - } - } - - /** - * Internal class for combined date/time formats - */ - protected static class CombinedDateFormat { - - /** - * date part - */ - protected DateFormat dateFormat; - - /** - * time part - */ - protected DateFormat timeFormat; - - /** - * Create an instance of the combined format - * @param dateFormat date format - * @param timeFormat time format - */ - public CombinedDateFormat(DateFormat dateFormat, DateFormat timeFormat) { - this.dateFormat = dateFormat; - this.timeFormat = timeFormat; - } - - /** - * format the given date - * @param date date to format - * @return formatted date - */ - public String format(java.util.Date date) { - if (dateFormat == null) { - if (timeFormat == null) { - return null; - } else { - return timeFormat.format(date); - } - } else { - if (timeFormat == null) { - return dateFormat.format(date); - } else { - StringBuffer buffer = new StringBuffer(); - - buffer.append(dateFormat.format(date)).append(" ").append(timeFormat.format(date)); - return buffer.toString(); - } - } - } - - /** - * Parse the given formatted date into a Date object - * @param formattedDate formatted date - * @return date object - */ - public java.util.Date parse(String formattedDate) throws ParseException { - if (dateFormat == null) { - if (timeFormat == null) { - return null; - } else { - return timeFormat.parse(formattedDate); - } - } else { - if (timeFormat == null) { - return dateFormat.parse(formattedDate); - } else { - // first parse with the date part - java.util.Date datePart = dateFormat.parse(formattedDate); - // now format the datePart again and remove from the original formatted date - String formattedDatePart = dateFormat.format(datePart); - - formattedDate = formattedDate.substring(Math.min(formattedDate.length(), formattedDatePart.length() + 1)); - // parse the remaining part with the timeformat - java.util.Date timePart = timeFormat.parse(formattedDate); - - // calculate the offset - long offset = Calendar.getInstance().getTimeZone().getOffset(0); - - // now we have date/time part we have to combine both and - // add the offset, since it is contained in both parts and - // would otherwise be calculated twice - return new java.util.Date(datePart.getTime() + timePart.getTime() + offset); - } - } - } - } -} diff --git a/base-lib/src/main/java/com/gentics/lib/render/velocity/ChangeableVelocityUberspectImpl.java b/base-lib/src/main/java/com/gentics/lib/render/velocity/ChangeableVelocityUberspectImpl.java deleted file mode 100644 index b688716f39..0000000000 --- a/base-lib/src/main/java/com/gentics/lib/render/velocity/ChangeableVelocityUberspectImpl.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * @author norbert - * @date 06.06.2008 - * @version $Id: ChangeableVelocityUberspectImpl.java,v 1.4.2.1 2011-04-07 09:57:53 norbert Exp $ - */ -package com.gentics.lib.render.velocity; - -import org.apache.velocity.exception.VelocityException; -import org.apache.velocity.runtime.log.Log; -import org.apache.velocity.runtime.parser.node.SetExecutor; -import org.apache.velocity.util.introspection.Info; -import org.apache.velocity.util.introspection.UberspectImpl; -import org.apache.velocity.util.introspection.VelPropertySet; - -import com.gentics.api.lib.exception.InsufficientPrivilegesException; -import com.gentics.api.lib.resolving.Changeable; - -/** - * @author norbert - */ -public class ChangeableVelocityUberspectImpl extends UberspectImpl { - - /* - * (non-Javadoc) - * @see org.apache.velocity.util.introspection.UberspectImpl#getPropertySet(java.lang.Object, - * java.lang.String, java.lang.Object, - * org.apache.velocity.util.introspection.Info) - */ - public VelPropertySet getPropertySet(Object obj, String identifier, Object arg, Info i) throws Exception { - VelPropertySet propertySet = super.getPropertySet(obj, identifier, arg, i); - - if (propertySet == null && obj instanceof Changeable) { - Class claz = obj.getClass(); - SetExecutor executor = new ChangeableSetExecutor(log, claz, identifier); - - if (executor.isAlive()) { - propertySet = new VelSetterImpl(executor); - } - } - return propertySet; - } -} - -class ChangeableSetExecutor extends SetExecutor { - - public ChangeableSetExecutor(Log log, Class clazz, String property) { - this.log = log; - this.property = property; - discover(clazz); - } - - protected void discover(Class clazz) { - if (!Changeable.class.isAssignableFrom(clazz)) { - // the ChangeableVelocityUberspectImpl already checks - // whether the obj is changeable, so this case should never happen. - log.error( - "An attempt was made to instantiate a SetExecutor for" + " " + clazz.getName() + " although it isn't" - + " changeable - it was probably referenced in a" + " velocity set statement: #set(obj.property = 'xyz')"); - return; - } - try { - if (property != null) { - setMethod((Changeable.class).getMethod("setProperty", new Class[] { - java.lang.String.class, java.lang.Object.class})); - } - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - String msg = "Exception while looking for put('" + property + "') method"; - - log.error(msg, e); - throw new VelocityException(msg, e); - } - } - - public Object execute(Object o, Object arg) { - Changeable c = (Changeable) o; - Object oldVal = c.get(property); - - try { - c.setProperty(property, arg); - } catch (InsufficientPrivilegesException e) { - log.error("Error while setting property '" + property + "'", e); - } - return oldVal; - } - - private final String property; -} diff --git a/base-lib/src/main/java/com/gentics/lib/render/velocity/SerializableVelocityTemplateWrapper.java b/base-lib/src/main/java/com/gentics/lib/render/velocity/SerializableVelocityTemplateWrapper.java deleted file mode 100644 index f4ddf3fd4d..0000000000 --- a/base-lib/src/main/java/com/gentics/lib/render/velocity/SerializableVelocityTemplateWrapper.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * @author alexander - * @date 04.06.2007 - * @version $Id: SerializableVelocityTemplateWrapper.java,v 1.2 2008-05-26 15:05:57 norbert Exp $ - */ -package com.gentics.lib.render.velocity; - -import java.io.Serializable; - -import org.apache.velocity.Template; -import org.apache.velocity.runtime.RuntimeSingleton; - -/** - * Wrap velocity template in serializable object, since it is not serializable - * (needed for JCS caching). This does not make the template itself - * serializable! - * - * When an instance of this class is garbage collected, all references to the Template instance - * are lost, so the local namespace of the template can be cleared. - */ -public class SerializableVelocityTemplateWrapper implements Serializable { - /** - * Serial Version UID - */ - private static final long serialVersionUID = -307344517621305235L; - - /** - * The velocity template to wrap. Marked transient to treat as cache miss if - * cache tried to serialize it. - */ - private transient Template template; - - /** - * Create a new wrapper around the velocity template. - * @param template The velocity template to wrap. - */ - public SerializableVelocityTemplateWrapper(Template template) { - this.template = template; - } - - /** - * Get the wrapped velocity template. - * @return The wrapped velocity template. - */ - public Template getTemplate() { - return template; - } - - /** - * Set the wrapped velocity template. - * @param template The velocity template to wrap. - */ - public void setTemplate(Template template) { - this.template = template; - } - - /* (non-Javadoc) - * @see java.lang.Object#finalize() - */ - @Override - protected void finalize() throws Throwable { - super.finalize(); - - // dump the velocimacro namespace - RuntimeSingleton.dumpVMNamespace(template.getName()); - } -} diff --git a/base-lib/src/main/java/com/gentics/portalnode/formatter/GenticsStringFormatter.java b/base-lib/src/main/java/com/gentics/portalnode/formatter/GenticsStringFormatter.java deleted file mode 100644 index d4a19ed72e..0000000000 --- a/base-lib/src/main/java/com/gentics/portalnode/formatter/GenticsStringFormatter.java +++ /dev/null @@ -1,362 +0,0 @@ -package com.gentics.portalnode.formatter; - -import java.io.UnsupportedEncodingException; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.regex.PatternSyntaxException; - -import com.gentics.api.portalnode.imp.AbstractGenticsImp; -import com.gentics.lib.etc.StringUtils; -import com.gentics.lib.log.NodeLogger; - -import fi.iki.santtu.md5.MD5; - -/** - * Created by IntelliJ IDEA. User: marius.toader Date: Feb 18, 2005 Time: - * 12:23:37 PM To change this template use Options | File Templates. - */ -public class GenticsStringFormatter extends AbstractGenticsImp { - // order is important, do not change to other type of map - private final static Map htmlEscapes = new LinkedHashMap(); - - // order is important, do not change to other type of map - private final static Map javaScriptEscapes = new LinkedHashMap(); - - /** - * constant for an empty string - */ - private final static String EMPTY_STRING = ""; - - static { - // this must allways be the the first one to be escaped - htmlEscapes.put("&", "&"); - htmlEscapes.put("<", "<"); - htmlEscapes.put(">", ">"); - // htmlEscapes.put(" ", " "); - htmlEscapes.put("\u2122", "™"); - htmlEscapes.put("\u00ae", "®"); - htmlEscapes.put("\u00a9", "©"); - htmlEscapes.put("\"", """); - htmlEscapes.put("\'", "'"); - - javaScriptEscapes.put("\\\\", "\\\\\\\\"); - javaScriptEscapes.put("\"", "\\\\\""); - javaScriptEscapes.put("\'", "\\\\'"); - } - - /** - * the default constructor - */ - public GenticsStringFormatter() {} - - /** - * Escapes the most common javascript escape characters. Please see the - * source code for the exact escape sequences. - * @param originalString The String that contains the unescaped string. - * @return A String that contains the string with the escape caracters. - */ - public String escapeJS(Object originalString) { - if (originalString != null) { - return applyRegex(originalString.toString(), javaScriptEscapes); - } else { - return EMPTY_STRING; - } - } - - /** - * Escapes the most common javascript escape caracters. Please see the - * source code for the exact escape sequences. - * @param originalString The String that contains the unescaped string. - * @return A String that contains the string with the escape caracters. - */ - public String escapeHTML(Object originalString) { - if (originalString != null) { - return applyRegex(originalString.toString(), htmlEscapes); - } else { - return EMPTY_STRING; - } - } - - /** - * Removes the embeded HTML tags from user input string to prevent potential - * problems (in fact it removes anything with ). - * @param originalString The original string that may contain HTML element - * @return A String that does not contain HTML elements () - */ - public String stripML(Object originalString) { - if (originalString == null) { - return EMPTY_STRING; - } - String parsedString = null; - - parsedString = originalString.toString().replaceAll("<[^<]*?>", ""); - return parsedString; - } - - /** - * Trims the string to the speciafied length if it's longer than that. - * @param originalString The string that must be trimmed. - * @param maxSize The maximum size in characters of the string. - * @return The trimmed string that now has max "maxSize" characters. - */ - public String trim(Object originalString, int maxSize) { - if (originalString == null) { - return EMPTY_STRING; - } - if (maxSize >= originalString.toString().length()) { - return originalString.toString(); - } - String parsedString = null; - - parsedString = originalString.toString().substring(0, maxSize); - return parsedString; - } - - /** - * Replaces certain portions of the string (based on a regular expression) - * with another string. - * @param originalString The string that will be parsed for matching - * substrings. - * @param regex The regular expression (as defined in jdk) that will match - * in the originalstring. - * @param replacement The string that will replace the parts of the original - * string that match the regex. - * @return The original string where occurences of the regex are replaced by - * the replacement string. - */ - public String regexp(Object originalString, Object regex, Object replacement) { - if (originalString == null || regex == null || replacement == null) { - if (originalString != null && originalString instanceof String) { - return (String) originalString; - } - return EMPTY_STRING; - } - String parsedString = null; - - try { - parsedString = originalString.toString().replaceAll(regex.toString(), replacement.toString()); - } catch (PatternSyntaxException e) { - NodeLogger.getNodeLogger(getClass()).error("Error while using regexp", e); - } - return parsedString; - } - - /** - * tests a given regex and returns a result string. error messages are not - * localized, because its not required, but improves performance. - * @param text the text to use. null is interpreted as empty string. - * @param regex the regex to test, null regexes will be invalid and generate - * a custom error message. - * @return 1 for match, 0 for no match, or any other text for syntax error. - */ - public String testRegex(Object text, Object regex) { - if (regex == null) { - return "error, regex was null"; - } - if (text == null) { - text = EMPTY_STRING; - } - try { - if (text.toString().matches(regex.toString())) { - return "1"; - } else { - return "0"; - } - } catch (PatternSyntaxException e) { - return "error, " + e.getMessage(); - } - } - - // iterates over a Map and replaces occurences of the "keys" (regexs) with - // the "values" - // of the keys - private String applyRegex(String originalString, Map regs) { - if (originalString == null) { - return ""; - } - String parsedString = null; - Iterator toEscape = regs.keySet().iterator(); - - parsedString = originalString; - try { - while (toEscape.hasNext()) { - String escape = (String) toEscape.next(); - - parsedString = parsedString.replaceAll(escape, (String) regs.get(escape)); - } - } catch (PatternSyntaxException e) { - NodeLogger.getNodeLogger(getClass()).warn("Error while using regexp"); - } - return parsedString; - } - - /** - * convert the given string to all uppercase - * @param originalString original string - * @return original string converted to uppercase letters - */ - public String toUpper(Object originalString) { - if (originalString == null) { - return EMPTY_STRING; - } else { - return originalString.toString().toUpperCase(); - } - } - - /** - * Trim all words in the string that exceed the given length - * @param originalString original string - * @param maxLength maximum length of words - * @param ellipsis to use in trimmed words - * @param template template to use as replacement for the long words. In the - * template, $word and $trimmedword can be used for the word and - * trimmed word. The template may be null or empty for just trimming - * the words - * @return string with all words longer than maxLength trimmed - */ - public String trimWords(Object originalString, int maxLength, Object ellipsis, - Object template) { - if (originalString == null || ellipsis == null) { - return EMPTY_STRING; - } - StringBuffer trimmedString = new StringBuffer(originalString.toString().length()); - boolean useTemplate = (template != null && template.toString().length() > 0); - - // split the string into words (by words boundaries, without losing - // spaces between the words) - String[] words = originalString.toString().split("\\b"); - int trimLength = ellipsis.toString().length() + 1; - - if (trimLength > maxLength - 1) { - // the maxlength is too small, make it bigger - maxLength = trimLength + 1; - } - for (int i = 0; i < words.length; ++i) { - if (words[i].trim().length() > maxLength) { - // we have to trim the word - if (useTemplate) { - // create the trimmed word - StringBuffer trimmedWord = new StringBuffer(maxLength); - - trimmedWord.append(words[i].substring(0, Math.max(maxLength - trimLength, 1))); - trimmedWord.append(ellipsis); - trimmedWord.append(words[i].substring(words[i].length() - 1, words[i].length())); - trimmedString.append(template.toString().replaceAll("\\$word\\b", words[i]).replaceAll("\\$trimmedword\\b", trimmedWord.toString())); - } else { - // just append the trimmed word - trimmedString.append(words[i].substring(0, Math.max(maxLength - trimLength, 1))); - trimmedString.append(ellipsis); - trimmedString.append(words[i].substring(words[i].length() - 1, words[i].length())); - } - } else { - // word is ok - trimmedString.append(words[i]); - } - } - - return trimmedString.toString(); - } - - /** - * Trim all words in the string that exceed the given length - * @param originalString original string - * @param maxLength maximum length of words - * @return string with all words longer than maxLength trimmed - */ - public String trimWords(Object originalString, int maxLength, Object ellipsis) { - return trimWords(originalString, maxLength, ellipsis, null); - } - - /** - * Trim all words in the string that exceed the given length - * @param originalString original string - * @param maxLength maximum length of words - * @return string with all words longer than maxLength trimmed - */ - public String trimWords(Object originalString, int maxLength) { - return trimWords(originalString, maxLength, "...", null); - } - - /** - * Translates a string into x-www-form-urlencoded - * format. This method uses the platform's default encoding - * as the encoding scheme to obtain the bytes for unsafe characters. - * - * @param string the string to be translated - * @return the translated string. - */ - public String encodeURL(String string) { - try { - return StringUtils.encodeURL(string, "UTF-8"); - } catch (UnsupportedEncodingException e) { - NodeLogger.getNodeLogger(getClass()).error("Error while encoding URL", e); - return string; - } - } - - /** - * Translates a string into x-www-form-urlencoded - * format, using the given encoding to obtain the bytes for unsafe characters. - * @param string the string to be translated - * @param encoding encoding - * @return the translated string - */ - public String encodeURL(String string, String encoding) { - try { - return StringUtils.encodeURL(string, encoding); - } catch (UnsupportedEncodingException e) { - NodeLogger.getNodeLogger(getClass()).error("Error while encoding URL", e); - return string; - } - } - - /** - * @see StringUtils#merge(Object[], String) - */ - public String implode(Object[] parts, String glue) { - return StringUtils.merge(parts, glue); - } - - /** - * @see StringUtils#merge(Object[], String, String, String) - */ - public String implode(Object[] parts, String glue, String prefix, String postfix) { - return StringUtils.merge(parts, glue, prefix, postfix); - } - - /** - * @see #implode(Object[], String) - */ - public String implode(Collection parts, String glue) { - return StringUtils.merge(parts.toArray(), glue); - } - - /** - * @see #implode(Object[], String, String, String) - */ - public String implode(Collection parts, String glue, String prefix, String postfix) { - return StringUtils.merge(parts.toArray(), glue, prefix, postfix); - } - - /** - * create md5 hash of the given string - * null strings are treated like empty strings "" - * @param string to be hashed - * @return md5 hash of string - */ - public String md5(String string) { - if (string == null) { - string = ""; - } - - MD5 md5 = new MD5(); - - md5.Init(); - md5.Update(string); - String hash = md5.asHex(); - - return hash; - } -} diff --git a/base-lib/src/main/java/com/gentics/portalnode/formatter/SortImp.java b/base-lib/src/main/java/com/gentics/portalnode/formatter/SortImp.java deleted file mode 100644 index 73823f1dd0..0000000000 --- a/base-lib/src/main/java/com/gentics/portalnode/formatter/SortImp.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * @author norbert - * @date 28.09.2007 - * @version $Id: SortImp.java,v 1.2 2007-11-13 10:03:41 norbert Exp $ - */ -package com.gentics.portalnode.formatter; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import com.gentics.api.lib.datasource.Datasource; -import com.gentics.api.lib.resolving.ResolvableComparator; -import com.gentics.api.portalnode.imp.AbstractGenticsImp; -import com.gentics.lib.log.NodeLogger; - -/** - * An imp for sorting collection of resolvables - */ -public class SortImp extends AbstractGenticsImp { - - /** - * logger - */ - protected NodeLogger logger = NodeLogger.getNodeLogger(getClass()); - - /** - * constant for ascending sorting - */ - public static final String TYPE_ASCENDING_SHORT = "asc"; - - /** - * constant for descending sorting - */ - public static final String TYPE_DESCENDING_SHORT = "desc"; - - /** - * Sort the object (collection, object array or map). Sorting is done case - * insensitive - * @param object collection, object array or map - * @param property sorted property (might contain :asc or :desc) - * @return sorted collection - */ - public Collection sort(Object object, String property) { - return sort(object, property, false, null); - } - - /** - * Sort the object (collection, object array or map) - * @param object collection, object array or map - * @param property sorted property (might contain :asc or :desc) - * @param caseSensitive true for case sensitive sorting, false for case - * insensitive - * @return sorted collection - */ - public Collection sort(Object object, String property, boolean caseSensitive) { - return sort(object, property, caseSensitive, null); - } - - /** - * Sort the object (collection, object array or map) - * @param object collection, object array or map - * @param property sorted property (might contain :asc or :desc) - * @param localeCode code of the locale to be used for sorting - * @return sorted collection - */ - public Collection sort(Object object, String property, String localeCode) { - return sort(object, property, false, localeCode); - } - - /** - * Sort the object (collection, object array or map) - * @param object collection, object array or map - * @param property sorted property (might contain :asc or :desc) - * @param caseSensitive true for case sensitive sorting, false for case - * insensitive - * @param localeCode code of the locale to be used for sorting - * @return sorted collection - */ - public Collection sort(Object object, String property, boolean caseSensitive, String localeCode) { - List properties = new ArrayList(1); - - properties.add(property); - - if (object instanceof Collection) { - return sort((Collection) object, properties, caseSensitive, localeCode); - } else if (object instanceof Object[]) { - return sort((Object[]) object, properties, caseSensitive, localeCode); - } else if (object instanceof Map) { - return sort((Map) object, properties, caseSensitive, localeCode); - } - // the object type is not supported - return null; - } - - /** - * Sort the collection with the given list of properties - * @param collection collection to sort - * @param properties list of sorted properties - * @return sorted collection - */ - public Collection sort(Collection collection, List properties) { - return sort(collection, properties, false, null); - } - - /** - * Sort the collection with the given list of properties - * @param collection collection to sort - * @param properties list of sorted properties - * @param caseSensitive true for case sensitive sorting, false for case - * insensitive - * @return sorted collection - */ - public Collection sort(Collection collection, List properties, boolean caseSensitive) { - return sort(collection, properties, caseSensitive, null); - } - - /** - * Sort the collection with the given list of properties - * @param collection collection to sort - * @param properties list of sorted properties - * @param localeCode code of the locale to be used for sorting - * @return sorted collection - */ - public Collection sort(Collection collection, List properties, String localeCode) { - return sort(collection, properties, false, localeCode); - } - - /** - * Sort the collection with the given list of properties - * @param collection collection to sort - * @param properties list of sorted properties - * @param caseSensitive true for case sensitive sorting, false for case - * insensitive - * @param localeCode code of the locale to be used for sorting - * @return sorted collection - */ - public Collection sort(Collection collection, List properties, boolean caseSensitive, String localeCode) { - List list = new ArrayList(collection.size()); - - list.addAll(collection); - return internalSort(list, properties, caseSensitive, localeCode); - } - - /** - * Sort the map values - * @param map map to sort - * @param properties list of sorted properties - * @return sorted collection - */ - public Collection sort(Map map, List properties) { - return sort(map.values(), properties, false, null); - } - - /** - * Sort the map values - * @param map map to sort - * @param properties list of sorted properties - * @param caseSensitive true for case sensitive sorting, false for case - * insensitive - * @return sorted collection - */ - public Collection sort(Map map, List properties, boolean caseSensitive) { - return sort(map.values(), properties, caseSensitive, null); - } - - /** - * Sort the map values - * @param map map to sort - * @param properties list of sorted properties - * @param localeCode code of the locale to be used for sorting - * @return sorted collection - */ - public Collection sort(Map map, List properties, String localeCode) { - return sort(map, properties, false, localeCode); - } - - /** - * Sort the map values - * @param map map to sort - * @param properties list of sorted properties - * @param caseSensitive true for case sensitive sorting, false for case - * insensitive - * @param localeCode code of the locale to be used for sorting - * @return sorted collection - */ - public Collection sort(Map map, List properties, boolean caseSensitive, String localeCode) { - return sort(map.values(), properties, caseSensitive, localeCode); - } - - /** - * Sort the array with the given list of properties - * @param array array to sort - * @param properties list of sorted properties - * @return sorted collection - */ - public Collection sort(Object[] array, List properties) { - return sort(array, properties, false, null); - } - - /** - * Sort the array with the given list of properties - * @param array array to sort - * @param properties list of sorted properties - * @param caseSensitive true for case sensitive sorting, false for case - * insensitive - * @return sorted collection - */ - public Collection sort(Object[] array, List properties, boolean caseSensitive) { - return internalSort(Arrays.asList(array), properties, caseSensitive, null); - } - - /** - * Sort the array with the given list of properties - * @param array array to sort - * @param properties list of sorted properties - * @param localeCode code of the locale to be used for sorting - * @return sorted collection - */ - public Collection sort(Object[] array, List properties, String localeCode) { - return sort(array, properties, false, localeCode); - } - - /** - * Sort the array with the given list of properties - * @param array array to sort - * @param properties list of sorted properties - * @param caseSensitive true for case sensitive sorting, false for case - * insensitive - * @param localeCode code of the locale to be used for sorting - * @return sorted collection - */ - public Collection sort(Object[] array, List properties, boolean caseSensitive, String localeCode) { - return internalSort(Arrays.asList(array), properties, caseSensitive, localeCode); - } - - /** - * Parse the given property into a sorting property (detect sortorder) - * @param property property, might contain :asc or :desc - * @return sorting parameter with sortorder (defaults to asc) - */ - protected Datasource.Sorting getSorting(String property) { - int colonIndex = property.indexOf(':'); - - if (colonIndex != -1) { - String sortType = property.substring(colonIndex + 1); - - property = property.substring(0, colonIndex); - - if (TYPE_ASCENDING_SHORT.equalsIgnoreCase(sortType)) { - return new Datasource.Sorting(property, Datasource.SORTORDER_ASC); - } else if (TYPE_DESCENDING_SHORT.equalsIgnoreCase(sortType)) { - return new Datasource.Sorting(property, Datasource.SORTORDER_DESC); - } else { - return new Datasource.Sorting(property, Datasource.SORTORDER_ASC); - } - } else { - return new Datasource.Sorting(property, Datasource.SORTORDER_ASC); - } - } - - /** - * Parse the given list of properties into an array of sorting parameters - * @param properties list of properties - * @return array of sorting parameters - */ - protected Datasource.Sorting[] getSorting(List properties) { - int size = properties.size(); - Datasource.Sorting[] sorting = new Datasource.Sorting[size]; - - for (int i = 0; i < size; ++i) { - sorting[i] = getSorting(properties.get(i).toString()); - } - - return sorting; - } - - /** - * Internal method to sort the given list - * @param list list to sort - * @param properties sorting parameters - * @param caseSensitive true for case sensitive sorting, false for case - * insensitive - * @param localeCode code of the locale used for sorting (may be null for default locale) - * @return sorted collection - */ - protected Collection internalSort(List list, List properties, boolean caseSensitive, String localeCode) { - try { - if (properties == null) { - throw new Exception("Cannot sort without sorting properties"); - } else { - Comparator c = null; - - if (localeCode != null) { - Locale locale = new Locale(localeCode); - - c = new ResolvableComparator(getSorting(properties), caseSensitive, locale); - } else { - c = new ResolvableComparator(getSorting(properties), caseSensitive); - } - Collections.sort(list, c); - } - return list; - } catch (Exception e) { - logger.error("Error while sorting: ", e); - return null; - } - } -} diff --git a/base-lib/src/main/java/com/gentics/portalnode/formatter/URLIncludeImp.java b/base-lib/src/main/java/com/gentics/portalnode/formatter/URLIncludeImp.java deleted file mode 100644 index a0a18ed5ae..0000000000 --- a/base-lib/src/main/java/com/gentics/portalnode/formatter/URLIncludeImp.java +++ /dev/null @@ -1,463 +0,0 @@ -package com.gentics.portalnode.formatter; - -import java.io.Serializable; - -import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; -import org.apache.commons.httpclient.cookie.CookiePolicy; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.params.HttpClientParams; -import org.apache.commons.httpclient.params.HttpConnectionManagerParams; -import org.apache.commons.httpclient.params.HttpConnectionParams; - -import com.gentics.api.lib.cache.PortalCache; -import com.gentics.api.lib.cache.PortalCacheAttributes; -import com.gentics.api.lib.cache.PortalCacheException; -import com.gentics.api.lib.etc.ObjectTransformer; -import com.gentics.api.lib.exception.NodeException; -import com.gentics.api.portalnode.imp.AbstractGenticsImp; -import com.gentics.lib.log.NodeLogger; - -/** - * Imp for accessing the given URL and returning the content fetched from there - */ -public class URLIncludeImp extends AbstractGenticsImp { - - /** - * Name of the cache region - */ - protected final static String CACHE_REGION = ""; - - /** - * Default timeout for the connection manager - */ - protected final static long DEFAULT_CONNECTION_MANAGER_TIMEOUT = 1000; - - /** - * Default host connection limit - */ - protected final static int DEFAULT_HOST_CONNECTION_LIMIT = 20; - - /** - * Default total connection limit - */ - protected final static int DEFAULT_MAX_CONNECTION_LIMIT = 20; - - /** - * The logger - */ - protected final static NodeLogger logger = NodeLogger.getNodeLogger(URLIncludeImp.class); - - /** - * Cache instance for the cache region - */ - protected static PortalCache cache; - - /** - * connection manager instance - */ - protected static MultiThreadedHttpConnectionManager connectionManager = null; - - /** - * http client instance - */ - protected static HttpClient client; - - static { - try { - cache = PortalCache.getCache(CACHE_REGION); - } catch (PortalCacheException e) { - logger.error("Error while initializing cache region " + CACHE_REGION, e); - } - - // create the connection manager and the http client instance - connectionManager = new MultiThreadedHttpConnectionManager(); - - int maxHostConnections = ObjectTransformer.getInteger(System.getProperty(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS), - DEFAULT_HOST_CONNECTION_LIMIT); - - logger.debug("Using max host connections: " + HttpConnectionManagerParams.MAX_HOST_CONNECTIONS + " {" + maxHostConnections + "}"); - - int maxTotalConnections = ObjectTransformer.getInteger(System.getProperty(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS), - DEFAULT_MAX_CONNECTION_LIMIT); - - logger.debug("Using max total connections: " + HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS + " {" + maxTotalConnections + "}"); - - connectionManager.getParams().setMaxTotalConnections(maxTotalConnections); - connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxHostConnections); - - client = new HttpClient(connectionManager); - - // Set timeout on how long we’ll wait for a connection from the pool - client.getParams().setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, DEFAULT_CONNECTION_MANAGER_TIMEOUT); - client.getParams().setParameter(HttpClientParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); - } - - /** - * Access the given URL and return the content - * - * @param url - * URL to be requested - * @param cacheLifeTime - * cache lifetime in secs, defaults to 300 secs (5 mins) - * @param timeout - * timeout for accessing the URL and getting the contents in ms, - * defaults to 2000 ms (2 secs) - * @param defaultContent - * default content to be returned, if the URL cannot be accessed - * @return content fetched from the URL. If null is given and the URL cannot - * be accessed, an exception is thrown - * @throws NodeException - * if the URL cannot be accessed and no defaultContent was given - */ - - public String includeUrl(String url, int cacheLifeTime, int timeout, String defaultContent) throws NodeException { - - if (logger.isDebugEnabled()) { - logger.debug("include(" + url + ", " + cacheLifeTime + ", " + timeout + ", " + defaultContent + ")"); - } - - // check whether a URL was given - if (ObjectTransformer.isEmpty(url)) { - logger.warn("Error while including URL: URL was empty"); - return ""; - } - - // check whether the content is cached - if (cache != null) { - try { - Object cachedObject = cache.get(url); - - if (CachedError.isCachedError(cachedObject)) { - if (logger.isDebugEnabled()) { - logger.debug("Got cached error"); - } - return handleError(url, "Access to URL {" + url + "} failed and failure was cached.", defaultContent, null, false, cacheLifeTime); - } - String content = ObjectTransformer.getString(cachedObject, null); - - if (content != null) { - if (logger.isDebugEnabled()) { - logger.debug("Got content from cache"); - } - return content; - } - } catch (PortalCacheException e) { - logger.warn("Error while getting cached content for {" + url + "}", e); - } - } - - // request the URL and get the contents - GetMethod getRequest = new GetMethod(url); - - getRequest.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); - getRequest.setFollowRedirects(true); - getRequest.getParams().setSoTimeout(timeout); - getRequest.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, timeout); - - String content = null; - - try { - int status = client.executeMethod(getRequest); - - switch (status) { - case HttpStatus.SC_OK: - case HttpStatus.SC_NO_CONTENT: - if (logger.isDebugEnabled()) { - logger.debug("Got content from URL {" + url + "}"); - } - content = getRequest.getResponseBodyAsString(); - break; - - default: - return handleError(url, "Error while accessing url {" + url + "}, response code was " + status, defaultContent, null, true, cacheLifeTime); - } - } catch (Exception e) { - return handleError(url, "Error while accessing url {" + url + "}", defaultContent, e, true, cacheLifeTime); - } - - // put contents into cache and return it - if (cache != null) { - try { - cache.put(url, content, new CacheAttributes(cacheLifeTime)); - } catch (PortalCacheException e) { - logger.warn("Error while putting content of {" + url + "} into cache", e); - } - } - - return content; - } - - public String include(Object url, Object cacheLifeTime, Object timeout, - Object defaultContent) throws NodeException { - - // get the parameters - String sURL = ObjectTransformer.getString(url, null); - int iCacheLifeTime = ObjectTransformer.getInt(cacheLifeTime, 300); - int iTimeout = ObjectTransformer.getInt(timeout, 2000); - String sDefaultContent = ObjectTransformer.getString(defaultContent, null); - - return includeUrl(sURL, iCacheLifeTime, iTimeout, sDefaultContent); - - } - - /** - * Method to handle an error - * - * @param URL - * url that was accessed - * @param message - * message of the error - * @param defaultContent - * default content to be returned in case of an error, may be - * null - * @param t - * throwable (root cause, may be null) - * @param putIntoCache - * true if the error shall be cached, false if not (because it - * already is cached) - * @param cacheLifeTime - * cache life time in seconds - * @return the content to return - * @throws NodeException - */ - protected String handleError(String URL, String message, - String defaultContent, Throwable t, boolean putIntoCache, - int cacheLifeTime) throws NodeException { - // log an error - logger.error(message, t); - - if (putIntoCache && cache != null) { - try { - cache.put(URL, CachedError.getInstance(), new CacheAttributes(cacheLifeTime)); - } catch (PortalCacheException e) {} - } - - // either return the default content or throw an exception - if (defaultContent != null) { - return defaultContent; - } else { - throw new NodeException(message, t); - } - } - - /** - * Access the given URL and return the content - * - * @param url - * URL to be requested - * @param cacheLifeTime - * cache lifetime in secs - * @param timeout - * timeout for accessing the URL and getting the contents in ms - * @return content fetched from the URL. - * @throws NodeException - * if the URL cannot be accessed - */ - public String include(Object url, Object cacheLifeTime, Object timeout) throws NodeException { - return include(url, cacheLifeTime, timeout, null); - } - - /** - * Access the given URL and return the content - * - * @param url - * URL to be requested - * @param cacheLifeTime - * cache lifetime in secs - * @return content fetched from the URL. - * @throws NodeException - * if the URL cannot be accessed - */ - public String include(Object url, Object cacheLifeTime) throws NodeException { - return include(url, cacheLifeTime, null, null); - } - - /** - * Access the given URL and return the content - * - * @param url - * URL to be requested - * @return content fetched from the URL. - * @throws NodeException - * if the URL cannot be accessed - */ - public String include(Object url) throws NodeException { - return include(url, null, null, null); - } - - /** - * Internal class for cache attributes. This is used to set the maximum age - * of cache entries - */ - public static class CacheAttributes implements PortalCacheAttributes { - - /** - * Maximum Age - */ - private int maxAge; - - /** - * Creation date - */ - private long createDate; - - /** - * Last access time - */ - private long lastAccessTime; - - /** - * Create an instance of the Cache Attributes - * - * @param maxAge - * maximum age (in secs) - */ - public CacheAttributes(int maxAge) { - this.maxAge = maxAge; - createDate = System.currentTimeMillis(); - lastAccessTime = createDate; - } - - /* - * (non-Javadoc) - * - * @see com.gentics.api.lib.cache.PortalCacheAttributes#getCreateDate() - */ - public long getCreateDate() { - return createDate; - } - - /* - * (non-Javadoc) - * - * @see com.gentics.api.lib.cache.PortalCacheAttributes#getIsEternal() - */ - public boolean getIsEternal() { - return false; - } - - /* - * (non-Javadoc) - * - * @see - * com.gentics.api.lib.cache.PortalCacheAttributes#getLastAccessDate() - */ - public long getLastAccessDate() { - return lastAccessTime; - } - - /* - * (non-Javadoc) - * - * @see com.gentics.api.lib.cache.PortalCacheAttributes#getMaxAge() - */ - public int getMaxAge() { - return maxAge; - } - - /* - * (non-Javadoc) - * - * @see com.gentics.api.lib.cache.PortalCacheAttributes#getMaxIdleTime() - */ - public int getMaxIdleTime() { - return 0; - } - - /* - * (non-Javadoc) - * - * @see com.gentics.api.lib.cache.PortalCacheAttributes#getSize() - */ - public int getSize() { - return 0; - } - - /* - * (non-Javadoc) - * - * @see - * com.gentics.api.lib.cache.PortalCacheAttributes#setIsEternal(boolean) - */ - public void setIsEternal(boolean isEternal) {} - - /* - * (non-Javadoc) - * - * @see - * com.gentics.api.lib.cache.PortalCacheAttributes#setLastAccessDateToNow - * () - */ - public void setLastAccessDateToNow() { - lastAccessTime = System.currentTimeMillis(); - } - - /* - * (non-Javadoc) - * - * @see com.gentics.api.lib.cache.PortalCacheAttributes#setMaxAge(int) - */ - public void setMaxAge(int maxAge) { - this.maxAge = maxAge; - } - - /* - * (non-Javadoc) - * - * @see - * com.gentics.api.lib.cache.PortalCacheAttributes#setMaxIdleTime(int) - */ - public void setMaxIdleTime(int maxIdleTime) {} - - /* - * (non-Javadoc) - * - * @see com.gentics.api.lib.cache.PortalCacheAttributes#setSize(int) - */ - public void setSize(int size) {} - } - - /** - * This class is just for caching errors. - */ - public static class CachedError implements Serializable { - - /** - * Serial Version UID - */ - private static final long serialVersionUID = -3780962562170649534L; - - /** - * Singleton for the cached error - */ - protected final static CachedError instance = new CachedError(); - - /** - * Private constructor to prohibit external object creation - */ - private CachedError() {} - - /** - * Get the singleton - * - * @return singleton - */ - public static CachedError getInstance() { - return instance; - } - - /** - * Check whether the given object is a cached error - * - * @param o - * object to check - * @return true if it is a cached error, false if not - */ - public static boolean isCachedError(Object o) { - return (o instanceof CachedError); - } - } -} diff --git a/base-lib/src/main/java/com/gentics/portalnode/formatter/VelocityToolsImp.java b/base-lib/src/main/java/com/gentics/portalnode/formatter/VelocityToolsImp.java deleted file mode 100644 index fda171197f..0000000000 --- a/base-lib/src/main/java/com/gentics/portalnode/formatter/VelocityToolsImp.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * @author herbert - * @date 11.08.2006 - * @version $Id: VelocityToolsImp.java,v 1.1 2006-08-11 13:44:15 herbert Exp $ - */ -package com.gentics.portalnode.formatter; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.Map; - -import org.apache.velocity.tools.view.XMLToolboxManager; - -import com.gentics.api.portalnode.imp.AbstractGenticsImp; -import com.gentics.api.portalnode.imp.ImpException; -import com.gentics.lib.etc.StringUtils; -import com.gentics.lib.log.NodeLogger; - -/** - * A simple Imp which wraps the functionality of the - * Velocity Tools. - * http://jakarta.apache.org/velocity/tools/ - * - * @author herbert - * - */ -public class VelocityToolsImp extends AbstractGenticsImp { - public static final String CONFIG_PARAMETER = "configuration"; - NodeLogger logger; - private XMLToolboxManager toolboxManager; - private Map toolbox; - - public void init(String impId, Map parameters) throws ImpException { - super.init(impId, parameters); - logger = NodeLogger.getNodeLogger(this.getClass()); - String configFile = (String) parameters.get(CONFIG_PARAMETER); - InputStream config = null; - - if (configFile != null) { - configFile = StringUtils.resolveSystemProperties(configFile); - try { - config = new FileInputStream(configFile); - } catch (FileNotFoundException e) { - logger.error("Error while trying to load configFile from: {" + configFile + "} - trying to load from Portletapplication.", e); - } - } - if (config == null) { - config = getClass().getResourceAsStream("toolbox.xml"); - } - this.toolboxManager = new XMLToolboxManager(); - try { - toolboxManager.load(config); - toolbox = toolboxManager.getToolbox(null); - } catch (Exception e) { - logger.error("Error while trying to load toolbox.", e); - } - } - - /** - * Returns the corresponding tool from the toolbox. - * - * @param key name of the velocity tool as defined in toolbox.xml - * @return the specified Velocity Tool. - */ - public Object get(String key) { - try { - return toolbox.get(key); - } catch (Exception e) { - logger.error("Error while retrieving velocity tool {" + key + "}", e); - } - return null; - } -} diff --git a/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/JAXBDateFormatType.java b/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/JAXBDateFormatType.java deleted file mode 100644 index f6042c32ed..0000000000 --- a/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/JAXBDateFormatType.java +++ /dev/null @@ -1,227 +0,0 @@ - -package com.gentics.lib.formatter.dateformatter; - -import jakarta.xml.bind.JAXBElement; -import jakarta.xml.bind.annotation.XmlAccessType; -import jakarta.xml.bind.annotation.XmlAccessorType; -import jakarta.xml.bind.annotation.XmlAttribute; -import jakarta.xml.bind.annotation.XmlElementRef; -import jakarta.xml.bind.annotation.XmlElementRefs; -import jakarta.xml.bind.annotation.XmlSchemaType; -import jakarta.xml.bind.annotation.XmlType; -import jakarta.xml.bind.annotation.adapters.CollapsedStringAdapter; -import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - - -/** - *

Java-Klasse für dateFormatType complex type.

- * - *

Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.

- * - *
{@code
- * 
- *   
- *     
- *       
- *         
- *           
- *           
- *         
- *       
- *       
- *       
- *       
- *     
- *   
- * 
- * }
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "dateFormatType", propOrder = { - "dateOrTime" -}) -public class JAXBDateFormatType { - - @XmlElementRefs({ - @XmlElementRef(name = "date", type = JAXBElement.class, required = false), - @XmlElementRef(name = "time", type = JAXBElement.class, required = false) - }) - protected JAXBElement [] dateOrTime; - @XmlAttribute(name = "id", required = true) - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "token") - protected String id; - @XmlAttribute(name = "defaultdate") - protected String defaultdate; - @XmlAttribute(name = "defaulttime") - protected String defaulttime; - - /** - * - * @return - * array of - * {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - * {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - * - */ - public JAXBElement [] getDateOrTime() { - if (this.dateOrTime == null) { - return new JAXBElement[ 0 ] ; - } - JAXBElement [] retVal = new JAXBElement[this.dateOrTime.length] ; - System.arraycopy(this.dateOrTime, 0, retVal, 0, this.dateOrTime.length); - return (retVal); - } - - /** - * - * - * @return - * one of - * {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - * {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - * - */ - public JAXBElement getDateOrTime(int idx) { - if (this.dateOrTime == null) { - throw new IndexOutOfBoundsException(); - } - return this.dateOrTime[idx]; - } - - public int getDateOrTimeLength() { - if (this.dateOrTime == null) { - return 0; - } - return this.dateOrTime.length; - } - - /** - * - * - * @param values - * allowed objects are - * {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - * {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - * - */ - public void setDateOrTime(JAXBElement [] values) { - if (values == null) { - this.dateOrTime = null; - return ; - } - int len = values.length; - this.dateOrTime = ((JAXBElement []) new JAXBElement[len] ); - for (int i = 0; (i ) values[i]); - } - } - - /** - * - * - * @param value - * allowed object is - * {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - * {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - * - */ - public JAXBElement setDateOrTime(int idx, JAXBElement value) { - return this.dateOrTime[idx] = ((JAXBElement ) value); - } - - public boolean isSetDateOrTime() { - return ((this.dateOrTime!= null)&&(this.dateOrTime.length > 0)); - } - - public void unsetDateOrTime() { - this.dateOrTime = null; - } - - /** - * Ruft den Wert der id-Eigenschaft ab. - * - * @return - * possible object is - * {@link String } - * - */ - public String getId() { - return id; - } - - /** - * Legt den Wert der id-Eigenschaft fest. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setId(String value) { - this.id = value; - } - - public boolean isSetId() { - return (this.id!= null); - } - - /** - * Ruft den Wert der defaultdate-Eigenschaft ab. - * - * @return - * possible object is - * {@link String } - * - */ - public String getDefaultdate() { - return defaultdate; - } - - /** - * Legt den Wert der defaultdate-Eigenschaft fest. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setDefaultdate(String value) { - this.defaultdate = value; - } - - public boolean isSetDefaultdate() { - return (this.defaultdate!= null); - } - - /** - * Ruft den Wert der defaulttime-Eigenschaft ab. - * - * @return - * possible object is - * {@link String } - * - */ - public String getDefaulttime() { - return defaulttime; - } - - /** - * Legt den Wert der defaulttime-Eigenschaft fest. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setDefaulttime(String value) { - this.defaulttime = value; - } - - public boolean isSetDefaulttime() { - return (this.defaulttime!= null); - } - -} diff --git a/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/JAXBDateFormatsType.java b/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/JAXBDateFormatsType.java deleted file mode 100644 index 32fbf472fa..0000000000 --- a/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/JAXBDateFormatsType.java +++ /dev/null @@ -1,153 +0,0 @@ - -package com.gentics.lib.formatter.dateformatter; - -import jakarta.xml.bind.annotation.XmlAccessType; -import jakarta.xml.bind.annotation.XmlAccessorType; -import jakarta.xml.bind.annotation.XmlAttribute; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlSchemaType; -import jakarta.xml.bind.annotation.XmlType; -import jakarta.xml.bind.annotation.adapters.CollapsedStringAdapter; -import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - - -/** - *

Java-Klasse für dateFormatsType complex type.

- * - *

Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.

- * - *
{@code
- * 
- *   
- *     
- *       
- *         
- *       
- *       
- *     
- *   
- * 
- * }
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "dateFormatsType", propOrder = { - "dateFormat" -}) -public class JAXBDateFormatsType { - - @XmlElement(name = "date-format", type = DateFormatConfig.class) - protected JAXBDateFormatType[] dateFormat; - @XmlAttribute(name = "default", required = true) - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "token") - protected String _default; - - /** - * - * @return - * array of - * {@link JAXBDateFormatType } - * - */ - public JAXBDateFormatType[] getDateFormat() { - if (this.dateFormat == null) { - return new JAXBDateFormatType[ 0 ] ; - } - JAXBDateFormatType[] retVal = new DateFormatConfig[this.dateFormat.length] ; - System.arraycopy(this.dateFormat, 0, retVal, 0, this.dateFormat.length); - return (retVal); - } - - /** - * - * - * @return - * one of - * {@link JAXBDateFormatType } - * - */ - public JAXBDateFormatType getDateFormat(int idx) { - if (this.dateFormat == null) { - throw new IndexOutOfBoundsException(); - } - return this.dateFormat[idx]; - } - - public int getDateFormatLength() { - if (this.dateFormat == null) { - return 0; - } - return this.dateFormat.length; - } - - /** - * - * - * @param values - * allowed objects are - * {@link JAXBDateFormatType } - * - */ - public void setDateFormat(JAXBDateFormatType[] values) { - if (values == null) { - this.dateFormat = null; - return ; - } - int len = values.length; - this.dateFormat = ((DateFormatConfig[]) new DateFormatConfig[len] ); - for (int i = 0; (i 0)); - } - - public void unsetDateFormat() { - this.dateFormat = null; - } - - /** - * Ruft den Wert der default-Eigenschaft ab. - * - * @return - * possible object is - * {@link String } - * - */ - public String getDefault() { - return _default; - } - - /** - * Legt den Wert der default-Eigenschaft fest. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setDefault(String value) { - this._default = value; - } - - public boolean isSetDefault() { - return (this._default!= null); - } - -} diff --git a/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/JAXBDateOrTimeType.java b/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/JAXBDateOrTimeType.java deleted file mode 100644 index c1fa5f5286..0000000000 --- a/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/JAXBDateOrTimeType.java +++ /dev/null @@ -1,100 +0,0 @@ - -package com.gentics.lib.formatter.dateformatter; - -import jakarta.xml.bind.annotation.XmlAccessType; -import jakarta.xml.bind.annotation.XmlAccessorType; -import jakarta.xml.bind.annotation.XmlAttribute; -import jakarta.xml.bind.annotation.XmlSchemaType; -import jakarta.xml.bind.annotation.XmlType; -import jakarta.xml.bind.annotation.XmlValue; -import jakarta.xml.bind.annotation.adapters.CollapsedStringAdapter; -import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - - -/** - *

Java-Klasse für dateOrTimeType complex type.

- * - *

Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.

- * - *
{@code
- * 
- *   
- *     
- *       
- *     
- *   
- * 
- * }
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "dateOrTimeType", propOrder = { - "value" -}) -public class JAXBDateOrTimeType { - - @XmlValue - protected String value; - @XmlAttribute(name = "language", required = true) - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "token") - protected String language; - - /** - * Ruft den Wert der value-Eigenschaft ab. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } - - /** - * Legt den Wert der value-Eigenschaft fest. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } - - public boolean isSetValue() { - return (this.value!= null); - } - - /** - * Ruft den Wert der language-Eigenschaft ab. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLanguage() { - return language; - } - - /** - * Legt den Wert der language-Eigenschaft fest. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLanguage(String value) { - this.language = value; - } - - public boolean isSetLanguage() { - return (this.language!= null); - } - -} diff --git a/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/ObjectFactory.java b/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/ObjectFactory.java deleted file mode 100644 index 890b5db6c3..0000000000 --- a/base-lib/src/main/jaxb/com/gentics/lib/formatter/dateformatter/ObjectFactory.java +++ /dev/null @@ -1,107 +0,0 @@ - -package com.gentics.lib.formatter.dateformatter; - -import javax.xml.namespace.QName; -import jakarta.xml.bind.JAXBElement; -import jakarta.xml.bind.annotation.XmlElementDecl; -import jakarta.xml.bind.annotation.XmlRegistry; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the com.gentics.lib.formatter.dateformatter package. - *

An ObjectFactory allows you to programmatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - private static final QName _DateFormats_QNAME = new QName("", "date-formats"); - private static final QName _JAXBDateFormatTypeDate_QNAME = new QName("", "date"); - private static final QName _JAXBDateFormatTypeTime_QNAME = new QName("", "time"); - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.gentics.lib.formatter.dateformatter - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link JAXBDateFormatsType } - * - * @return - * the new instance of {@link JAXBDateFormatsType } - */ - public JAXBDateFormatsType createJAXBDateFormatsType() { - return new JAXBDateFormatsType(); - } - - /** - * Create an instance of {@link JAXBDateFormatType } - * - * @return - * the new instance of {@link JAXBDateFormatType } - */ - public JAXBDateFormatType createJAXBDateFormatType() { - return new DateFormatConfig(); - } - - /** - * Create an instance of {@link JAXBDateOrTimeType } - * - * @return - * the new instance of {@link JAXBDateOrTimeType } - */ - public JAXBDateOrTimeType createJAXBDateOrTimeType() { - return new JAXBDateOrTimeType(); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link JAXBDateFormatsType }{@code >} - * - * @param value - * Java instance representing xml element's value. - * @return - * the new instance of {@link JAXBElement }{@code <}{@link JAXBDateFormatsType }{@code >} - */ - @XmlElementDecl(namespace = "", name = "date-formats") - public JAXBElement createDateFormats(JAXBDateFormatsType value) { - return new JAXBElement<>(_DateFormats_QNAME, JAXBDateFormatsType.class, null, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - * - * @param value - * Java instance representing xml element's value. - * @return - * the new instance of {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - */ - @XmlElementDecl(namespace = "", name = "date", scope = JAXBDateFormatType.class) - public JAXBElement createJAXBDateFormatTypeDate(JAXBDateOrTimeType value) { - return new JAXBElement<>(_JAXBDateFormatTypeDate_QNAME, JAXBDateOrTimeType.class, JAXBDateFormatType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - * - * @param value - * Java instance representing xml element's value. - * @return - * the new instance of {@link JAXBElement }{@code <}{@link JAXBDateOrTimeType }{@code >} - */ - @XmlElementDecl(namespace = "", name = "time", scope = JAXBDateFormatType.class) - public JAXBElement createJAXBDateFormatTypeTime(JAXBDateOrTimeType value) { - return new JAXBElement<>(_JAXBDateFormatTypeTime_QNAME, JAXBDateOrTimeType.class, JAXBDateFormatType.class, value); - } - -} diff --git a/base-lib/src/main/jaxb/date-formatPrime.xsd b/base-lib/src/main/jaxb/date-formatPrime.xsd deleted file mode 100644 index a05ac26c0e..0000000000 --- a/base-lib/src/main/jaxb/date-formatPrime.xsd +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/base-lib/src/main/resources/com/gentics/portalnode/formatter/toolbox.xml b/base-lib/src/main/resources/com/gentics/portalnode/formatter/toolbox.xml deleted file mode 100644 index 9a14ab7cbe..0000000000 --- a/base-lib/src/main/resources/com/gentics/portalnode/formatter/toolbox.xml +++ /dev/null @@ -1,96 +0,0 @@ - - - - true - - version - 1.1 - - - isSimple - true - - - foo - this is foo. - - - bar - this is bar. - - - map - session - java.util.HashMap - - - date - application - org.apache.velocity.tools.generic.DateTool - - - - - - - math - application - org.apache.velocity.tools.generic.MathTool - - - number - application - org.apache.velocity.tools.generic.NumberTool - - - render - application - org.apache.velocity.tools.generic.RenderTool - - - esc - application - org.apache.velocity.tools.generic.EscapeTool - - - alternator - application - org.apache.velocity.tools.generic.AlternatorTool - - - parser - org.apache.velocity.tools.generic.ValueParser - - - list - application - org.apache.velocity.tools.generic.ListTool - - - sort - org.apache.velocity.tools.generic.SortTool - - - iterator - request - org.apache.velocity.tools.generic.IteratorTool - - diff --git a/base-lib/src/test/java/com/gentics/lib/formatter/GenticsDateFormatterTest.java b/base-lib/src/test/java/com/gentics/lib/formatter/GenticsDateFormatterTest.java deleted file mode 100644 index 2cceba0dfd..0000000000 --- a/base-lib/src/test/java/com/gentics/lib/formatter/GenticsDateFormatterTest.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.gentics.lib.formatter; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; - -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import com.gentics.api.portalnode.imp.ImpException; -import com.gentics.contentnode.tests.category.BaseLibTest; -import com.gentics.lib.jaxb.JAXBHelper; - -import jakarta.xml.bind.JAXBException; - -@Category(BaseLibTest.class) -public class GenticsDateFormatterTest { - - private static GenericGenticsDateFormatter formatter; - private final static String IMP_NAME = "bogus"; - private final static String DATE_FORMAT = "dd MMM yyyy HH:mm:ss"; - private final static String DATE_RESULT = "01 Jan 1970 01:00:00"; - private final static long FIXED_DATE_IN_2014 = 1397478595585L; - - @BeforeClass - public static void setupOnce() throws JAXBException, ImpException { - JAXBHelper.init(null); - formatter = new GenericGenticsDateFormatter(); - Map settings = new HashMap(); - - String confPath = GenticsDateFormatterTest.class.getResource("dateformatter.xml").getFile(); - settings.put(GenericGenticsDateFormatter.CONFIGPATH_PARAM, confPath); - - formatter.init(IMP_NAME, settings); - - } - - @Test - public void testInvalidFormat() { - String dateString = formatter.format(new Integer(2)); - assertNull(dateString); - } - - @Test - @Ignore("Test unstable due to local settings") - public void simpleFormatterTest() throws ImpException, JAXBException { - assertNotNull(formatter.format()); - String dateResult = "Thu Jan 01 01:00:00 CET 1970"; - assertEquals("The result should match the expected format", dateResult, formatter.format(new Date(3))); - assertEquals("The result should match the expected format", dateResult, formatter.format((Object) new Date(3))); - assertNotNull(formatter.format(DATE_FORMAT)); - - assertEquals("The result should match the expected format", DATE_RESULT, formatter.format((Object) new Date(1), DATE_FORMAT)); - assertNotNull(formatter.format(DATE_FORMAT, "DE")); - assertEquals("The result should match the expected format", DATE_RESULT, formatter.format(new Date(1), DATE_FORMAT, "DE")); - assertEquals("The result should match the expected format", DATE_RESULT, formatter.format((Object) new Date(1), DATE_FORMAT, "DE")); - } - - @Test - @Ignore("Test unstable due to local settings") - public void testFormatDate() { - assertNotNull(formatter.formatDate()); - String date = "Thu Jan 01 01:00:00 CET 1970"; - assertEquals("The dates should match.", date, formatter.formatDate(new Date(1))); - String input = "1.1.2014 12:30"; - assertEquals("Input should match the output.", input, formatter.formatDate(input)); - - assertEquals("The dates should match.", DATE_RESULT, formatter.formatDate(new Date(1), DATE_FORMAT)); - assertEquals("The dates should match.", DATE_RESULT, formatter.formatDate((Object) new Date(1), DATE_FORMAT)); - assertNotNull(formatter.formatDate(DATE_FORMAT, "EN")); - assertEquals("The dates should match.", DATE_RESULT, formatter.formatDate(new Date(1), DATE_FORMAT, "EN")); - assertEquals("The dates should match.", DATE_RESULT, formatter.formatDate((Object) new Date(1), DATE_FORMAT, "EN")); - } - - @Test - public void testFromTimestamp() { - Date date = formatter.fromTimestamp(1000); - assertEquals("Both dates should match", new Date(1000 * 1000).getTime(), date.getTime()); - date = formatter.fromTimestamp("1000"); - assertEquals("Both dates should match", new Date(1000 * 1000).getTime(), date.getTime()); - } - - @Test - public void testParseDate() { - String inputDate = "2014-03-12 12:30"; - Date date = formatter.parse(null); - assertNull(date); - date = formatter.parseDate(inputDate, DATE_FORMAT, "EN"); - assertNull(date); - date = formatter.parse(inputDate, DATE_FORMAT, "DE"); - assertNull(date); - } - - @Test - public void testDateDiff() { - - GenericGenticsDateFormatter formatter = new GenericGenticsDateFormatter(); - long diff = formatter.dateDiff(new Date(0), new Date(1)); - assertEquals("Diff does not match", 1, diff); - diff = formatter.dateDiff((Object) new Date(1), (Object) new Date(2)); - assertEquals("diff does not match", 1, diff); - - diff = formatter.dateDiff(new Date(1), new Date(FIXED_DATE_IN_2014), "y"); - assertEquals("Years since 1970 do not match", 44, diff); - diff = formatter.dateDiff(new Date(1), new Date(FIXED_DATE_IN_2014), "M"); - assertEquals("Months since 1970 do not match", 531, diff); - diff = formatter.dateDiff(new Date(1), new Date(FIXED_DATE_IN_2014), "w"); - assertEquals("Weeks since 1970 do not match", 2310, diff); - diff = formatter.dateDiff(new Date(1), new Date(FIXED_DATE_IN_2014), "d"); - assertEquals("Days since 1970 do not match", 16174, diff); - diff = formatter.dateDiff(new Date(1), new Date(FIXED_DATE_IN_2014), "h"); - assertEquals("Hours since 1970 do not match", 388188, diff); - diff = formatter.dateDiff(new Date(1), new Date(FIXED_DATE_IN_2014), "m"); - assertEquals("Minutes since 1970 do not match", 23291309, diff); - diff = formatter.dateDiff(new Date(1), new Date(FIXED_DATE_IN_2014), "s"); - assertEquals("Seconds since 1970 do not match", 1397478595, diff); - diff = formatter.dateDiff((Object) new Date(0), (Object) new Date(FIXED_DATE_IN_2014), "M"); - assertEquals("Months since 1970 do not match.", 531, diff); - diff = formatter.dateDiff((Object) new Date(0), (Object) new Date(FIXED_DATE_IN_2014), "y"); - assertEquals("44 Years have past since 1970.", 44, diff); - } - - @Test - public void testMisc() { - assertEquals("The impname should match the name we choose during init.", IMP_NAME, formatter.getImpId()); - - TimeZone tz = TimeZone.getTimeZone("Europe/Vienna"); - int offset = (int) ((Calendar.getInstance().get(Calendar.ZONE_OFFSET) + Calendar.getInstance().get(Calendar.DST_OFFSET)) / 60 / 60 / 1000); - - assertEquals("+0" + offset + ":00", formatter.getRfc3339Timezone()); - assertEquals("+0" + offset + ":00", formatter.getRfc3339Timezone(new Date())); - - assertFalse("The given object is not a date object", formatter.isDate("1.1.2014")); - assertTrue("The given object is a date", formatter.isDate(new Date(1))); - assertFalse("The given object is not a date", formatter.isDate(new Integer(1))); - } - - @Test - public void testCustomFormat() { - Date now = new Date(); - new SimpleDateFormat("dd", Locale.forLanguageTag("en")); - - assertThat(formatter.format(now, "custom", "en")) - .describedAs("Date formatter with customer formatter in en") - .isEqualTo(new SimpleDateFormat("dd", Locale.forLanguageTag("en")).format(now) + " " - + new SimpleDateFormat("hh", Locale.forLanguageTag("en")).format(now)); - assertThat(formatter.format(now, "custom", "de")).describedAs("Date formatter with customer formatter in de") - .isEqualTo(new SimpleDateFormat("MM", Locale.forLanguageTag("de")).format(now) + " " - + new SimpleDateFormat("ss", Locale.forLanguageTag("de")).format(now)); - } -} diff --git a/base-lib/src/test/java/com/gentics/node/tests/formatter/BlockingHttpConnectionHandler.java b/base-lib/src/test/java/com/gentics/node/tests/formatter/BlockingHttpConnectionHandler.java deleted file mode 100644 index 97295ac9df..0000000000 --- a/base-lib/src/test/java/com/gentics/node/tests/formatter/BlockingHttpConnectionHandler.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.gentics.node.tests.formatter; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.net.Socket; -import java.util.Scanner; - -import com.gentics.testutils.http.IHttpServerConnectionHandler; - -public class BlockingHttpConnectionHandler implements IHttpServerConnectionHandler { - - private long nMilisecondsToWait = 0; - - /** - * Create a new blocking http connection handler that will block the connection for the given amount of time. - * - * @param nMilisecondsToWait - */ - public BlockingHttpConnectionHandler(long nMilisecondsToWait) { - this.nMilisecondsToWait = nMilisecondsToWait; - } - - /** - * Set the amount of miliseconds which the connection should be stalled - * - * @param time - */ - public void setBlockingTime(long nMilisecondsToWait) { - this.nMilisecondsToWait = nMilisecondsToWait; - } - - public void handleConnection(Socket client) throws IOException { - - InputStream ins = client.getInputStream(); - OutputStream out = client.getOutputStream(); - - System.out.println("Handling Connection - Starting Block"); - try { - Thread.sleep(nMilisecondsToWait); - } catch (InterruptedException e) { - - e.printStackTrace(); - } - System.out.println("Handling Connection - Blocking finished"); - - Scanner in = new Scanner(ins); - PrintWriter output = new PrintWriter(out, true); - - String cmd = in.nextLine(); - - output.println("HTTP/1.0 200 OK"); - output.println(""); - output.println("Here you go: " + cmd); - - out.close(); - ins.close(); - } - -} - diff --git a/base-lib/src/test/java/com/gentics/node/tests/formatter/UrlIncludeImpTest.java b/base-lib/src/test/java/com/gentics/node/tests/formatter/UrlIncludeImpTest.java deleted file mode 100644 index 10925838d3..0000000000 --- a/base-lib/src/test/java/com/gentics/node/tests/formatter/UrlIncludeImpTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.gentics.node.tests.formatter; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import com.gentics.contentnode.tests.category.BaseLibTest; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.gentics.api.lib.exception.NodeException; -import com.gentics.portalnode.formatter.URLIncludeImp; -import com.gentics.testutils.http.HttpServer; -import org.junit.experimental.categories.Category; - -@Category(BaseLibTest.class) -public class UrlIncludeImpTest { - - public final static int HTTPPORT = 0; - public final static long BLOCKTIME = 8000; - public HttpServer server; - public BlockingHttpConnectionHandler handler; - public int cacheLifeTime = 20; - public String defaultContent = "This is the default content"; - String url = ""; - - @Before - public void setup() throws IOException { - - server = new HttpServer(HTTPPORT); - handler = new BlockingHttpConnectionHandler(1000); - server.setConnectionHandler(handler); - new Thread(server).start(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - url = getServerURL(); - } - - @After - public void tearDown() throws IOException { - server.stop(); - } - - @Test - public void testIncludeImpTimeout() throws NodeException { - - URLIncludeImp urlImp = new URLIncludeImp(); - - int soTimeout = 200; - - String output = urlImp.includeUrl(url, cacheLifeTime, soTimeout, defaultContent); - - assertEquals("We expected the default content since the connection should have been failed.", defaultContent, output); - - // Wait some more time to give the blocking http connection handler time to finish - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - public String getServerURL() { - System.out.println("Selected ServerPort:" + server.getPort()); - String url = "http://localhost:" + server.getPort(); - - return url; - } - - @Test - public void testIncludeImpMultithreading() throws NodeException { - - final URLIncludeImp urlImp = new URLIncludeImp(); - - final int soTimeout = 200; - - for (int i = 0; i < 2000; i++) { - System.out.println("Starting thread: " + i); - - if (i % 5 == 0) { - System.out.println("Waiting"); - // Wait some more time to give the blocking http connection handler time to finish - try { - Thread.sleep(5); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - new Thread(new Runnable() { - - public void run() { - try { - String output = urlImp.includeUrl(url, cacheLifeTime, soTimeout, defaultContent); - - System.out.println(output); - } catch (NodeException e) { - e.printStackTrace(); - } - } - }).start(); - - } - - } - - /** - * Test the url imp include with a higher socket timeout value. - * - * @throws NodeException - */ - @Test - public void testIncludeImpTimeout2() throws NodeException { - - URLIncludeImp urlImp = new URLIncludeImp(); - int soTimeout = 30000; - - handler.setBlockingTime(0); - url += "?blaa"; - String output = urlImp.includeUrl(url, cacheLifeTime, soTimeout, defaultContent); - - assertEquals("We expected the acctual server response since the connection should be fine.", "Here you go: GET /?blaa HTTP/1.1\n", output); - System.out.println(output); - - // Wait some more time to give the blocking http connection handler time to finish - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } -} diff --git a/base-lib/src/test/resources/com/gentics/lib/formatter/dateformatter.xml b/base-lib/src/test/resources/com/gentics/lib/formatter/dateformatter.xml deleted file mode 100644 index e7572d2950..0000000000 --- a/base-lib/src/test/resources/com/gentics/lib/formatter/dateformatter.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - dd - - MM - - - diff --git a/cms-core/src/main/java/com/gentics/contentnode/factory/PartTypeFactory.java b/cms-core/src/main/java/com/gentics/contentnode/factory/PartTypeFactory.java index a1f25b599d..152afab4ae 100644 --- a/cms-core/src/main/java/com/gentics/contentnode/factory/PartTypeFactory.java +++ b/cms-core/src/main/java/com/gentics/contentnode/factory/PartTypeFactory.java @@ -9,6 +9,8 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.Optional; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import com.gentics.api.contentnode.parttype.ExtensiblePartType; @@ -18,6 +20,7 @@ import com.gentics.contentnode.object.Value; import com.gentics.contentnode.object.parttype.ExtensiblePartTypeWrapper; import com.gentics.contentnode.object.parttype.PartType; +import com.gentics.contentnode.object.parttype.UnavailablePartType; import com.gentics.lib.etc.StringUtils; /** @@ -25,6 +28,15 @@ * parttype-id. */ public class PartTypeFactory { + /** + * Type IDs of optional part types (33: VelocityPartType, 34: BreadcrumbPartType, 35: NavigationPartType) + */ + protected final static Set OPTIONAL_TYPE_IDS = Set.of(33, 34, 35); + + /** + * Type IDs of optional part types, which are valueless + */ + protected final static Set OPTIONAL_VALUELESS_IDS = Set.of(33, 34, 35); private static PartTypeFactory factory; @@ -66,6 +78,10 @@ public boolean isValueless(int typeId) throws NodeException { public boolean isValueless(int typeId, boolean failIfPartTypeNotFound) throws NodeException { PartTypeInfo partTypeInfo = getPartTypeInfo(typeId, failIfPartTypeNotFound); + if (OPTIONAL_VALUELESS_IDS.contains(typeId)) { + return true; + } + // check if classname is set if (null == partTypeInfo) { return true; @@ -113,9 +129,10 @@ private PartTypeInfo getPartTypeInfo(int partTypeId, boolean failIfNotFound) thr res = p.executeQuery(); if (res.next()) { - Class partTypeClass = null; + Class partTypeClass = null; String partTypeClassName = res.getString("javaclass"); String partTypeName = res.getString("name"); + String originalClassName = null; res.close(); @@ -127,10 +144,15 @@ private PartTypeInfo getPartTypeInfo(int partTypeId, boolean failIfNotFound) thr try { partTypeClass = Class.forName(partTypeClassName); } catch (ClassNotFoundException e) { - throw new NodeException("No class for partType " + partTypeId, e); + if (OPTIONAL_TYPE_IDS.contains(partTypeId)) { + partTypeClass = UnavailablePartType.class; + originalClassName = partTypeClassName; + } else { + throw new NodeException("No class for partType " + partTypeId, e); + } } - partTypeInfo = new PartTypeInfo(partTypeClass, partTypeName); + partTypeInfo = new PartTypeInfo(partTypeClass, partTypeName, originalClassName); partTypeInfoCache.put(partTypeId, partTypeInfo); return partTypeInfo; } else { @@ -184,6 +206,13 @@ public PartType getPartType(int typeId, Value value) throws NodeException { if (!PartType.class.isAssignableFrom(partTypeInfo.getClazz())) {// TODO error handling } + // special handling for UnavailablePartType + if (partTypeInfo.getClazz() == UnavailablePartType.class) { + PartType partType = new UnavailablePartType(value, partTypeInfo.getOriginalClassName()); + partType.setAnnotationClass(partTypeInfo.getAnnotationClass()); + return partType; + } + try { // get the desired constructor Constructor constructor = partTypeInfo.getClazz().getConstructor(new Class[] { Value.class}); @@ -221,6 +250,16 @@ public boolean matches(Part part, PartType partType) throws NodeException { } } + /** + * Check whether the part type with given ID is available + * @param typeId type ID + * @return true iff available + * @throws NodeException + */ + public boolean isAvailable(int typeId) throws NodeException { + return Optional.ofNullable(getPartTypeInfo(typeId, false)).map(PartTypeInfo::isAvailable).orElse(false); + } + /** * Class for parttype info (class and annotation name) */ @@ -236,14 +275,21 @@ protected class PartTypeInfo { */ protected String annotationClass; + /** + * If the {@link #clazz} is {@link UnavailablePartType}, this string specifies the original class name (which is unavailable) + */ + protected String originalClassName; + /** * Create an instance * @param clazz class * @param name name (will be transformed to the annotation class) + * @param originalClassName optional original class name */ - public PartTypeInfo(Class clazz, String name) { + public PartTypeInfo(Class clazz, String name, String originalClassName) { this.clazz = clazz; this.annotationClass = buildAnnotationClass(name); + this.originalClassName = originalClassName; } /** @@ -273,5 +319,21 @@ public Class getClazz() { public String getAnnotationClass() { return annotationClass; } + + /** + * Get the original class name + * @return original class name + */ + public String getOriginalClassName() { + return originalClassName; + } + + /** + * Check whether the part type is available + * @return true iff available + */ + public boolean isAvailable() { + return !clazz.isAssignableFrom(UnavailablePartType.class); + } } } diff --git a/cms-core/src/main/java/com/gentics/contentnode/formatter/CNDateFormatterImp.java b/cms-core/src/main/java/com/gentics/contentnode/formatter/CNDateFormatterImp.java deleted file mode 100644 index d898d0ec70..0000000000 --- a/cms-core/src/main/java/com/gentics/contentnode/formatter/CNDateFormatterImp.java +++ /dev/null @@ -1,516 +0,0 @@ -package com.gentics.contentnode.formatter; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Map; - -import com.gentics.api.portalnode.imp.AbstractGenticsImp; -import com.gentics.api.portalnode.imp.ImpException; -import com.gentics.contentnode.etc.ContentNodeDate; -import com.gentics.contentnode.factory.Transaction; -import com.gentics.contentnode.factory.TransactionManager; -import com.gentics.contentnode.object.Page; -import com.gentics.contentnode.render.RenderableResolvable; -import com.gentics.contentnode.resolving.StackResolvable; -import com.gentics.lib.formatter.dateformatter.DateFormatConfig; - -/** - * New and better Version if the GenticsDateFormatter. Can be used to format - * dates in Portal.Node and Content.Node - */ -public class CNDateFormatterImp extends AbstractGenticsImp { - - /** - * some basic definitions needed for calculations - */ - public static final int MINUTE = 60; - - public static final int HOUR = 60 * MINUTE; - - public static final int DAY = 24 * HOUR; - - public static final int WEEK = 7 * DAY; - - public static final int MONTH = 30 * DAY; - - public static final int YEAR = 365 * DAY; - - /** - * - */ - public CNDateFormatterImp() { - } - - /* - * (non-Javadoc) - * - * @see - * com.gentics.api.portalnode.imp.AbstractGenticsImp#init(java.lang.String, - * java.util.Map) - */ - public void init(String impId, Map parameters) throws ImpException { - super.init(impId, parameters); - } - - /** - * Format the current date in the given format and the current language - * - * @param format - * format - * @return formatted date - */ - public String format(String format) { - return format(new Date(), format, getCurrentLanguageCode()); - } - - /** - * @param format - * @deprecated use {@link #format(String)} instead - * @return - */ - public String formatDate(String format) { - return format(format); - } - - /** - * Format the current date in the given format and language - * - * @param format - * format - * @param languageCode - * language code - * @return formatted date - */ - public String format(String format, String languageCode) { - return format(new Date(), format, languageCode); - } - - /** - * @param format - * @param languageCode - * @deprecated use {@link #format(String, String)} instead - * @return - */ - public String formatDate(String format, String languageCode) { - return format(format, languageCode); - } - - /** - * Format the given date in the given format and current language - * - * @param date - * date - * @param format - * format - * @return formatted date - */ - public String format(Date date, String format) { - return format(date, format, getCurrentLanguageCode()); - } - - /** - * - * @param date - * @param format - * @deprecated use {@link #format(Date, String)} instead - * @return - */ - public String formatDate(Date date, String format) { - return format(date, format); - } - - /** - * Format the given date in the given format and language - * - * @param date - * date - * @param format - * format - * @param languageCode - * language - * @return formatted date - */ - public String format(Date date, String format, String languageCode) { - DateFormat dateFormat = DateFormatConfig.createDateTimeFormat(format, DateFormatConfig.getLocale(languageCode)); - return dateFormat.format(date); - } - - /** - * @param date - * @param format - * @param languageCode - * @deprecated use {@link #format(Date, String, String)} instead - * @return - */ - public String formatDate(Date date, String format, String languageCode) { - return format(date, format, languageCode); - } - - /** - * Format the given date in the given format and current language - * - * @param date - * date - * @param format - * format - * @return formatted date - */ - public String format(Object date, String format) { - return format(toDate(date), format); - } - - /** - * - * @param date - * @param format - * @deprecated use {@link #format(Object, String)} instead - * @return - */ - public String formatDate(Object date, String format) { - return format(date, format); - } - - /** - * Format the given date in the given format and language - * - * @param date - * date - * @param format - * format - * @param languageCode - * language - * @return formatted date - */ - public String format(Object date, String format, String languageCode) { - return format(toDate(date), format, languageCode); - } - - /** - * - * @param date - * @param format - * @param languageCode - * @deprecated use {@link #format(Object, String, String)} instead - * @return - */ - public String formatDate(Object date, String format, String languageCode) { - return format(date, format, languageCode); - } - - /** - * parse the given string to a date (in the default format) and return the - * date or null if the string is not parsable - * - * @param formattedDate - * formatted date to be parsed - * @return date object or null - */ - public Date parse(String formattedDate) { - return parse(formattedDate, null); - } - - /** - * - * @param formattedDate - * @deprecated use {@link #parse(String)} instead - * @return - */ - public Date parseDate(String formattedDate) { - return parse(formattedDate); - } - - /** - * parse the given string to a date in the given format and return the date - * or null if the string is unparseable - * - * @param formattedDate - * formatted date to be parsed - * @param dateFormat - * date format or null for the default format - * @return date object or null - */ - public Date parse(String formattedDate, String dateFormat) { - return parse(formattedDate, dateFormat, getCurrentLanguageCode()); - } - - /** - * - * @param formattedDate - * @param dateFormat - * @deprecated use {@link #parse(String, String))} instead - * @return - */ - public Date parseDate(String formattedDate, String dateFormat) { - return parse(formattedDate, dateFormat); - } - - /** - * Parse the given string to a date in the given format and given - * languagecode - * - * @param formattedDate - * formatted date to be parsed - * @param format - * date format or null for the default format - * @param languageCode - * language code - * @return date object or null - */ - public Date parse(String formattedDate, String format, String languageCode) { - - try { - DateFormat dateFormat = DateFormatConfig.createDateTimeFormat(format, DateFormatConfig.getLocale(languageCode)); - return dateFormat.parse(formattedDate); - } catch (ParseException e) { - logger.error("Error while parsing {" + formattedDate + "} into a date with format {" + format + "}", e); - return null; - } - } - - /** - * - * @param formattedDate - * @param format - * @param languageCode - * @deprecated use {@link #parse(String, String, String)} instead - * @return - */ - public Date parseDate(String formattedDate, String format, String languageCode) { - return parse(formattedDate, format, languageCode); - } - - /** - * generate a date from a timestamp - * - * @param timestamp - * timestamp - * @return date object - */ - public Date fromTimestamp(int timestamp) { - return new Date((long) timestamp * 1000L); - } - - /** - * generate a date from a timestamp - * - * @param timestamp - * timestamp (as string) - * @return date object - */ - public Date fromTimestamp(String timestamp) { - try { - return new Date(Long.parseLong(timestamp) * 1000L); - } catch (NumberFormatException ex) { - return null; - } - } - - /** - * check whether the object is a date or not - * - * @param object - * object to check - * @return true when the object is a date, false if not - */ - public boolean isDate(Object object) { - return object instanceof Date; - } - - /** - * Calculate the difference between the given dates in the given time unit. - * Possible time units are: - *

    - *
  • y for years
  • - *
  • M for months
  • - *
  • w for weeks
  • - *
  • d for days
  • - *
  • h for hours
  • - *
  • m for minutes
  • - *
  • s for seconds
  • - *
  • ms for milliseconds (the default)
  • - *
- * - * @param fromDate - * first date (should be earlier) - * @param toDate - * second date (should be later) - * @param unit - * the time unit for output of the date difference - * @return difference in the given unit - */ - public long dateDiff(Date fromDate, Date toDate, String unit) { - long msDiff = toDate.getTime() - fromDate.getTime(); - long diff = msDiff; - - if ("y".equals(unit)) { - // difference in years - Calendar toCal = Calendar.getInstance(); - - toCal.setTime(toDate); - Calendar fromCal = Calendar.getInstance(); - - fromCal.setTime(fromDate); - diff = toCal.get(Calendar.YEAR) - fromCal.get(Calendar.YEAR); - // now check whether the to-day is earlier in the year as the - // from-day - toCal.set(Calendar.YEAR, fromCal.get(Calendar.YEAR)); - if (toCal.getTime().before(fromCal.getTime())) { - diff -= 1; - } - } else if ("M".equals(unit)) { - // difference in months - Calendar toCal = Calendar.getInstance(); - - toCal.setTime(toDate); - Calendar fromCal = Calendar.getInstance(); - - fromCal.setTime(fromDate); - diff = (toCal.get(Calendar.YEAR) - fromCal.get(Calendar.YEAR)) * 12; - // now check whether the to-day is earlier in the year as the - // from-day - toCal.set(Calendar.YEAR, fromCal.get(Calendar.YEAR)); - diff += (toCal.get(Calendar.MONTH) - fromCal.get(Calendar.MONTH)); - toCal.set(Calendar.MONTH, fromCal.get(Calendar.MONTH)); - if (toCal.getTime().before(fromCal.getTime())) { - diff -= 1; - } - } else if ("w".equals(unit)) { - // difference in weeks - diff = msDiff / (7 * 24 * 60 * 60 * 1000); - } else if ("d".equals(unit)) { - // difference in days - diff = msDiff / (24 * 60 * 60 * 1000); - } else if ("h".equals(unit)) { - // difference in hours - diff = msDiff / (60 * 60 * 1000); - } else if ("m".equals(unit)) { - // difference in minutes - diff = msDiff / (60 * 1000); - } else if ("s".equals(unit)) { - // difference in seconds - diff = msDiff / 1000; - } - return diff; - } - - /** - * Other version of the {@link #dateDiff(Date, Date, String)} Method - * - * @param fromDate - * first date - * @param toDate - * second date - * @param unit - * the time unit for output of the date difference - * @return difference in the given unit - */ - public long dateDiff(Object fromDate, Object toDate, String unit) { - return dateDiff(toDate(fromDate), toDate(toDate), unit); - } - - /** - * Calculate the difference between the given dates in milliseconds. - * - * @param fromDate - * first date (should be earlier) - * @param toDate - * second date (should be later) - * @return difference in milliseconds - */ - public long dateDiff(Date fromDate, Date toDate) { - return dateDiff(fromDate, toDate, "ms"); - } - - /** - * Other version of the {@link #dateDiff(Date, Date)} Method - * - * @param fromDate - * first date (should be earlier) - * @param toDate - * second date (should be later) - * @return difference in milliseconds - */ - public long dateDiff(Object fromDate, Object toDate) { - return dateDiff(toDate(fromDate), toDate(toDate)); - } - - /** - * Transform the ContentNodeDate to a Date - * - * @param date - * ContentNodeDate - * @return Date - */ - protected static Date toDate(Object date) { - if (date == null) { - return null; - } - - // unwrap the object (if wrapped) - if (date instanceof RenderableResolvable) { - date = ((RenderableResolvable) date).getWrappedObject(); - } - - if (date instanceof Date) { - return (Date) date; - } else if (date instanceof ContentNodeDate) { - return new Date(((ContentNodeDate) date).getTimestamp().longValue() * 1000L); - } else if (date instanceof Integer) { - return new Date((Integer) date); - } else { - return null; - } - } - - /** - * Get the current language code or null - * - * @return current language code or null - */ - protected String getCurrentLanguageCode() { - - // try to get the currently rendered page (if any) - try { - Transaction t = TransactionManager.getCurrentTransaction(); - StackResolvable rootObject = t.getRenderType().getRenderedRootObject(); - if (rootObject instanceof Page) { - return ((Page) rootObject).getLanguage().getCode(); - } - } catch (Exception e) {// hmm, silently ignore these exceptions? - } - return null; - } - - /** - * Get the timezone of the current date in RFC3339 format. See RFC 3339 for details. - * - * @return timezone of the current time in RFC3339 format. - */ - public String getRfc3339Timezone() { - - Date date = new Date(); - - return getRfc3339Timezone(date); - } - - /** - * Get the timezone of the given date in RFC3339 format. See RFC 3339 for details. - * - * @param date - * date - * @return timezone of the given date in RFC3339 format. - */ - public String getRfc3339Timezone(Object date) { - Date foo = toDate(date); - SimpleDateFormat format = new SimpleDateFormat("Z"); - String rfc3339tz = format.format(foo).substring(0, 3) + ":" + format.format(foo).substring(3); - - return rfc3339tz; - } - -} diff --git a/cms-core/src/main/java/com/gentics/contentnode/logger/VelocityLogSystem.java b/cms-core/src/main/java/com/gentics/contentnode/logger/VelocityLogSystem.java deleted file mode 100644 index 26b8549afe..0000000000 --- a/cms-core/src/main/java/com/gentics/contentnode/logger/VelocityLogSystem.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * @author herbert - * @date Mar 20, 2008 - * @version $Id: VelocityLogSystem.java,v 1.3 2010-09-28 17:01:30 norbert Exp $ - */ -package com.gentics.contentnode.logger; - -import org.apache.velocity.runtime.RuntimeServices; -import org.apache.velocity.runtime.log.LogSystem; - -import com.gentics.api.lib.exception.NodeException; -import com.gentics.contentnode.factory.Transaction; -import com.gentics.contentnode.factory.TransactionException; -import com.gentics.contentnode.factory.TransactionManager; -import com.gentics.contentnode.render.RenderResult; -import com.gentics.contentnode.render.RenderType; -import com.gentics.contentnode.resolving.StackResolver; -import com.gentics.lib.log.NodeLogger; - -public class VelocityLogSystem implements LogSystem { - - NodeLogger logger = NodeLogger.getNodeLogger(VelocityLogSystem.class); - - public void init(RuntimeServices rs) throws Exception { - // TODO Auto-generated method stub - // runtime.log.logsystem.class - logger.info("Initializing custom velocity log system."); - } - - /** - * trys to log the given message into the render result - * (so users can see them in the debug stream in the CMS. - * if we are not in a render phase, this method returns false - * and will not log anything.) - */ - private boolean internalLogRenderResult(int level, String message) { - try { - Transaction t = TransactionManager.getCurrentTransaction(); - - if (t == null) { - return false; - } - - RenderType renderType = t.getRenderType(); - - String postfix = null; - - if (renderType != null) { - StackResolver stack = renderType.getStack(); - - postfix = stack.getUIReadableStack(); - } - - RenderResult result = t.getRenderResult(); - - if (result == null) { - return false; - } - - if (postfix != null) { - message = new StringBuffer("Velocity " + logLevelToString(level) + " while rendering: ").append(postfix).append(" --- ").append(message).toString(); - } - - switch (level) { - case LogSystem.WARN_ID: - result.warn(VelocityLogSystem.class, message); - break; - - case LogSystem.INFO_ID: - result.info(VelocityLogSystem.class, message); - break; - - case LogSystem.DEBUG_ID: - result.debug(VelocityLogSystem.class, message); - break; - - case LogSystem.ERROR_ID: - result.error(VelocityLogSystem.class, message); - break; - - default: - result.debug(VelocityLogSystem.class, message); - break; - } - } catch (TransactionException e) { - return false; - } catch (NodeException e) { - logger.debug("Error while trying to log message into render result.", e); - return false; - } - return true; - } - - private String logLevelToString(int level) { - switch (level) { - case LogSystem.WARN_ID: - return "warning"; - - case LogSystem.INFO_ID: - return "info"; - - case LogSystem.DEBUG_ID: - return "debug"; - - case LogSystem.ERROR_ID: - return "error"; - - default: - return "unknown"; - } - } - - public void logVelocityMessage(int level, String message) { - // first try to log into the render result .. - if (!internalLogRenderResult(level, message)) { - switch (level) { - case LogSystem.WARN_ID: - logger.warn(message); - break; - - case LogSystem.INFO_ID: - logger.info(message); - break; - - case LogSystem.DEBUG_ID: - logger.debug(message); - break; - - case LogSystem.ERROR_ID: - logger.error(message); - break; - - default: - logger.debug(message); - break; - } - } - } - -} diff --git a/cms-core/src/main/java/com/gentics/contentnode/object/parttype/AbstractVelocityCompatibilityPartType.java b/cms-core/src/main/java/com/gentics/contentnode/object/parttype/AbstractVelocityCompatibilityPartType.java deleted file mode 100644 index 9cf5256925..0000000000 --- a/cms-core/src/main/java/com/gentics/contentnode/object/parttype/AbstractVelocityCompatibilityPartType.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * @author alexander - * @date 12.04.2007 - * @version $Id: AbstractVelocityCompatibilityPartType.java,v 1.1 2007-04-12 15:18:28 alexander Exp $ - */ -package com.gentics.contentnode.object.parttype; - -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - * Abstract base class for all compatibility part types - */ -public abstract class AbstractVelocityCompatibilityPartType extends AbstractVelocityPartType { - - /** - * Read all text and cdata sections of node and append - * - * @param node The node from which to extract all text and cdata nodes - * @return The extracted template. - */ - protected static String getTemplateFromNode(Node node) { - - StringBuffer text = new StringBuffer(); - - // read children (text and cdata nodes) and aggregate - if (node.hasChildNodes()) { - NodeList children = node.getChildNodes(); - - for (int k = 0; k < children.getLength(); k++) { - Node item = children.item(k); - - if (item.getNodeType() == Node.CDATA_SECTION_NODE || item.getNodeType() == Node.TEXT_NODE) { - text.append(item.getNodeValue()); - } - } - } - - return text.toString(); - } - -} diff --git a/cms-core/src/main/java/com/gentics/contentnode/object/parttype/AbstractVelocityPartType.java b/cms-core/src/main/java/com/gentics/contentnode/object/parttype/AbstractVelocityPartType.java deleted file mode 100644 index fa0b78f98f..0000000000 --- a/cms-core/src/main/java/com/gentics/contentnode/object/parttype/AbstractVelocityPartType.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * @author alexander - * @date 11.04.2007 - * @version $Id: AbstractVelocityPartType.java,v 1.6 2010-11-16 12:46:24 norbert Exp $ - */ -package com.gentics.contentnode.object.parttype; - -import java.io.IOException; -import java.io.Writer; -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.velocity.Template; -import org.apache.velocity.app.Velocity; -import org.apache.velocity.context.Context; -import org.apache.velocity.exception.MethodInvocationException; -import org.apache.velocity.exception.ParseErrorException; -import org.apache.velocity.exception.ResourceNotFoundException; -import org.apache.velocity.runtime.resource.loader.StringResourceLoader; -import org.apache.velocity.runtime.resource.util.StringResourceRepository; - -import com.gentics.api.contentnode.parttype.AbstractExtensiblePartType; -import com.gentics.api.lib.exception.NodeException; -import com.gentics.contentnode.factory.TransactionManager; -import com.gentics.contentnode.object.Tag; -import com.gentics.contentnode.render.RenderType; -import com.gentics.lib.etc.StringUtils; -import com.gentics.lib.log.NodeLogger; -import com.gentics.lib.render.velocity.SerializableVelocityTemplateWrapper; - -/** - * Abstract navigation parttype providing common methods for all navigation - * parttypes and velocity parttype. Class could be separated into two classes, - * one for all navigation parttypes and one only for the velocity partttype. - */ -public abstract class AbstractVelocityPartType extends AbstractExtensiblePartType { - /** - * Sequence that is used as template name postfix. See {@link #getTemplateFromString(String)} for details. - */ - protected static final AtomicLong templateNamePostfixSequence = new AtomicLong(); - - /** - * Logger - */ - protected static NodeLogger logger = NodeLogger.getNodeLogger(AbstractVelocityPartType.class); - - /** - * Put string into string resource repository, read template from velocity, - * delete from string resource repository and return parsed template. - * Additionally, add velocity macros. - * - * The name of the template will be made unique by adding a new value of {@link #templateNamePostfixSequence}. - * Uniqueness of templates is important so that the velocimacros of the template can safely be removed from the velocimacro factory, - * When the {@link SerializableVelocityTemplateWrapper} instance of the template is garbage collected. - * @param template The template as string. - * @return The template object constructed from the string. - */ - protected Template getTemplateFromString(String template) throws Exception { - // use the current thread's name as part of the template name, to - // separate the velocimacros (template name is the "namespace" of - // locally defined velocimacros) - // Additionally, we add the tag id to the template name, so that different velocity tags do not interfer - RenderType renderType = TransactionManager.getCurrentTransaction().getRenderType(); - Tag tag = renderType.getTopmostTag(); - - StringBuilder templateNameBuilder = new StringBuilder(); - - if (tag == null) { - templateNameBuilder.append("Internal Template"); - } else { - templateNameBuilder.append("Tag Template ").append(tag.getName()); - } - templateNameBuilder.append("-").append(templateNamePostfixSequence.incrementAndGet()); - String templateName = templateNameBuilder.toString(); - StringResourceRepository srr = StringResourceLoader.getRepository(); - - srr.putStringResource(templateName, template); - Template tmp = Velocity.getTemplate(templateName); - - srr.removeStringResource(templateName); - - return tmp; - } - - /** - * Parse the template given by the parameters. - *
    - *
  1. Check whether the template has been cached (cache key is the md5 sum of the template source)
  2. - *
  3. Call {@link #getTemplateFromString(String)} to parse the template source into a Template
  4. - *
  5. Wrap the Template object into a {@link SerializableVelocityTemplateWrapper} instance that is put in the cache and returned from this object
  6. - *
- * @param fullTemplate template source - * @return A Template object. - * @throws NodeException - */ - protected SerializableVelocityTemplateWrapper parseTemplate(String fullTemplate) throws NodeException { - // the md5Sum of the template will be used as cache key and part of its name - String md5Sum = StringUtils.md5(fullTemplate); - - // try to get parsed templates from portal cache - Object tmpTemplates = getCachedObject(md5Sum); - - if (tmpTemplates instanceof SerializableVelocityTemplateWrapper) { - logger.debug("Template found in cache."); - SerializableVelocityTemplateWrapper wrapper = (SerializableVelocityTemplateWrapper)tmpTemplates; - Template template = wrapper.getTemplate(); - - // template might be null as it is stored as transient in the - // wrapper - // if it is null, treat as cache miss - if (template != null) { - return wrapper; - } else { - logger.warn("Template cached, but null. Do not use disk-based cache for templates!"); - } - } - - Template tmp = null; - - try { - tmp = getTemplateFromString(fullTemplate); - } catch (Exception e) { - logger.error("StringResourceLoader didn't return a valid template. " + e.getMessage()); - throw new NodeException("StringResourceLoader didn't return a valid template. " + e.getMessage(), e); - } - - SerializableVelocityTemplateWrapper wrapper = new SerializableVelocityTemplateWrapper(tmp); - - putObjectIntoCache(md5Sum, wrapper); - - return wrapper; - } - - /** - * Render the template wrapped by the wrapper and make sure that the wrapper is not garbage collected while the template is still rendered - * @param wrapper wrapper - * @param context velocity context - * @param writer write to receive the rendered template - * @throws ResourceNotFoundException - * @throws ParseErrorException - * @throws MethodInvocationException - * @throws IOException - */ - protected void mergeTemplate(SerializableVelocityTemplateWrapper wrapper, Context context, Writer writer) - throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException { - wrapper.getTemplate().merge(context, writer); - - // special hack to avoid the instance of SerializableVelocityTemplateWrapper to - // be garbage collected while the template is still rendered. - // If the SerializableVelocityTemplateWrapper is garbage collected, the finalize() method would dump the VM namespace of the template - // to remove the local inline macros from the Velocity store (this is done to avoid memory leaks) - // if this happens while the template is rendered, the macros would not be resolved any more. - // accessing the config object after the call to getTemplate().merge() above will keep the reference, so the SerializableVelocityTemplateWrapper - // will not be eligible for garbage collection to an inapropriate moment. - wrapper.toString(); - } -} diff --git a/cms-core/src/main/java/com/gentics/contentnode/object/parttype/BreadcrumbCompatibilityPartType.java b/cms-core/src/main/java/com/gentics/contentnode/object/parttype/BreadcrumbCompatibilityPartType.java deleted file mode 100644 index 63cb614c4a..0000000000 --- a/cms-core/src/main/java/com/gentics/contentnode/object/parttype/BreadcrumbCompatibilityPartType.java +++ /dev/null @@ -1,860 +0,0 @@ -/* - * @author alexander - * @date 14.03.2007 - * @version $Id: BreadcrumbCompatibilityPartType.java,v 1.13 2009-12-16 16:12:12 herbert Exp $ - */ -package com.gentics.contentnode.object.parttype; - -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.exception.MethodInvocationException; -import org.apache.velocity.exception.ParseErrorException; -import org.apache.velocity.exception.ResourceNotFoundException; -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import com.gentics.api.lib.etc.ObjectTransformer; -import com.gentics.api.lib.exception.NodeException; -import com.gentics.api.lib.exception.UnknownPropertyException; -import com.gentics.api.lib.resolving.PropertyResolver; -import com.gentics.api.lib.resolving.Resolvable; -import com.gentics.contentnode.render.RenderableResolvable; -import com.gentics.lib.etc.StringUtils; -import com.gentics.lib.log.NodeLogger; - -/** - * This parttype implements the compatibility breadcrumb navigation. - */ - -public class BreadcrumbCompatibilityPartType extends AbstractVelocityCompatibilityPartType { - - /** - * Static logger - */ - protected static NodeLogger logger = NodeLogger.getNodeLogger(BreadcrumbCompatibilityPartType.class); - - /** - * Static type code for folders. - */ - protected static final int TYPE_FOLDER = 10002; - - /** - * Name of input parameter for startfolder - */ - protected static final String INPUT_STARTFOLDER = "startfolder"; - - /** - * Default value for startfolder - */ - protected static final String INPUT_STARTFOLDER_DEFAULT = "node.folder"; - - /** - * Name of input parameter for template - */ - public static final String INPUT_TEMPLATE = "templates"; - - /** - * Name of input parameter for tagname_hidden - */ - protected static final String INPUT_TAGNAMEHIDDEN = "tagname_hidden"; - - /** - * Default value for tagname_hidden - */ - protected static final String INPUT_TAGNAMEHIDDEN_DEFAULT = "navhidden"; - - /** - * Name of input parameter for disable_fallback - */ - protected static final String INPUT_DISABLEFALLBACK = "disable_fallback"; - - /** - * Default value for disable_fallback 0 ... use fallback to default language - * 1 ... cut (end breadcrumb if language not available) 2 ... skip (skip - * folder if language not available) - */ - protected static final String INPUT_DISABLEFALLBACK_DEFAULT = "0"; - - /** - * Name of input parameter for disable_activepage - */ - protected static final String INPUT_DISABLEACTIVEPAGE = "disable_activepage"; - - /** - * Default value for disable_activepage - */ - protected static final boolean INPUT_DISABLEACTIVEPAGE_DEFAULT = false; - - /** - * Name of input parameter for startpage (of folder) compatibility mode - */ - protected static final String INPUT_TAGNAME_STARTPAGE = "tagname_startpage2"; - - /** - * Default value for startpage of folder - */ - protected static final String INPUT_TAGNAME_STARTPAGE_DEFAULT = "object.startpage"; - - /** - * Name of input parameter for startfolder - */ - protected static final String INPUT_LANGUAGECODE = "languagecode"; - - /** - * Default value for startfolder - */ - protected static final String INPUT_LANGUAGECODE_DEFAULT = ""; - - /** - * Name of input parameter for disable_hidden - */ - protected static final String INPUT_DISABLEHIDDEN = "disable_hidden"; - - /** - * Default value for disable_hidden - */ - protected static final boolean INPUT_DISABLEHIDDEN_DEFAULT = false; - - /** - * Name of input parameter for page - */ - protected static final String INPUT_PAGE = "page"; - - /** - * Name of attribute for folder of page - */ - protected static final String NAV_FOLDER = "folder"; - - /** - * Name of attribute for parent - */ - protected static final String NAV_PARENT = "parent"; - - /** - * Name of attribute for translated name - */ - protected static final String NAV_NAME_LANGUAGE = "object.name_"; - - /** - * Name of attribute for name - */ - protected static final String NAV_NAME = "name"; - - /** - * Name of attribute for URL - */ - protected static final String NAV_URL = "url"; - - /** - * Name of attribute for ID - */ - protected static final String NAV_ID = "id"; - - /** - * Name of attribute for objecttype - */ - protected static final String NAV_OBJECTTYPE = "ttype"; - - /** - * Name of attribute for language variants - */ - protected static final String NAV_LANGUAGES = "languageset.pages."; - - /** - * Render the navigation. Gets all needed input parameters and starts - * rendering at startpage. Parse old-style templates from XML. - * @throws NodeException - */ - public String render() throws NodeException { - logger.info("Start rendering breadcrumb."); - - ConfigObject config = getInitParameters(); - - Iterator pathIterator = config.path.iterator(); - StringWriter outwriter = new StringWriter(); - - // compatibility breadcrumb starts counting at 1 - int level = 1; - - while (pathIterator.hasNext()) { - Object folder = pathIterator.next(); - - if (folder instanceof Resolvable) { - // create the corresponding nav object - NavObject nav = new NavObject(new RenderableResolvable((Resolvable) folder), level, config); - - // check for hidden folder - if (nav.getHidden()) { - continue; - } - - if ("".equals(nav.getName())) { - if (config.disableFallback == 1) { - // cut navigation - logger.debug("Disable fallback == 1, cutting navigation."); - break; - } else if (config.disableFallback == 2) { - // skip item - logger.debug("Disable fallback == 2, skipping item."); - continue; - } - } - renderObject(outwriter, nav, level, config); - level++; - } - } - - logger.info("End rendering breadcrumb."); - if (logger.isDebugEnabled()) { - logger.debug("Breadcrumb: " + outwriter.toString()); - } - - return outwriter.toString(); - } - - /** - * Read all needed init parameters using the resolve() method. Populates - * instance variables. - * @throws NodeException - */ - protected ConfigObject getInitParameters() throws NodeException { - - logger.debug("Start reading configuration."); - - ConfigObject config = new ConfigObject(); - - // get startfolder from input parameters - Object tmpStartfolder = resolve(INPUT_STARTFOLDER); - - if (tmpStartfolder instanceof Resolvable) { - config.startfolder = (Resolvable) tmpStartfolder; - } - - // if no startfolder specified, use default node.folder - if (config.startfolder == null) { - config.startfolder = (Resolvable) resolve(INPUT_STARTFOLDER_DEFAULT); - } - - // if still no startfolder, something has gone wrong - if (config.startfolder == null) { - logger.error("No startfolder set and couldn't find default start folder."); - throw new NodeException("No startfolder set and couldn't find default start folder."); - } - - // get template - config.template = ObjectTransformer.getString(resolve(INPUT_TEMPLATE), ""); - if ("".equals(config.template)) { - logger.error("No templates found."); - throw new NodeException("No templates found."); - } - - // get disable_activepage flag - // default to false - config.disableActivepage = ObjectTransformer.getBoolean(resolve(INPUT_DISABLEACTIVEPAGE), INPUT_DISABLEACTIVEPAGE_DEFAULT); - - // get tagname_hidden - // default to "navhidden" - config.tagnameHidden = ObjectTransformer.getString(resolve(INPUT_TAGNAMEHIDDEN), INPUT_TAGNAMEHIDDEN_DEFAULT); - if (config.tagnameHidden == null || "".equals(config.tagnameHidden)) { - config.tagnameHidden = INPUT_TAGNAMEHIDDEN_DEFAULT; - } - - // get languagecode - // default to "" - config.languagecode = ObjectTransformer.getString(resolve(INPUT_LANGUAGECODE), INPUT_LANGUAGECODE_DEFAULT); - if (config.languagecode == null || "".equals(config.languagecode)) { - config.languagecode = INPUT_LANGUAGECODE_DEFAULT; - } - - // get disable_fallback - String tmpDisableFallback = ObjectTransformer.getString(resolve(INPUT_DISABLEFALLBACK), INPUT_DISABLEFALLBACK_DEFAULT); - - config.disableFallback = 0; - if ("2".equals(tmpDisableFallback) || "skip".equalsIgnoreCase(tmpDisableFallback)) { - config.disableFallback = 2; - } else if ("1".equals(tmpDisableFallback) || "yes".equalsIgnoreCase(tmpDisableFallback) || "true".equalsIgnoreCase(tmpDisableFallback)) { - config.disableFallback = 1; - } - - // get tagname_startpage - config.tagnameStartpage = ObjectTransformer.getString(resolve(INPUT_TAGNAME_STARTPAGE), INPUT_TAGNAME_STARTPAGE_DEFAULT); - if (config.tagnameStartpage == null || "".equals(config.tagnameStartpage)) { - config.tagnameStartpage = INPUT_TAGNAME_STARTPAGE_DEFAULT; - } - - // get disable_hidden - config.disableHidden = ObjectTransformer.getBoolean(resolve(INPUT_DISABLEHIDDEN), INPUT_DISABLEHIDDEN_DEFAULT); - - // get current page - Object tmpCurrentPage = resolve(INPUT_PAGE); - - if (tmpCurrentPage instanceof Resolvable) { - config.currentPage = (Resolvable) tmpCurrentPage; - } else { - logger.warn("Current page not found."); - } - - // get current folder - if (config.currentPage != null) { - Object tmpCurrentFolder = config.currentPage.get(NAV_FOLDER); - - if (tmpCurrentFolder instanceof Resolvable) { - config.currentFolder = (Resolvable) tmpCurrentFolder; - } else { - logger.error("Current folder could not be resolved."); - throw new NodeException("Current folder could not be resolved."); - } - } else { - logger.warn("Current folder could not be resolved."); - throw new NodeException("Current folder could not be resolved."); - } - - // get path from current page to startpage and add objects to vector - config.path = new Vector(); - Resolvable pathitem = config.currentFolder; - - while (!config.startfolder.equals(pathitem) && pathitem != null) { - config.path.add(pathitem); - Object parent = pathitem.get(NAV_PARENT); - - if (parent instanceof Resolvable) { - pathitem = (Resolvable) parent; - } else { - pathitem = null; - } - } - // add startfolder to path - if (config.startfolder.equals(pathitem)) { - config.path.add(pathitem); - } - - // reverse path vector - Collections.reverse(config.path); - - // parse old style templates - config.templates = parseTemplates(config.template); - - if (logger.isDebugEnabled()) { - logger.debug("End reading configuration." + config); - } - - return config; - } - - /** - * Parse old-style XML templates and transform to Velocity templates. - * @param inputTemplate All templates as one XML document. - * @return A HashMap containing all transformed templates, hashed by level - * and type. - * @throws NodeException If an exception occured during XML parsing. - */ - protected HashMap parseTemplates(String inputTemplate) throws NodeException { - - logger.debug("Start parsing templates."); - - // add surrounding block to make valid XML - inputTemplate = "" + inputTemplate + ""; - - // try to get parsed templates from portal cache - Object tmpTemplates = getCachedObject(inputTemplate); - - if (tmpTemplates instanceof HashMap) { - logger.debug("Templates found in cache."); - return (HashMap) tmpTemplates; - } - - logger.debug("Templates not found in cache, start parsing from XML."); - - // templates not cached, create new - HashMap templates = new HashMap(); - - try { - // Read XML input string into a DOM document - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new InputSource(new StringReader(inputTemplate))); - - // loop over all templates - NodeList nodeTemplates = document.getElementsByTagName("template"); - - for (int i = 0; i < nodeTemplates.getLength(); i++) { - - // read a template - Node node = nodeTemplates.item(i); - - // get template level - NamedNodeMap nodeAttributes = node.getAttributes(); - Node nodeLevel = nodeAttributes.getNamedItem("level"); - Integer templateLevel = Integer.valueOf(nodeLevel.getNodeValue()); - - // read subtemplates - NodeList nodeSubTemplates = node.getChildNodes(); - HashMap subTemplates = new HashMap(); - - for (int j = 0; j < nodeSubTemplates.getLength(); j++) { - - // read template - Node nodeSubTemplate = nodeSubTemplates.item(j); - - // check to see if node is an element - if (nodeSubTemplate.getNodeType() != Node.ELEMENT_NODE) { - continue; - } - - String elementName = nodeSubTemplate.getNodeName(); - String elementValue = getTemplateFromNode(nodeSubTemplate); - - // put into hashmap to store in cache - Template tmp = getTemplateFromString(convertVelocity(elementValue)); - - subTemplates.put(elementName, tmp); - } - templates.put(templateLevel, subTemplates); - } - - // put parsed templates into cache - putObjectIntoCache(inputTemplate, templates); - - logger.debug("End parsing templates."); - - // return templates - return templates; - - } catch (ParserConfigurationException pce) { - logger.error("ParserConfigurationException while parsing templates. " + pce.getMessage()); - throw new NodeException(pce.getMessage(), pce); - } catch (IOException ioe) { - logger.error("IOException while parsing templates. " + ioe.getMessage()); - throw new NodeException(ioe.getMessage(), ioe); - } catch (SAXException saxe) { - logger.error("SAXException while parsing templates. " + saxe.getMessage()); - throw new NodeException(saxe.getMessage(), saxe); - } catch (Exception e) { - logger.error("Exception while parsing templates. " + e.getMessage()); - throw new NodeException(e.getMessage(), e); - } - } - - /** - * Replace all